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: Emacs: Copy/Cut Current Line If No Selection

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: Emacs: Copy/Cut Current Line If No Selection

If you already have a string, use kill-new

;; push a string into kill-ring
(kill-new "dragon dragon")

Full example:

(defun xah-copy-all ()
  "Put the whole buffer content into the `kill-ring'.
(respects `narrow-to-region')
URL `http://ergoemacs.org/emacs/elisp_cut_copy_yank_kill-ring.html'
Version 2015-05-06"
  (interactive)
  (kill-new (buffer-string))
  (message "Buffer content copied."))

How to paste from kill-ring?

;; paste from kill-ring
(yank)

How to mark a region?

To mark a region, do (push-mark my positon). The current cursor positon to my positon will become the new region.

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

Full example: Emacs: Extend Selection, Select Text in Quote, Select Line, Select Block

Like it?
Buy Xah Emacs Tutorial
or share
blog comments powered by Disqus