How would you go about writing a file from emacs that contains only the line numbers eg:
1
2
3
4
5
Ideally this would be a command that you would execute (how?) that can be told how many lines to print. Is this possible?
Here's a quick elisp function that does it:
(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"))))
You would run it with (write-line-numbers 8)
in elisp or with M-x write-line-numbers 8 interactively.
Or you could save the above as a script and run emacs like so:
emacs -Q --script write-line-numbers.el --eval '(write-line-numbers 8)'
But as Moritz points out, there are better ways to do this outside of emacs.
.emacs
in your home directory and restart emacs. Or type it into any buffer and run eval-last-sexp
(C-x C-e
) when the point is just after the final paren. Yet another way is to run eval-expression
(M-:
) and type it in at the prompt. The last two methods won't persist between emacs sessions - ataylor 2012-04-04 15:08
Why don't you use the shell program seq
for it? E.g. seq 20
will print 20 neat lines numbered 1 to 20.
M-: (with-temp-file "foo.txt" (dotimes (i 15) (insert (format "%2d\n" (1+ i)))))
If you do this often enough, make it a function:
(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))))))
dotimes
approach, you could also usenumber-sequence
andmapconcat
to generate the content for the file as follows:(mapconcat 'number-to-string (number-sequence 1 5) "\n")
- phils 2012-04-04 10:27