Emacs: Copy this line

Emacs tends to mark from point (cursor) towards either end of the element. If you want a function that marks or copies the entire element from beginning to end, you often have to build them yourself.

Here is a function to copy the current line. It is most appropriate for prose — the function copies only the text. It does not copy the final newline and it disregards the leading and trailing spaces on the line.

(defun copy-this-line (&optional N)
  "Copy current line from first letter to last, i.e. without leading
or trailing whitespace. With a numerical argument, copy another line
as per relative line numbering."
  (interactive "P")
  (save-excursion
    (if (equal N nil)
        (kill-new
         (string-trim
          (filter-buffer-substring
           (progn
             (back-to-indentation)
             (point))
           (line-end-position))))
      (kill-new
       (string-trim
        (filter-buffer-substring
         (progn
           (forward-line (prefix-numeric-value N))
           (back-to-indentation)
           (point))
         (line-end-position)))))))

With an explicit numerical argument 1, the function copies one line below (towards the end of the document). With a negative argument, the function copies a line before the current line.

Leave a Reply

Your email address will not be published. Required fields are marked *