Elisp: Cut Copy Paste to/from kill-ring

By Xah Lee. Date: . Last updated: .

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.

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")


(defun my-copy-all ()
  "Put the whole buffer content into the `kill-ring'.
(respects `narrow-to-region')"
  (kill-new (buffer-string))
  (message "Buffer content copied."))

Paste from Kill Ring

;; paste from kill-ring

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."
  (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
Patreon me $5 patreon

Or Buy Xah Emacs Tutorial

Or buy a nice keyboard: Best Keyboard for Emacs

If you have a question, put $5 at patreon and message me.