4

From the documentation of string-width string:

This function returns the width in columns of the string string, if it were displayed in the current buffer and the selected window.

For me this imply that (string-width "1\n12\n123") should return 3, while in reality it returns 6.

I can accept this (even though in my opinion this behavior contradicts documentation), but I also would like to know if there is an easy way to find

the width in columns of the string string, if it were displayed in the current buffer and the selected window.

I can imagine implementation when I first split string with \n, then find string-width for each piece and take maximum, but, somehow, I don't like this solution very much.

vonaka
  • 171
  • 7
  • 1
    The result of `6` is correct. Absent a modification of the `buffer-display-table`, you have `1`, which is one column; you have `12`, which are two columns, and you have `123`, which are three columns, giving a grand total of `6` columns. – lawlist Aug 29 '18 at 01:52
  • You probably want `(length (split-string "1\n12\n123" "\n"))` if the result desired is `3`? – lawlist Aug 29 '18 at 01:59
  • Thanks, @lawlist. It must be misunderstanding of mine. For me `the width in columns of the string, if it were displayed` is the length (in columns) of the longest line. Here the desired number is `3`, because when you display that string the width of the text will be `3`, I mean, you can't cross the sixth column in the buffer. So, no, `(length (split-string "1\n12\n123" "\n"))` is not what I want, as it count the number of lines. – vonaka Aug 29 '18 at 07:35
  • Technically, it's possible to modify the display of `\n`, thus you can't split the string by `\n` in this situation. – xuchunyang Aug 30 '18 at 12:08

1 Answers1

3

As can be inferred from the question, a possible answer would be:

(apply #'max (mapcar #'string-width (split-string STR "\n")))

but this may still not be sufficient depending on your particular needs (e.g. do you need to take into account proportional fonts, or possible presence of images, or ...), so you may like to expand your question by explaining what you intend to do with that information.

Stefan
  • 26,154
  • 3
  • 46
  • 84
  • Thanks, in fact, in my little experiments I don't need this width any more, so, now, it is more theoretical (or educational) question than practical. But, still, if you know the solution for proportional fonts (but without images -- this is too much) I'll be grateful. – vonaka Aug 31 '18 at 08:35
  • I imagine that doing something different in the presence of proportional fonts is outside the scope of `string-width`, since after all, it promises to return a number of *columns*. If you want the width of a string in *pixels* or some other physical unit, that is a different question. – Harald Hanche-Olsen Aug 31 '18 at 13:30