Emacs Lisp Idioms: How to Cut/Copy/Paste to/from kill-ring?

Buy Xah Emacs Tutorial. Master emacs benefits for life.
, , …,

How to cut text to kill-ring?

;; cut text between buffer positions and push it to kill-ring.
(kill-region 247 528)

Full example:

(defun xah-cut-line-or-region ()
  "Cut the current line, or current text selection."
  (interactive)
  (if (use-region-p)
      (kill-region (region-beginning) (region-end))
    (kill-region (line-beginning-position) (line-beginning-position 2)) ) )

Note: User's kill-ring content should not change unexpectedly. Emacs lisp function should not use the kill-ring as temp storage area for itself. If your command is specifically designed to put text to the kill-ring so that user can paste it later, then good. Else, just save text to a variable for your elisp program's use.

How to copy text to kill-ring?

;; copy text between buffer positions and push it to kill-ring.
(kill-ring-save 247 528)

Full example:

(defun xah-copy-line-or-region ()
  "Copy current line, or current text selection."
  (interactive)
  (if (use-region-p)
      (kill-ring-save (region-beginning) (region-end))
    (kill-ring-save (line-beginning-position) (line-beginning-position 2)) ) )

If you already have a string, use kill-new

;; push a string into kill-ring
(kill-new myString)

Full example:

(defun xah-copy-all ()
  "Put the whole buffer content into the kill-ring.
If narrow-to-region is in effect, then copy that region only."
  (interactive)
  (kill-new (buffer-string))
  (message "Buffer content copied copy-region-as-kill"))

How to paste from kill-ring?

;; paste from kill-ring
(yank)

How to mark a region?

To mark a region, simply (push-mark my positon). The current cursor positon to my positon will become the new region. You can change the cursor position by goto-char.

to make the region active, use (setq mark-active t). 〔➤ Emacs: What's Region, Active Region, transient-mark-mode?

Full example:

(defun xah-select-inside-quotes ()
  "Select text between double straight quotes
on each side of cursor."
  (interactive)
  (let (p1 p2)
    (skip-chars-backward "^\"")
    (setq p1 (point))
    (skip-chars-forward "^\"")
    (setq p2 (point))

    (goto-char p1)
    (push-mark p2)
    (setq mark-active t)
  )
)
Like it?
Buy Xah Emacs Tutorial
or share
blog comments powered by Disqus