如何使用正则表达式搜索,并且忽略当前 buffer 的 Syntax Table?

使用正则搜索 emacs\b

// org-mode

'emacs'         // not match
emacs.          // match
emacs-lisp-mode // match
// fundamental-mode

// all matches
'emacs'
emacs.
emacs-lisp-mode

Edit: 没看清题目,下面答非所问了 :rofl: 抱歉楼主(

要用 elisp 搜索的话,用 syntax-ppss 或者当前位置的 face 来判断是不是在字符串里,然后自己把正则搜索包一个函数,搜到字符串里的时候继续往前搜一下。

可以参考我插件里这个函数:

(defun citre--pos-in-code-p (&optional pos)
  "Non-nil if position POS is in code.
This means POS is not in comments or strings.  When POS is not
specified, use current point.

Notice that its behavior at boundaries of comment/strings may
vary, depending on whether font lock mode is enabled."
  (let* ((pos (or pos (point))))
    ;; `syntax-ppss' is not always reliable, so we only use it when font lock
    ;; mode is disabled.
    (if font-lock-mode
        (let ((pos-faces (get-text-property pos 'face)))
          (unless (listp pos-faces)
            (setq pos-faces (list pos-faces)))
          (not
           (cl-intersection '(font-lock-comment-face
                              font-lock-comment-delimiter-face
                              font-lock-doc-face
                              font-lock-string-face)
                            pos-faces)))
      (not (save-excursion
             (or (nth 4 (syntax-ppss pos))
                 (nth 3 (syntax-ppss pos))))))))

syntax-ppss 的话在定界符上好像会判断不出来,这个自己试一下吧。

搜索函数长这样:

(defun citre--search-backward-in-code (str &optional bound count)
  "Search backward from point for STR, and skip comments and strings.
About the optional arguments BOUND and COUNT, see the docstring
of `search-backward'.

This function will return the point at the beginning of the first
matched STR.  When the search fails, it won't signal an error,
but return nil.  This is different from `search-backward'."
  (let ((pos nil))
    (save-excursion
      (cl-loop
       while
       (search-backward str bound t count)
       do
       (when (citre--pos-in-code-p)
         (setq pos (point))
         (cl-return))))
    (when pos
      (goto-char pos))))

要交互式搜索的话我也不太清楚怎么做,每个插件有自己的设计,我估计要把这种逻辑 hack 进去不会太容易(

1 个赞

\b word 边界,什么叫 word 是 syntax table 定义的,要在 A 模式下使用 B 模式的 syntax table,如果用 Lisp 的话,有专门的函数。

emacs[^a-z]?

感谢楼上各位的回复, 不过现在找到了

(with-syntax-table (make-syntax-table)
  (re-search-forward "emacs\\b" nil t))
1 个赞