Reputation:
I want to use elisp to copy lines from a buffer. for example: copy line 100 to 200 text to another buffer.
Should I select the region (goto-line) then copy it? just like what we do with keyboard? Some post say do not use goto-line in elisp code. I don't know what's effective way to do it.
Upvotes: 0
Views: 553
Reputation: 20014
Here's a function copy-lines-from-buffer
that's similar to copy-to-buffer
except that it works with line numbers instead of points, and unlike copy-to-buffer
it does not erase the current contents of the target buffer:
(defun copy-lines-from-buffer (buffer start-line end-line)
"Copy the text from START-LINE to END-LINE from BUFFER.
Insert it into the current buffer."
(interactive "*bSource buffer: \nnStart line: \nnEnd line: ")
(let ((f #'(lambda (n) (goto-char (point-min))
(forward-line n)
(point))))
(apply 'insert-buffer-substring buffer
(with-current-buffer buffer
(list (funcall f start-line) (funcall f end-line))))))
The copy-lines-from-buffer
function takes either a buffer or buffer name as its first argument, the start line number as its second argument, and the end line number as its third. It creates a local helper function f
that returns point at the beginning of line n
of the current buffer, and it calls f
twice with the current buffer set to buffer
to create a list consisting of the starting point and ending point of the desired buffer contents. It then uses apply
to invoke insert-buffer-substring
with buffer
and the buffer contents start and end points as arguments.
Call copy-lines-from-buffer
from the point in your buffer where you want the contents to be inserted. The contents of the start line are included in the copied content, but the contents of the end line are not included.
Upvotes: 0