Search code examples
emacselisp

Programmatically detect if any line in a buffer is wrapping?


I have an idea for a possibly cool/probably stupid emacs script which would dynamically resize text to fill available space.

One thing I can't seem to figure out is how to query the current buffer to see if any lines are currently being wrapped. How would I do it?


Solution

  • You can check if any lines are wrapped in the current buffer with function like this:

    (defun wrapped-lines-p ()
      (save-excursion
        (goto-char (point-min))
        (let ((long-line-regexp 
               (format "^.\\{%d\\}.+$" (window-body-width))))
          (search-forward-regexp long-line-regexp nil t))))
    

    As noted in the comments, this doesn't take into account the buffer's font size. Since buffers can have a mix of different sized fonts, the window text pixel size needs to be tested. Try this:

    (defun wrapped-lines-p ()
      (let ((window-width-pixels (window-body-width nil t)))
        (> (car (window-text-pixel-size nil nil nil (1+ window-width-pixels)))
           window-width-pixels)))