MapaDelSitio CambiosRecientes Noticias ÁreaElisp WikiCómo

AutoInsertHeaderGuards

Insert Header guards constructed from the filename. If you have blah.h opened up without any text then header guards and a simple class definition are inserted. If there is already some text in the file then only the header guards are inserted.

  ; Create Header Guards with f12
  (global-set-key [f12] 
  		'(lambda () 
  		   (interactive)
  		   (if (buffer-file-name)
  		       (let*
  			   ((fName (upcase (file-name-nondirectory (file-name-sans-extension buffer-file-name))))
  			    (ifDef (concat "#ifndef " fName "_H" "\n#define " fName "_H" "\n"))
  			    (begin (point-marker))
  			    )
  			 (progn
  					; If less then 5 characters are in the buffer, insert the class definition
  			   (if (< (- (point-max) (point-min)) 5 )
  			       (progn
  				 (insert "\nclass " (capitalize fName) "{\npublic:\n\nprivate:\n\n};\n")
  				 (goto-char (point-min))
  				 (next-line-nomark 3)
  				 (setq begin (point-marker))
  				 )
  			     )
  			   
  					;Insert the Header Guard
  			   (goto-char (point-min))
  			   (insert ifDef)
  			   (goto-char (point-max))
  			   (insert "\n#endif" " //" fName "_H")
  			   (goto-char begin))
  			 )
  		     ;else
  		     (message (concat "Buffer " (buffer-name) " must have a filename"))
  		     )
  		   )
  		)

May be it’s better to make use of the “auto-insert” of emacs. Add following code into your .emacs and find out what emacs do for you when you create new C++ files.

    ;; autoinsert C/C++ header
    (define-auto-insert
      (cons "\\.\\([Hh]\\|hh\\|hpp\\)\\'" "My C / C++ header")
      '(nil
    	"// " (file-name-nondirectory buffer-file-name) "\n"
    	"//\n"
    	"// last-edit-by: <> \n"
    	"//\n"
    	"// Description:\n"
    	"//\n"
    	(make-string 70 ?/) "\n\n"
    	(let* ((noext (substring buffer-file-name 0 (match-beginning 0)))
    		   (nopath (file-name-nondirectory noext))
    		   (ident (concat (upcase nopath) "_H")))
    	  (concat "#ifndef " ident "\n"
    			  "#define " ident  " 1\n\n\n"
    			  "\n\n#endif // " ident "\n"))
    	(make-string 70 ?/) "\n"
    	"// $Log:$\n"
    	"//\n"
    	))
    
    ;; auto insert C/C++
    (define-auto-insert
      (cons "\\.\\([Cc]\\|cc\\|cpp\\)\\'" "My C++ implementation")
      '(nil
    	"// " (file-name-nondirectory buffer-file-name) "\n"
    	"//\n"
    	"// last-edit-by: <> \n"
    	"// \n"
    	"// Description:\n"
    	"//\n"
    	(make-string 70 ?/) "\n\n"
    	(let* ((noext (substring buffer-file-name 0 (match-beginning 0)))
    		   (nopath (file-name-nondirectory noext))
    		   (ident (concat nopath ".h")))
    	  (if (file-exists-p ident)
    		  (concat "#include \"" ident "\"\n")))
    	(make-string 70 ?/) "\n"
    	"// $Log:$\n"
    	"//\n"
    	))

See Also: AutomaticFileHeaders andl Lisp:header2.el for generic code that 1) adds and 2) updates header info.