When I edit C/C++ files time to time in the middle of buffer, I decide to add #include at the begin of buffer. Save position jump to begin of buffer, then insert suitable line, then jump back is boring.

I wonder may be there is standard (emacs build-in/elpa/melpa) solution to deal with such problem?

I mean some elisp code to find #include directives at the begin of file and insert new one.

If there are no, may be there is such solution for other languages for import (Java, Python), use (Rust) and so on which I can modify for C++?

  • FWIW, you can use C-r #include RET to find an existing directive, do your thing there, then use C-u C-SPC to jump back to where you were. The magic works because C-r pushes the starting point to the mark ring.
    – YoungFrog
    Aug 17 '17 at 8:01

I'm sure someone will point you to an existing function, but it's easy easy enough to write your own:

(defun add-include (header)
  "Add an #include line for `header' near top of file, avoiding duplicates."
  (interactive "M#include: ")
  (let ((incl (format "#include <%s>" header)))
      (if (search-backward incl nil t)
          (message "You already %s." incl)
        (when (search-backward "#include" nil 'stop-at-top)
        (insert incl)

It first checks to see if you already have that include and if so does nothing. If not, it then checks to see if you have any includes at all, and if so put the new one on the line after the last one. Finally, if you have no includes at all, it puts the new one at the top of the buffer.

I'm sure usage would find some rough corners you'd want to smooth out. For example, I just noticed I hard-coded < and > for the include line. You can modify this if you sometimes need quotes instead.

  • Thanks, if no packages exists I will use your code. Aug 17 '17 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.