Emacs、AUCTeX和使用换行符替换字符串的查询

4

我使用emacs+auctex和auto-fill-mode。

现在有时我想搜索(和替换)一个包含空格的字符串,比如"test1 test2"。问题是,auto-fill-mode有时会将空格字符替换为换行符。因此,搜索和替换"test1 test2"不能找到那些auto-fill替换空格为换行符的字符串。

有什么解决这个问题的办法吗?

在文本模式下,使用query-replace-regexp中的\s-可以工作,即"test1\s-test2",但在auctex-mode中无效,我不知道原因。

使用C-q C-j非常不方便,因为像"test1 test2"这样的情况经常发生,特别是因为我想一次获取换行符和空格,所以我必须做类似这样的事情:

M-x query-replace-regexp RET

test1[ <-- one space

C-j C-q

]\s-*test2

最后的\s-*是因为auctex可能存在缩进问题。 这似乎不太优雅。
顺便说一下,如果你想搜索和替换"test1 test2",每次都要特别考虑换行符的情况,这非常令人烦恼...
2个回答

3

Emacs还有“类别”,它们类似于语法类,但更加灵活。您可以在正则表达式中使用\cX来匹配类别X中的字符。

这里是一个定义“所有空格”类别的函数,其中包括空格、换行符、制表符和换页符,您可以在正则表达式中引用它作为\cs

(defun define-all-whitespace-category (table)
  "Define the 'all-whitespace' category, 's', in the category table TABLE."
  ;; First, clear out any existing definition for category 's'. Otherwise,
  ;; define-category throws an error if one calls this function more than once.
  (aset (char-table-extra-slot table 0) (- ?s ? ) nil)
  ;; Define the new category.
  (define-category ?s "all whitespace
All whitespace characters, including tab, form feed, and newline"
    table)
  ;; Add characters to it.
  (mapc (lambda (c) (modify-category-entry c ?s table))
        '(?  ?\n ?\f ?\t)))

(define-all-whitespace-category (standard-category-table))

我觉得auctex-mode使用的是标准类别表,所以你应该能够在该模式下使用query-replace-regexp和foo\cs+bar

为了测试它,你可以将光标放在感兴趣的某个字符上,然后说:

M-: (looking-at "\\cs") RET

如果点下方的字符属于全空格类别,则其将被评估为t

这是一个比我的解决方案更好的方式。我几乎总是在emacs中展示以前未知的角落,我喜欢这个 :) - jdd

0

解决这个问题最简单的方法可能是编写一个小的elisp函数。

类似于:

(defun auctex-query-replace-regexp (first second replace)
  (interactive "Mfirst:\nMsecond:\nM:replace:")
  (while (re-search-forward (concat first "[ 
]*" second))
    (replace-match replace)))

把它放到你的 .emacs 中,在最后一个 ) 上放置光标,使用 C-x C-e 进行求值。
使用 global-set-key 全局绑定快捷键,或者用 add-hook 在特定模式下绑定。
请注意,字符类包括一个字面上的 空格 和一个字面上的 换行符,可以用 C-oC-q C-j 插入。
这是一个非常简单的例子。改进它留给读者作为练习 ;)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接