前言
在使用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."*/
我在使用search-backward时做错了什么?
(代码中可能还有其他至少一个bug,如果search-backward成功了,我不应该添加(length includename),但现在我更关心的是如何使其首先成功)