以编程方式检测缓冲区中是否有任何行正在换行?

Programmatically detect if any line in a buffer is wrapping?

我有一个可能 cool/probably 愚蠢的 emacs 脚本的想法,它会动态调整文本大小以填充可用 space。

我似乎无法弄清楚的一件事是如何查询当前缓冲区以查看当前是否有任何行正在换行。我该怎么做?

请注意 "any lines are currently being wrapped" 是 window 的 属性,而不是 缓冲区 .

给定一个 window,您可以从顶部可见行扫描到底部并将行长度与 window-width:

进行比较
(defun window-long-lines-p ()
  "Return t is any visible line in the current window is longer than window width."
  (save-excursion
    (move-to-window-line -1)
    (let ((end (point)) here
          found-long-line)
      (move-to-window-line 0)
      (while (and (not found-long-line)
                  (< (setq here (point)) end))
        (when (< (window-width)
                 (- (progn (forward-line 1)
                           (point))
                    here))
          (setq found-long-line t)
          (message "long line: %d" (1- (line-number-at-pos)))))
      found-long-line)))

您可以使用如下函数检查当前缓冲区中是否包含任何行:

(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))))

如评论中所述,这没有考虑缓冲区的字体大小。由于缓冲区可以混合使用不同大小的字体,因此需要测试 window 文本像素大小。试试这个:

(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)))