I wannt to replace a specific word in multiple files. First time i do "C-c c" everything works fine, but when i repeat the command the text is not updated in the newly created files correctly. The files contain same content as the first pair of files(.cpp, .h). I think it is a buffer issue in replace-word-in-string but i dont know how to fix it? I'm a beginner at Elisp please explain in simple terms, thanks for helping me out.
;;Prototype source
(setq sourceCode "//Include Librarys
#include MyClass
//Include Files
//******
//MyClass::MyClass
//******
MyClass::MyClass() {}
//******
//MyClass::~MyClass
//******
MyClass::~MyClass() {}
")
;;Prototype Header
(setq headerCode "#ifndef MYCLASS
#define MYCLASS
//Include Librarys
//Include Files
//Forward declarations
class MyClass {
public:
MyClass();
~MyClass();
private:
};
#endif //!MyClass
")
;;Create CLASS
(global-set-key (kbd "C-c c")
(defun create-class (directory name)
(interactive "s(Create a new class) Enter path:
sEnter class name: ")
(setq directory "c:/Programming/") ;only for degugging
(setq path (concat directory name))
(setq pathSource (concat path ".cpp"))
(setq pathHeader (concat path ".h"))
;Replace default class name with user specified class name
(setq sourceCode (replace-word-in-string sourceCode name "MyClass"))
(setq headerCode (replace-word-in-string headerCode name "MyClass"))
;Check if file exist in current directory
(if (and (file-exists-p pathSource)(file-exists-p pathHeader))
(message "%s" "Filename already exist, no files where created!")
(write-region sourceCode nil pathSource) ;Write to files.
(write-region headerCode nil pathHeader)
(message "Created source file: %s and created header file: %s" pathSource pathHeader)
)
)
)
(defun replace-word-in-string(string replacementWord searchedWord)
(with-temp-buffer
(insert string)
(goto-char (point-min))
(while (re-search-forward searchedWord nil t)
(replace-match replacementWord nil t)
(setq retString (buffer-string)) ;returns all content in buffer as a string
)
)
retString
)
C-c c
is reserved for users, it isn't (normally) used by any Emacs packages. So we'll have a hard time helping without knowing what it's bound to. Can you tell us whatC-h k C-c c
reports?create-class
was defined in your personal config files - it's not part of emacs or any public package. Where did you get it? Can you post the code? From the help page thatC-h k C-c c
creates, there should be a link to your init.el. Clicking that will bring you to the source code for the function.create-class
on its own, at top-level, not nested inside your keybinding. i.e.,(defun create-class ...)
and(global-set-key (kbd "C-c c") 'create-class)