這東東好像有很多人寫過,不過看了幾個都覺得不怎么漂亮,花了點時間實現了下面的函數,用起來還不錯。
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; c/c++ header include guard
(defun insert-include-guard ()
"insert include guard for c and c++ header file.
for file filename.ext will generate:
#ifndef FILENAME_EXT_
#define FILENAME_EXT_
original buffer content
#endif//FILENAME_EXT_
"
(interactive)
(setq file-macro
(concat (replace-regexp-in-string "\\." "_" (upcase (file-name-nondirectory buffer-file-name))) "_"))
(setq guard-begin (concat "#ifndef " file-macro "\n"
"#define " file-macro "\n\n"))
(setq guard-end
(concat "\n\n#endif//" file-macro "\n"))
(setq position (point))
(goto-char (point-min))
(insert guard-begin)
(goto-char (point-max))
(insert guard-end)
(goto-char (+ position (length guard-begin))))