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)))
(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 usingregion-beginning
andregion-end
or else an error will be thrown .... See the doc-strings forregion-active-p
anduse-region-p
.