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

≯℡__Kan透↙ 提交于 2019-12-17 15:32:49

问题


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


回答1:


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




回答2:


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.




回答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.



来源:https://stackoverflow.com/questions/605846/how-do-i-access-the-contents-of-the-current-region-in-emacs-lisp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!