gpt4 book ai didi

search - Emacs Lisp 向后搜索

转载 作者:太空宇宙 更新时间:2023-11-03 18:43:20 26 4
gpt4 key购买 nike

序言

在 C++ 中使用 VTK 库,我经常不得不这样写:

vtkInteractorStyleRubberBandZoom *isrbz = vtkInteractorStyleRubberBandZoom::New();

此外,每次我需要在我的程序中使用一个新的 VTK 类时,我都必须在源文件的某个地方添加#include "vtkInteractorStyleRubberBandZoom.h"

我如何实现自动化,这样我就必须将每个长得难以忍受的类名输入一次而不是三个?

我试着为它写一个 Emacs 次要模式。可能已经有现成的解决方案(YaSnippet?),但我认为自己编写它也是一个很好的练习。

代码

;vtk-mode.el
;add to .emacs:
;(load "vtk-mode")
;(global-set-key [(control =)] 'expand-vtk)

(defun expand-vtk ()
(interactive)
(setq now (point))
(setq vtkstart (search-backward "vtk"))
(setq vtkend (- (search-forward " ") 1))
(setq vtkname (buffer-substring vtkstart vtkend))

;check for #include "vtkBlah.h"
(setq includename (format "#include \"%s.h\"\n" vtkname))
(search-backward includename nil (append-include-vtk includename))
(goto-char (+ now (length includename)))

(insert (format "= %s::New();" vtkname)))

(defun append-include-vtk (incname)
(goto-char 0)
(insert incname))

问题

基本上,它可以工作,除了搜索包含名称总是失败,例如。例如:

vtkSomething *smth /*press C-= here, it looks backward for 
#include "vtkSomething.h", can't find it and
calls append-include-vtk, adding it to the beginning
of the file, then comes back here and expands this line into: */

vtkSomething *smth = vtkSomething::New();

//and let's add another instance of vtkSomething...
vtkSomething *smth2 /*press C-= again, it looks backward for
#include "vtkSomething", and fails, despite the fact
that it was added by the previous command. So it adds it again."*/

我在这里使用向后搜索做错了什么?

(代码中还有另一个(至少一个)错误,如果向后搜索成功,我不应该添加 (length includename),但现在我更感兴趣的是如何让它成功,首先)

最佳答案

好的,我知道了。不知何故,我知道 search-backward (noerror) 的第三个参数是回调,但事实并非如此。因此每次都会对其进行评估,而不仅仅是在搜索失败时。它应该是这样的:

(defun expand-vtk ()
(interactive)
(setq now (point))
(setq vtkstart (search-backward "vtk"))
(setq vtkend (- (search-forward " ") 1))
(setq vtkname (buffer-substring vtkstart vtkend))

;check for #include "vtkBlah.h"
(setq includename (format "#include \"%s.h\"\n" vtkname))
(if (search-backward includename nil t)
(goto-char now)
(progn (append-include-vtk includename)
(goto-char (+ now (length includename)))))

(insert (format "= %s::New();" vtkname)))

(defun append-include-vtk (incname)
(goto-char 0)
(insert incname))

关于search - Emacs Lisp 向后搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4074929/

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