Searching with intelligent bracket counting (Elisp

2019-06-07 14:44发布

问题:

I have the following function that deletes the LaTeX command surrounding the current cursor position:

(defun remove-tex-cmd ()
  (interactive)
  (save-excursion
    (let (cur-point beg-point end-point)
      (setq cur-point (point))
      (catch 'notexcmd
        (if (not (re-search-backward "\\.*?{" nil t)) ; now the point is at the {
            (throw 'notexcmd nil))
        (search-backward "\\" nil t)
        (setq beg-point (point))
        (re-search-forward "}")
        (setq end-point (point))
        (if (> end-point cur-point)
            (kill-region beg-point end-point))
        (throw 'notexcmd nil)))
    (if 'notexcmd
        (message "no tex command at point"))))

It works well except for the following situation, because it simply matches the next closing }:

\test{a<cursor here>sdf ${bla}+1$}

results in

+1$}

I could, of course, count the opening and closing brackets. However, as this problem should occur frequently, I wonder whether there exists some more intelligent search function, or am I missing a totally different point?

回答1:

Use list- or sexp- based operations:

(defun remove-tex-cmd ()
  (interactive)
  (backward-up-list 1)
  (backward-sexp 1)
  (kill-sexp 2))

To handle scan error when outside parentheses:

(defun remove-tex-cmd ()
  (interactive)
  (condition-case nil
      (progn
        (backward-up-list 1)
        (backward-sexp 1)
        (kill-sexp 2))
    (scan-error (message "Outside parentheses."))))