0

I would like to write a script where I can select some text as the region, extract the selected region as a string, modify it, and pass it to another program.

I am playing around with ielm and see that I can call (yank) to pull the region string into a register. How would I go about getting the region string into a variable though?

  • How about? (buffer-substring (region-beginning) (region-end)) or (buffer-substring-no-properties (region-beginning) (region-end)). To get it into a variable you can use (setq my-variable (buffer-substring.....) or let-bind the value to a temporary variable during the relevant function ... You'll need to set up a test for whether the region is active before using region-beginning and region-end or else an error will be thrown .... See the doc-strings for region-active-p and use-region-p. – lawlist Aug 31 at 0:28
  • @Drew bare with me - I don't have all the emacs terminology down but basically I have a region active and I would like the text in that region to be in a variable as a string. – George Mauer Aug 31 at 1:41
  • I see what you're saying @Drew, I meant "parameters" as in parameters that will be passed into the other programs - as far as elisp is concerned a string. I'll edit – George Mauer Sep 2 at 19:52
  • It is @Drew. Post an answer and I'll accept – George Mauer Sep 3 at 14:17
1

This code should do what you want:

(setq your-variable  (buffer-substring (region-beginning) (region-end)))

If you want a command, try this:

(defun my-set-var-to-selection (variable beg end)
  "Set VARIABLE to a string with the selected text.
You are prompted for VARIABLE."
  (interactive 
   (if (use-region-p)
       (list (intern (completing-read "Variable: " obarray 'boundp t))
             (region-beginning)
             (region-end))
     (error "No selection (no active region)")))
  (set variable (buffer-substring beg end)))

If you don't want to require VARIABLE to already be a variable (you want to allow any name as a variable) then remove the arguments 'boundp and t from the completing-read call.

If you want to use the region text even when the region is not active (no selection) then use just this as the interactive spec:

(interactive 
  (list (intern (completing-read "Variable: " obarray 'boundp t))
        (region-beginning)
        (region-end)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.