Reputation: 2910
Here is the problem that I'm solving: Convert a region of text into a string data structure for subsequent processing by elisp program. The challenge is that
By my understanding, a region is defined by a mark and the subsequent cursor position. And I usually execute elisp program in *scratch* buffer. Furthermore, the region is also in the *scratch* buffer.
But to write the function call and execute it in the buffer, I need to move the cursor away from the end of the text selection (region) in order to write the program of
(setq grabbed (buffer-substring-no-properties (region-beginning) (region-end)))
but then the region of selection would change due to the cursor movement.
So I wonder how I could execute the elisp program while keeping the selection intact and still can access the return value.
Upvotes: 0
Views: 1577
Reputation: 2910
Finally, I found a desirable solution! It's using ielm
buffer, the real repl of elisp.
In the ielm
buffer, I can set working buffer (by C-c C-b
) to be a buffer where I have the text to be manipulated, for example, *scratch*
.
I can then select a region of the working buffer to be processed, and in the ielm
buffer then I can type and execute elisp code to extract the text in the selected region in the working buffer, for example,
ELISP> (setq grabbed (buffer-substring-no-properties (region-beginning) (region-end)))
"One\nTwo\nThre"
ELISP> grabbed
"One\nTwo\nThre"
ELISP> (split-string grabbed)
("One" "Two" "Thre")
I can then work with the value held by the set variable, grabbed
.
Here is a very helpful description of ielm
:
https://www.masteringemacs.org/article/evaluating-elisp-emacs
Upvotes: 0
Reputation: 28531
If you want to run the function from some Elisp code but as if the user had invoked it via a keybinding, you can use call-interactively
:
(setq variable-to-keep-the-value (call-interactively 'lines-to-list))
But in most cases, what you want instead is to take yourself the responsibility to choose to which part of text the function should apply:
(setq variable-to-keep-the-value
(lines-to-list (region-beginning) (region-end)))
Notice that the region's boundaries are nothing magical, regardless if they've been set by the mouse or what.
Upvotes: 2