gpt4 book ai didi

regex - Emacs正则表达式:替换 latex 方程中的字符串

转载 作者:行者123 更新时间:2023-12-01 08:01:29 26 4
gpt4 key购买 nike

我想将所有在LaTeX方程式中出现的所有字母'n'替换为字母'N'。可以假定文档中的LaTeX方程的格式为$ ... $

也将接受perl或ubuntu或Windows上随时可用的任何其他语言/工具/应用程序的解决方案。

最佳答案

在emacs中,我们可以利用auctex的亮点来替换所有数学环境中的字符串。 (我知道这与问题有所出入。但是,也许这更有用。)在运行下面的代码后,按M-x latex-replace-in-math并输入源正则表达式(例如\<n\>),然后输入替换字符串(例如N)。如果在变量名之间保留空格,则\<n\>n更好,否则\sin也会被\siN取代,这可能不是您想要的。但是,下面的代码也不是什么大问题,因为它可以查询替换,您可以按n跳过不需要的替换。

请注意,如果要替换区分大小写的代码,则应停用选项→忽略搜索的大小写。

用户cgogolin的回答给了我一个新的主意。

我新的首选解决方案是:

(fset 'latex-replace-in-math
`(lambda (regexp to-string &optional delimited start end backward &rest _ignore)
"Like `query-replace-regexp' but only replaces in LaTeX-math environments."
,(interactive-form 'query-replace-regexp)
(let ((replace-re-search-function (lambda (regexp bound noerror)
(catch :found
(while (let ((ret (re-search-forward regexp bound noerror)))
(when (save-match-data (texmathp)) (throw :found ret))
ret))))))
(query-replace-regexp regexp to-string delimited start end backward))))

前一个更复杂的版本是:

(defun latex-in-math (pos)
"Check whether pos is in math environment."
(let ((face (plist-get (text-properties-at pos) 'face)))
(or (eq face 'font-latex-math-face)
(and (listp face)
(memq 'font-latex-math-face face)))))

(defun latex-next-math-change (&optional bound stay)
"Starting at point search for next beginning of math environment.
Place point there if STAY is nil and return point.
Else leave point where it was and return nil."
(let ((b (point))
(inMathB (latex-in-math (point)))
inMath)
(catch :found
(while (setq b (next-single-property-change b 'face nil bound))
(setq inMath (latex-in-math b))
(when (or (and inMathB (null inMath))
(and (null inMathB) inMath))
(unless stay (goto-char b))
(throw :found b))))))

(defun latex-replace-in-math (src tgt &optional bound)
"In all math-environments replace SRC with TGT."
(interactive (list (read-regexp "Source regular expression:")
(read-string "Target string:")))
(save-excursion
(font-lock-fontify-region (point) (point-max)))
(catch 'quit
(let (b e repl)
(when (latex-in-math (point))
(error "point-min should not be in math environment"))
(while (setq b (latex-next-math-change bound))
(goto-char b)
(while (search-forward-regexp src (latex-next-math-change bound t) 'noErr)
(unless (eq repl 'all)
(let ((ol (make-overlay (match-beginning 0) (match-end 0))))
(overlay-put ol 'face 'query-replace)
(while (null
(eval (cdr (assq (read-char "y: replace, n: don't, q: quit, !: replace all" '(?y ?n ?q ?!))
'((?y . (setq repl t))
(?n . (setq repl 'no))
(?q . (setq repl 'quit))
(?! . (setq repl 'all))))))))
(delete-overlay ol))
(when (eq repl 'quit)
(throw 'quit nil)))
(unless (eq repl 'no)
(replace-match tgt)))))))

关于regex - Emacs正则表达式:替换 latex 方程中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19845598/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com