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
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.
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.
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.
#'... 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.
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.
buffer-substring
together with region-beginning
and region-end
can do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With