Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected text in Emacs Lisp?

Tags:

emacs

elisp

I need to get selection as a string in my Emacs Lisp function.

like image 324
Pavel Chuchuva Avatar asked Feb 08 '10 04:02

Pavel Chuchuva


People also ask

How to select text in Emacs?

You can select blocks of text in Emacs just as you would in most other environments. You could, for example, drag your mouse over a region. You could also hold down the Shift key and use arrow keys.

How to select a word in Emacs?

Place the cursor on either side of the word, then hold the shift key down and hold the alt/option key down, and then use the left or right arrow.

Why does Emacs use Lisp?

Richard Stallman chose Lisp as the extension language for his rewrite of Emacs (the original used Text Editor and Corrector (TECO) as its extension language) because of its powerful features, including the ability to treat functions as data.


2 Answers

Selected text is called region in Emacs universe. See How do I access the contents of the current region in Emacs Lisp?

like image 159
Pavel Chuchuva Avatar answered Oct 21 '22 01:10

Pavel Chuchuva


The accepted answer pointed me to the right answer. I want to leave this piece of code for more ELisp beginners like me. regionp contains the "selection" (known as region in ELisp) as a variable in the ELisp function. The if condition checks if the region is active.

(defun get-selected-text (start end)
  (interactive "r")
    (if (use-region-p)
        (let ((regionp (buffer-substring start end)))
            (message regionp))))
like image 12
Carlo Espino Avatar answered Oct 21 '22 01:10

Carlo Espino