[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: Select Text Inside Parentheses

From: Drew Adams
Subject: RE: Select Text Inside Parentheses
Date: Sat, 1 Sep 2012 09:34:17 -0700

> I'm trying to select text between parentheses. This text is not
> code. This is my block of text: 
> (
> foo
> bar
> baz
> )
> Problem is that it selects the whole first line after the first
> parentheses, so I get a whole line of white space in front of 
> the first character. I'd like the selection to start at the first 
> character after the first parentheses and end at the last
> character before the last parentheses. I tried adding
> (delete-horizontal-space).
> Any pointers as to how I can do this?.
> (require 'simple)

You never need to require `simple.el[c]'.  It is preloaded.

> (defun set-selection-around-parens()
>   (interactive)
>   (let ( (right-paren (save-excursion
>                         (re-search-forward ")" nil t)))
>          (left-paren (save-excursion (re-search-backward "(" nil t))))
>     (when (and right-paren left-paren)
>       (push-mark (- right-paren 1))
>       (goto-char (+ left-paren 1))
>       (delete-horizontal-space)
>       (activate-mark))))

Below is a quick start.  It does not try to take care of whether a parenthesized
sexp might be inside a string.

(defun foo ()
  (when (re-search-forward
         "(\\(\s-\\|[\n]\\)*\\(.+\\)\\(\s-\\|[\n]\\)*)" nil t)
    (goto-char (match-beginning 2))
    (push-mark nil 'nomsg 'activate)
    (goto-char (match-end 2))
    (setq deactivate-mark  nil)))

Someone else might have another suggestion.  Or you can tweak this.

If you do not want to select only whitespace between parens - e.g.,
for `(        )', then you might change \\(.+\\) to \\(\\S-+.*\\).
That is, "(\\(\\s-\\|[\n]\\)*\\(\\S-+.*\\)\\(\\s-\\|[\n]\\)*)".

The regexp matches `(' followed by perhaps some whitespace (including newlines):

Followed by a non-empty stretch of any chars "\\(.+\\)"
(or perhaps "\\(\\S-+.*\\)").

Followed by perhaps some whitespace (maybe newlines)
followed by `)': "(\\(\\s-\\|[\n]\\)*)".

The regexp's first subgroup matches the possible first stretch of whitespace.
Its second subgroup matches the text you want.  So you pick up the text from
(match-beginning 2) to (match-end 2).

Set `deactivate-mark' to nil at the end of a command where you want the mark to
remain active.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]