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

Singletoned picture Singletoned · Mar 3, 2009 · Viewed 11k times · Source

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

Answer

Gareth Rees picture Gareth Rees · Mar 3, 2009

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.