Search code examples
emacsemacs24

How to attach character to the next N lines using Emacs?


Using emacs24 I'd like to attach for example # at the beginning of the next five lines. So having this:

Line1
line2
line3

get this:

#Line1
#line2
#line3

for the number of lines that I specify. How can I do that? Thanks!


Solution

  • While there may be something built in to Emacs that does this, and you can certainly write a little Lisp to get it done, I would usually use "rectangular editing" features to get this done. Imagine that the buffer contains the following, with . representing the point (where your cursor is)

    .Line1
    line2
    line3
    

    Set the mark

    Press C-n twice. This is the state of the buffer now:

    Line1
    line2
    .line3
    

    Press C-x r t.

    Type #.

    Press enter.

    I would find this much more natural than entering a value for the number of times to repeat a command, because you can visually select the lines you want to edit. YMMV

    Edit

    Here's how to do this using a bit of Emacs Lisp. Note that although I've been using Emacs for a few years now, I only recently began learning how to actually use Emacs Lisp, so this code might not be that great! It does get the job done.

    (defun insert-n-times (s n)
      (interactive "Mstring:\nNtimes:")
      (while (> n 0)
        (insert s)
        (goto-char (- (point) 1))
        (next-line)
        (setq n (- n 1))))
    

    Use it by doing the following: M-x insert-n-times RET <type a string> RET <type a number>