I use this elisp code to add a C++ class name to a line such as:

void getNameRawString(char *string);

automatically becomes ...

void SomeClassName::getNameRawString(char *string);


This is useful as you can copy a bunch of class method definitions from a header file you've just created and then run this on each line to add the class names.

First I wrote a utility function that finds the function name, which is presumed to be letters and underscores, following space and ended with a bracket. The function name includes the word probably because it might not work depending on your formatting, but you can twiddle the regex to get what you want.

So as you can see this finds the match for the regex, which will place the point at the end of the search. Then I search backwards for a space which puts the point where we want to insert the class name and double colons...


(defun find-function-start-probably()
(interactive)
(re-search-forward " [*&_a-zA-Z]+(")
(re-search-backward " ")
(forward-char)
(if (or
(char-equal (char-after) ?*)
(char-equal (char-after) ?&))
(forward-char)))


Finally the function below calls find-function-start-probably. It prompts for the class name, finds the function and inserts the text. The program automatically aborts if there is no match. You can override that behavior by passing arguments to re-search-forward.


(defun classname-add(classname)
(interactive "sEnter class name: ")
(find-function-start-probably)
(insert classname)
(insert "::")
(beginning-of-line)
(forward-line))


Improvements on the way:

Multi-line version: do this over multiple lines

Improvements unlikely but would be nice:

Parse the header file more intelligently and create all the class function definitions with empty function bodies in a specified buffer