Elisp: Cut Copy Paste to/from kill-ring

By Xah Lee. Date: . Last updated: .

How to cut text to kill-ring?

;; delete text between buffer positions and push 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?

;; push text between buffer positions to kill-ring
(kill-ring-save 247 528)

If you already have a string, use kill-new

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

Example:

(defun my-copy-all ()
  "Put the whole buffer content into the `kill-ring'.
(respects `narrow-to-region')"
  (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). 〔►see Elisp: Region, Active Region

(defun my-select-text-in-quote ()
  "Select text between the nearest left and right quotes."
  (interactive)
  (let ($pos
        ($skipChars "^\""))
    (skip-chars-backward $skipChars)
    (setq $pos (point))
    (skip-chars-forward $skipChars)
    (push-mark $pos)
    (setq mark-active t)))

More examples: Emacs: Select Line, between Quotes, Extend Selection

Writing Emacs Command

  1. Elisp: How to Write Commands
  2. Elisp: Region, Active Region
  3. Elisp: Get Buffer String
  4. Elisp: Functions on Line
  5. Elisp: Cut Copy Paste to/from kill-ring
  6. Elisp: Get User Input
  7. Elisp: Get universal-argument
  8. Elisp: Find Replace String in Buffer
  9. Elisp: Using thing-at-point
Like it? Buy Xah Emacs Tutorial. Thanks.