Search code examples
emacselisp

Test for one long word greater than window-width


The screenshot below was generated using visual-line-mode. I am seeking to test whether a particular line could not be wrapped at word-end because the entire word exceeded the width of a window.

For example:  if the cursor is anywhere on line number 1, I would like to return t if point-at-bol to point-at-eol is both one long word that cannot be broken and it exceeds the window-width.

The same test should return nil if the cursor is anywhere on line 3.

I tried placing the cursor immediately before and immediately after the \ symbol in the right-hand margin and attempting to identify that character with what-cursor-position but that particular symbol is not reachable with that function. In other words, \ doesn't seem to occupy a (point) in the usual sense of testing a point at window edge.

Example
(source: lawlist.com)


Solution

  • The following function tests if the last word on the line is longer than the window width.

    (defun too-long-p ()
      "Returns t if last word on the line is longer than the window's
    column width."
      (save-excursion
        (end-of-line)
        (> (length (thing-at-point 'word))
           (window-total-width))))
    

    And here's a version that addresses the "both" issue you raised, but I suspect the former may be closer to what you want.

    (defun too-long-p ()
      "Returns t if last word on the line is longer than the window's
    column width."
      (save-excursion
        (beginning-of-line)
        (forward-word)
        (and (eolp)
             (> (length (thing-at-point 'word))
                (window-total-width)))))
    

    In response to the comments, try this one (although I can't recall if tabs break lines, so you may need to edit the regexp):

    (defun too-long-p ()
      "Returns t if last word on the line is longer than the window's
    column width."
      (save-excursion
        (beginning-of-line)
        (unless (re-search-forward "[ \t]"
                                   (+ (point-at-bol) (window-total-width)) t)
          (> (length (thing-at-point 'line)) (window-total-width)))))