How can I use emacs string-insert-rectangle operation to add a vector of numbers to a series of lines? For example, I\'ve got this shortened version of a bunch of text entri
Here is a log of how you can solve it with a keyboard macro. AFAIK you can't solve this with just string-insert-rectangle
.
Where a register input is required, I used a
C-1 C-x r n
number-to-register
C-x ( kmacro-start-macro
C-M-f forward-sexp [3 times]
C-M-b backward-sexp
C-u C-x r i
insert-register
C-x r + increment-register
C-x ) kmacro-end-macro
C-SPC set-mark-command
M-> end-of-buffer
C-x C-k r apply-macro-to-region-lines
I think the simplest solution is to mark the first character of the original third column in the first line, move point to the same character of the last line, and then type:
C-uC-xrNRET id%d
RET
rectangle-number-lines is an interactive compiled Lisp function in `rect.el'.
It is bound to C-x r N.
(rectangle-number-lines START END START-AT &optional FORMAT)
Insert numbers in front of the region-rectangle.
START-AT, if non-nil, should be a number from which to begin counting. FORMAT, if non-nil, should be a format string to pass to `format' along with the line count. When called interactively with a prefix argument, prompt for START-AT and FORMAT.
The regexp-replace and macro techniques are both superb general-purpose tools to know, but rectangle-number-lines is pretty much custom-built for this very question.
Edit: I hadn't noticed at the time, but it turns out that this is a new feature in Emacs 24. Earlier versions of Emacs will translate that sequence to C-x r n
(lower-case n) which runs an entirely different function.
This is a way to do it in emacs, unfortunately, this approach doesn't use string-insert-rectangle. Also, this approach rudely assumes there are more than 10 characters on every line. Hilarity will ensue if that's not the case. M-x doit will invoke it.
(defun doit ()
(interactive)
(save-excursion
(beginning-of-buffer)
(let ((n 1))
(while (< (point) (point-max))
(forward-char 10)
(insert "id" (int-to-string n) " ")
(end-of-line)
(forward-line)
(incf n)))))
You can use query-replace-regexp
directly, by adding a new column with the match count \#
.
The matches look for 3 columns separated by spaces, which will be stored in submatch strings \1
to \3
. The replaced string adds a new column using the match count.
Version 1 (simpler, but starts at 0):
M-x query-replace-regexp RET
^\(\w+\)\ +\(\w+\)\ +\(\w+\)$ RET
\1 \2 id\# \3 RET
Note I used spaces for matching and replacing. You can use tabs instead.
Version 2 (uses lisp to customize the row count with the +1
function):
M-x query-replace-regexp RET
^\(\w+\)\ +\(\w+\)\ +\(\w+\)$ RET
\,(format "%s %s id%d %s" \1 \2 (+1 \#) \3) RET