Skip to content
lewang edited this page Mar 4, 2012 · 1 revision

er/contract-region without history

The normal way er/contract-region works is by going backwards in the history of expand-region. However, I find it useful to be able to select contents of sexps and strings without first selecting parts of it. I use this for refactoring code a lot.

For example:

(foo-func "blah" foo-bar)|

In order to mark the contents of the sexp, I would C-b M-r M-r M-r.

With this advice enabled, I can do M-r M-R

Code:

(defadvice er/contract-region (before backtrack-sexp activate compile)
  "allow contract region to work with sexp and strings without history"
    (when (and (use-region-p)
             (or (null er/history)
                 (eq (car (car er/history))
                     (cdr (car er/history)))))
    (let ((string-p (and (looking-at "\\s\"")
                         (save-excursion (forward-char) (er--point-inside-string-p))))
          (pair-p (and (looking-at "\\s(")
                       (save-excursion (forward-char) (er--point-inside-pairs-p))))
          end)
      (when (or string-p pair-p)
        (save-excursion
          (goto-char (mark))
          (backward-char 1)
          (skip-chars-backward er--space-str)
          (setq end (point)))
        (forward-char 1)
        (skip-chars-forward er--space-str)
        (push (cons (point)end) er/history)))))
Clone this wiki locally