emacs: inserting numbers into a column of text

On Oct 2, 7:05 am, Benjamin wrote:
> I use keyboard macros fairly frequently, but I often run into a
> situation where I would like to increment a number in the macro, e.g.,
> if I start with:
> tmp tmp tmp tmp
> and I want to end with:
> tmp1
> tmp2
> tmp3
> tmp4
> I know how to create the macro where it would result in:
> tmp1
> tmp1
> tmp1
> tmp1
> Is there a way to make the number increment each time the macro is
> executed?
> Otherwise I am forced to step down through each line and manually put
> the numbers in 1, 2, 3, 4, ...
> Naturally this is a greatly shortened example for illustration
> purposes, and often the incrementing takes place within a longer
> statement e.g., tmp(:,1) = function(x,y). My interest here is how to
> increment or decrement the number in a more automatic fashion.
> I don't mind doing something other than macros, or even external
> commands (perl/sed/awk, etc.)
> to assist with this.

This is a frequently asked question in emacs communities.

Different people has different solution. For me, i wrote a function to do it. I documented it in this page:

• Emacs Lisp Examples

The following is excerpt:
Sometimes, you need to insert a vertical column of sequential integers into a block of text, like this:

do this x times
do this x times
do this x times

where the “x” should be 1, 2, 3, ... The following code does it.

(defun insert-counter-column (n)
"Insert a sequence of integers vertically.
do this 1 times
do this 2 times
do this 3 times

If there are not enough existing lines after the cursor
when this function is called, it aborts at the last line.

See also: `kill-rectangle' and `string-rectangle'."
(interactive "nEnter the max integer: ")
(let ((i 1) colpos)
(setq colpos (- (point) (point-at-bol)))
(while (<= i n)
(insert (number-to-string i))
(next-line) (beginning-of-line) (forward-char colpos)
(setq i (1+ i))


Note: if you are a perl programer (or python, ruby, etc), you can easily write a function in your lang and have a emacs wrapper calling it. So that, you select you text, press a hotkey, and emacs call your script, feed it the current selection, and return the output replacing the current text selection.

This might be easier for many people.

• Elisp Wrapper For Perl Scripts

∑ http://xahlee.org/

No comments:

Post a Comment