在编写和阅读 C++ 的程序的时候,经常需要在头 .h 文件和.cpp 文 件之间调转,下面的代码可以帮助完成这个功能。如果当前 buffer 是一个 aa.h ,那么就会打开对应的aa.cc 或者 aa.cpp 或者 aa.cxx ,根据实际情况而定。同样如果当前是 aa.cc 或者 aa.cpp 或者 aa.cxx ,那么就会打开
(defun wcy-c-open-other-file () "if current file is a header file, then open the corresponding source file or vice versa. " (interactive) (let ((f (buffer-file-name)) (headers '("h" "hpp" "hxx")) (sources '("c" "cxx" "cpp" "cc"))) (if f (let* ((b (file-name-sans-extension f)) (x (file-name-extension f)) (s (cond ((member x headers) sources) ((member x sources) headers) (t nil))) (return-value nil)) (while s (let ((try-file (concat b "." (car s)))) (cond ((find-buffer-visiting try-file) (switch-to-buffer (find-buffer-visiting try-file)) (setq s nil return-value t)) ((file-readable-p try-file) (find-file try-file) (setq s nil return-value t)) (t (setq s (cdr s)))))) return-value))))
然后可以用 M-x wcy-c-open-other-file 打开文件了。
也可以加个 toobar 的快捷方式。
(tool-bar-add-item "c-open-other-file" 'wcy-c-open-other-file 'wcy-c-open-other-file :visible `(memq major-mode `(c++-mode c-mode)) :help "open the company .h or .cc file")
确认在 load-path 内可以找到
wcy-c-open-other-file.xpm 文件。
居然发现 M-x ff-find-other-file 也一样可以完成这个工作。