Emacs Lisp: 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")


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

How to paste from kill-ring?

;; paste from kill-ring

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 Emacs: What's Region, Active Region, transient-mark-mode?

(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

Like it? Buy Xah Emacs Tutorial. Thanks.

or, buy something from Best Keyboard for Emacs