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

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


Solution 1:

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.

Solution 2:

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

Solution 3:

If you want to copy region content in a Lisp code to a user-accessible data structure like kill-ring, X clipboard or register, Emacs Lisp manual recommends to use filter-buffer-substring instead of simply buffer-substring. Before copying, the function applies filter functions from a list variable called filter-buffer-substring-functions. The function was added in version 22.3.