Chen Yangjian's Blog

Carpe diem - Seize the day

Emacs 里头显示行号

| Comments

看了个 jQuery for Designers 的视频,觉得让 Emacs 也显示行号也是个不错的想法,于是开搞。 办法倒也简单,得益于 Emacs 的社区贡献的插件, 我只要选择 linum.el、lineno.el、setnul.el 等其中之一就行了, EmacsWiki 上有个关于行号的文档,可以看看。

然而选择虽多,它们都有各自的问题。lineno.el 加载很快,只更新被显示的区块的行号, 然而除此之外都很不合吾意,样式不好看,滚屏的时候刷新有延迟,等等;setnu.el 加载大文件 (比如 undergroud.txt,19226 行) 的时候很慢,Emacs 就僵在那儿了;linum.el 是我最满意的,样式也能凑合,加载速度也快。 不过就一个地方不太好,左手边行号的宽度它是计算出来的,行数较少的时候显示行号的区块很窄, 我觉得不好看,所以 linum-update-window 函数中计算显示格式的部分我加了一句:

(when (< w 6) (setq w 6))

不过根据 ChrisDone 的回复:

Putting the following in your .emacs yields almost the same result without modification of linum.el:

`(setq linum-format "%d ")`

Or you can set it as a function like the following if you’d like it right justified. The body of the function is modified from linum-0.9x.

(setq linum-format (lambda (line)

  (propertize (format (let ((w (length (number-to-string (count-lines (point-min) (point-max))))))
                      (concat "%" (number-to-string w) "d ")) line)
              'face 'linum)))

You can use ‘linum-before-numbering-hook’ to count and store the number of lines only once per update. Thus you can avoid the somewhat expensive ‘count-lines’ call for each updated line. And a more simplistic constant-width version of the above could look like: (setq linum-format "%6d ")

直接一点反而省事,反正超过 99999 行的文本文件我是不想用 Emacs 马上打开的…… 原谅我后来才注意到 linum-format 选项……

Comments