Search code examples
emacscommandelispcopy-paste

Define a copy-section command in Emacs


I would like to set up a command that put the content of the lines between two § characters without moving the point (not including the lines containg the §).

Here is my current attempt

(defun copy-section ()
  "Copy current section, that is lines between two §."
  (interactive)
  (save-excursion
      (when (not (search-backward-regexp "§" nil t))
        (goto-char (point-min)) )
      (forward-line 1)
      (when (not (search-forward-regexp "§" nil t))
        (goto-char (point-max)) )
      (move-beginning-of-line nil)
      (kill-ring-save (mark) (point)) ) )

It works well but the remarks in the documentation about moving around the mark being bad style make me think taht there is a better way to achieve the same result. Does saving position into variable (which I do not know how to do it) allows for a cleaner function.

Part of the code above comes from ergoemacs.


Solution

  • No "regexp" form needed as only a char is looked for

    (defun copy-section ()
      "Copy current section, that is lines between two §."
      (interactive)
      (save-excursion
        (let* ((start (and (search-backward "§" nil t)
                           (forward-line 1)
                           (point)))
               (end (progn (and start (search-forward "§" nil t))
                           (forward-line -1)
                           (end-of-line)
                           (point))))
          (and start end (kill-new (buffer-substring-no-properties start end))))))