Searching with intelligent bracket counting (Elisp)

微笑、不失礼 提交于 2019-12-08 07:42:37

问题


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."))))


来源:https://stackoverflow.com/questions/1057314/searching-with-intelligent-bracket-counting-elisp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!