Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the contents of the current region in Emacs Lisp?

Tags:

emacs

lisp

region

I want to access the contents of the current region as a string within a function. For example:

(concat "stringa" (get-region-as-string) "stringb") 

Thanks

Ed

like image 597
Singletoned Avatar asked Mar 03 '09 10:03

Singletoned


People also ask

How to set region in Emacs?

Click the mouse's left button at the start of the area to be selected, and drag the mouse to the end of the area. The region you selected should be highlighted.

How to use mark and point to set region in Emacs?

To set the mark, type C- SPC ( set-mark-command ). This makes the mark active; as you move point, you will see the region highlighting grow and shrink. The mouse commands for specifying the mark also make it active.

How do I Lisp in emacs?

In a fresh Emacs window, type ESC-x lisp-interaction-mode . That will turn your buffer into a LISP terminal; pressing Ctrl+j will feed the s-expression that your cursor (called "point" in Emacs manuals' jargon) stands right behind to LISP, and will print the result.

What does #' mean in Emacs Lisp?

#'... is short-hand for (function ...) which is simply a variant of '... / (quote ...) that also hints to the byte-compiler that it can compile the quoted form as a function.


2 Answers

As starblue says, (buffer-substring (mark) (point)) returns the contents of the region, if the mark is set. If you do not want the string properties, you can use the 'buffer-substring-no-properties variant.

However, if you're writing an interactive command, there's a better way to get the endpoints of the region, using the form (interactive "r"). Here's an example from simple.el:

 (defun count-lines-region (start end)   "Print number of lines and characters in the region."   (interactive "r")   (message "Region has %d lines, %d characters"        (count-lines start end) (- end start))) 

When called from Lisp code, the (interactive ...) form is ignored, so you can use this function to count the lines in any part of the buffer, not just the region, by passing the appropriate arguments: for example, (count-lines-region (point-min) (point-max)) to count the lines in the narrowed part of the buffer. But when called interactively, the (interactive ...) form is evaluated, and the "r" code supplies the point and the mark, as two numeric arguments, smallest first.

See the Emacs Lisp Manual, sections 21.2.1 Using Interactive and 21.2.2 Code Characters for interactive.

like image 158
Gareth Rees Avatar answered Sep 24 '22 02:09

Gareth Rees


buffer-substring together with region-beginning and region-end can do that.

like image 22
starblue Avatar answered Sep 25 '22 02:09

starblue