如何让Emacs将行号写入文件?

3
你如何在emacs中写一个只包含行数的文件呢?例如:
1
2
3
4
5

理想情况下,您可以执行一个命令(如何执行?),并告诉它要打印多少行。这是可能的吗?

2
作为“dotimes”方法的替代方案,您还可以使用“number-sequence”和“mapconcat”生成文件内容,代码如下:(mapconcat 'number-to-string (number-sequence 1 5) "\n") - phils
3个回答

6
这里是一个快速的elisp函数,可以实现此功能:
(defun write-line-numbers (n)
  (interactive "nNumber of lines: ")
  (save-excursion
    (with-output-to-temp-buffer "*lines*"
      (dotimes (line n)
        (princ (format "%d\n" (1+ line))))
      (set-buffer "*lines*")
      (write-file "lines.txt"))))

你可以在elisp中使用(write-line-numbers 8)运行它,也可以通过交互式方式使用M-x write-line-numbers 8来运行。
或者你可以将上述内容保存为脚本,并像这样运行emacs:
emacs -Q --script write-line-numbers.el --eval '(write-line-numbers 8)'

但是正如Moritz所指出的,除了emacs之外还有更好的方法来完成这个任务。


抱歉,我对emacs完全是新手,但我应该在哪里编写elisp函数?如何使这些类型的函数在emacs中可用? - user1098798
将其放入您的主目录下的.emacs文件中并重新启动emacs。或者在任何缓冲区中输入它,并在光标位于最后一个括号之后时运行eval-last-sexpC-x C-e)。另一种方法是运行eval-expressionM-:)并在提示符处键入它。后两种方法不会在emacs会话之间持久保存。 - ataylor

3

为什么不使用shell程序seq呢?例如:seq 20将打印出20个整洁的行,编号从1到20。


我已经为你点赞了,但并没有接受这个答案。你的回答非常有用,但我更感兴趣的是了解Emacs的工作原理,所以即使这可能不是用最简单的方法添加行号,我仍然想知道如何使用Emacs来做到 :) - user1098798

2

M-: (with-temp-file "foo.txt" (dotimes (i 15) (insert (format "%2d\n" (1+ i)))))

如果您经常这样做,请将其封装为一个函数:

(defun write-sequence (length output-file)
  (interactive "nLength of sequence: \nFOutput file: ")
  (with-temp-file output-file
    (dotimes (i length) (insert (format "%d\n" (1+ i))))))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接