Starting any Emacs buffer with a .c extension with a template - emacs

I write a lot of short throwaway programs, and one of the things I find myself doing repeatedly is typing out code like
#include <stdio.h>
#include <stdlib.h>
int main(void){
}
To save some tendon hits I was wondering if it was possible to insert a simple template above whenever I create a buffer with the extension of .c.

Put somthing like this in .emacs
(define-skeleton c-throwaway
"Throwaway C skeleton"
nil
"#include <stdio.h>\n"
"#include <stdlib.h>\n"
"\n"
"int main(void){\n"
"\n"
"}\n")
And eval (C-x C-e) it. That'll give you a
function (c-throwaway) that inserts your template.
To get this inserting automaticly you'll need to activate
auto-insert-mode. Once you do this you can describe-variable
auto-mode-alist and read up on how emacs does some of its open
file magic. Then define auto-insert-alist to apply it when you
find a new file.
Maybe something like this
(define-auto-insert "\\.\\([Cc]\\|cc\\|cpp\\)\\'" 'c-throwaway)
More detail:
Auto Insert Mode
Autotype

I use template.el from http://emacs-template.sourceforge.net/
Basically, I create a file called ~/.templates/TEMPLATE.c, and then that gets inserted into my .c files. You can also use special markup and arbitrary lisp expressions, if you don't just want to dump text into the buffer. I use this feature so that Perl modules start with "package Foo::Bar" when they are named lib/Foo/Bar.pm. Very handy.

The following function will ask for a filename and then insert a file and change to c-mode. The only problem is that you have to call this function to create the buffer instead of your normal way.
(defun defaultCtemplate(cfilename)
(interactive "sFilename: ")
(switch-to-buffer (generate-new-buffer cfilename))
(insert-file-contents "~/Desktop/test.c")
(c-mode)
)
P.S Thanks for the question, now I know how to do this for myself :)

You can also use the YASnippet template system for Emacs, which just has a builtin template called main. So while writing your code, just type main, hit TAB, and it will expand it to the form you want. (And you can always write your own snippet templates.)

I use following code to create files from templates. There are several templates, that are substitutes with actual file names, etc

This question is old, but this might help someone. Looking at this site, I copied and pasted this part into my .emacs file:
;; automatic insertion of templates
(require 'autoinsert)
(auto-insert-mode) ;;; Adds hook to find-files-hook
(setq auto-insert-directory "~/Documents/Emacs/templates/") ;;; *NOTE* Trailing slash important
;;(setq auto-insert-query nil) ;;; If you don't want to be prompted before insertion
(define-auto-insert "\.tex" "my-latex-template.tex")
(define-auto-insert "\.cpp" "my-cpp-template.cpp")
(define-auto-insert "\.h" "my-cpp-template.h")
After changing the directory and filenames, it works perfectly.

Here's how I do it (because I didn't know about auto insert mode :-)
(require 'tempo)
(setq c-new-buffer-template
'(
"#include <stdio.h>\n"
"#include <stdlib.h>\n"
"\n"
"int main(void){\n"
"\n"
"}\n"
))
(defun my-c-style ()
"My editing style for .c files."
(c-mode)
(if (zerop (buffer-size))
(tempo-template-c-skeleton)))
(setq auto-mode-alist
(cons '("\\.c\\'" . my-c-style) auto-mode-alist))
(tempo-define-template "c-skeleton" c-new-buffer-template
nil
"Insert a skeleton for a .c document")

I use a combination of Defaultcontent.el and YASnippet.el. The former fills brand-new files with default content. The latter is a sort of lightweight code-gen macro thing. Key in "for" and hit TAB and the skeleton of a for loop is inserted. Etc. You can define your own snippets pretty easily. "swi TAB" gets you a complete switch statement. And so on.

yasnippet is good at expand template in your file, and is very easy to create your snippets.
auto-insert is good at fill a new file with template, but write your own template is hard. There is a great package yatemplate bridges the gap between YASnippet and auto-insert-mode, i can write auto-insert rules with YASnippet.

Related

Emacs - How to wrap selection in org-mode source code block?

I have a bunch of elisp and other code with some notes i wanted to reformat to be more organized, and i found that having to type
#+BEGIN_SRC emacs-lisp ... #+END_SRC
all the time around what i want, is taking a bit longer than expected...
So what i wanted to do instead is to wrap/or put the selected content (with C-space) and put it in a template source code block for org-mode (in my case it's mostly elisp code, but i plan to use it for other things maybe)
How could i do this in emacs or in elisp?
There is a new templating mechanism in recent Org mode (>= 9.0 IIRC) that allows you tor wrap a region in a block: after selecting the region in the usual manner, you say C-c C-, s. You still have to type the emacs-lisp part though. That's the disadvantage. The advantage is that it is general enough to allow you to wrap a region in any kind of block. In your case, I think the disadvantage outweighs the advantage, so I would go with the wrap-region method in the other answer, but this one is good to know as well.
You can try wrap-region. It will allow you to define what type of string you want to wrap around a selection.
Put this in your init.el and evaluate it.
(wrap-region-global-mode t)
(wrap-region-add-wrapper "#+BEGIN_SRC emacs-lisp\n" "#+END_SRC" "#" 'org-mode)
Then, while you are editing your org files, you can select a block of text and type #, which will wrap it with your string. You can change the # to another character that will do the wrapping.
There is a feature in org-mode to do exactly that. It's like a snippet of some sort where you enter <eland hit TAB, the < char is here to say we're gonna use a template and the el part tells which template to use. But of course, you have to configure it first.
For that, you can just add this to an org-mode file or to your init.el file :
#+begin_src emacs-lisp
;; This is needed as of Org 9.2
(require 'org-tempo)
(add-to-list `org-structure-template-alist `("sh" . "src shell"))
(add-to-list `org-structure-template-alist `("el" . "src emacs-lisp"))
(add-to-list `org-structure-template-alist `("py" . "src python"))
#+end_src
There a bunch of way to use this, it's actually more useful than just use it as a template, you can go check the documentation here.

Emacs org-mode tags not found

I'm learning to use emacs and org-mode. I create a few tags, in a .org file, as such :outline: lets say.
And then searched for them using:
C-c a m outline
C-c a t outline
C-c \ outline
And the output is always (basically, did't find anything):
Headlines with TAGS match: outline
Press `C-u r' to search again with new search string
What am I doing wrong. Can someone please tell me what I'm missing?
Thanks in advance.
Common problems when initially setting up org-mode include, but are not limited to, properly configuring the org-agenda-files variable. A user may choose to have one or more files, or a directory.
Here is an example of multiple files:
(setq org-agenda-files
(list "~/org/gtd.org" "~/org/work.org" "~/org/personal.org"))
Here is an example of a directory:
(setq org-agenda-files (list "~/"))
(setq org-agenda-file-regexp "\\`[^.].*\\.org\\|.todo\\'")
It is interesting to note that there is also non-interactive function with the same name, which looks up the configuration of the org-agenda-files variable -- the function is what org-mode generally relies upon when any other function looks up the value of the variable. To see an example of how that non-interactive function works, the user can do something like this:
M-x eval-expression RET (org-agenda-files) RET
The importance of setting the org-agenda-files variable can be seen by examining the function org-match-sparse-tree, which in turn calls org-scan-tags using org-make-tags-matcher, which uses org-global-tags-completion-table, which uses the function org-agenda-files, which uses the variable org-agenda-files. If the variable org-agenda-files is not set up correctly, a tags search and auto-completion of tags will not work correctly.
Another common issue arises when the variable org-tag-alist has not yet been properly set up -- here is a link to the manual page on that issue: http://www.orgmode.org/manual/Setting-tags.html

Collapse/expand parts of .emacs file with org-mode

I recently learned the basics of emacs' org-mode and couldn't help but imagine applying the collapse/expand concept to parts of a source file. I would like to be able to divide my .emacs file in subparts and only display headers on load, somewhat like the following:
; ERC config...
; DIRED config...
; MISC config...
Each of these would of course be headers to many lines of codes once expanded, like this:
; ERC config
(defun start-irc ()
(interactive)
(erc-tls :server "irc.freenode.net" :port 6697 :nick "foo"))
; DIRED config...
; MISC config...
So is this possible? How could I accomplish something like this with emacs 24.2?
Thanks!
As nice as org-mode is, it does require some structure, which I don't believe can be maintained the way you want in your .emacs file.
What does work well is folding-mode. Check out the information for it on the wiki page, but basically what you do is set up comments around the chunks of code you want to put in a fold, like so:
;;{{{ some folder of some kind
(a few lines)
(of lisp)
(this "code" is just filler)
;;}}}
;;{{{ a different folder
(some more elisp code)
;;}}}
And when it is folded, it will look like:
;;{{{ some folder of some kind...
;;{{{ a different folder...
Babel enables you to achieve exactly this (i.e. managing your init file in org-mode). Specifically, see: http://orgmode.org/worg/org-contrib/babel/intro.html#emacs-initialization
Myself, I make use of outline-minor-mode in my init file for vaguely similar purposes. Various things are treated as outline headings, but you can set outline-regexp as a file local variable to restrict that behaviour, and then you toggle things open and closed with outline-toggle-children (which you would bind to some convenient key). The toggle command works from anywhere in the section, not just on the heading.
I start the headings I want to be collapsed by default with ;;;; * and end my init file with:
;;; Local Variables:
;;; outline-regexp: ";;;; "
;;; eval:(progn (outline-minor-mode 1) (while (re-search-forward "^;;;; \\* " nil t) (outline-toggle-children)))
;;; End:
In your instance you could use:
;;; Local Variables:
;;; outline-regexp: "; "
;;; eval:(progn (outline-minor-mode 1) (hide-body))
;;; End:
Pretty similar in effect to Trey's suggestion, although I expect with folding you can trivially nest sections which I'm not accounting for (having no need to do so). I feel the outline approach leaves the file looking slightly cleaner, if that matters to you.
You can also take a look at the new Outshine package which works together with outline-minor-mode to make it feel more like org-mode. In (e)lisp files outshine interprets sequences of semicolons as headers so all existing code which follows standard conventions for comments becomes foldable without any changes. Many org-mode-like key bindings (like TAB to fold/unfold heading, etc) work too.

How to configure cleverly org-archive-location in org-mode

BACKGROUND: In org-mode, the variable org-archive-location is set to "%s_archive::" by default, so that a file "toto.org" archives into a file "toto.org_archive". I would like it to archive to "toto.ref" instead. I am using org-mode version 7.4 (out of the git server).
I would have thought it to be as simple as
(setq org-archive-location
`(replace-regexp-in-string ".org" ".ref" %s)
)
But I was pointed out that this was not proper in LISP (plus, it did not work). My final solution is as follow, you should be able to adapt to most clever configurations of org-archive-location:
(setq org-archive-location "%s::* ARCHIVES")
(defadvice org-extract-archive-file (after org-to-ref activate)
(setq ad-return-value
(replace-regexp-in-string "\\.org" ".ref" ad-return-value)
)
)
Note that:
1) I voluntarily did not add a $ at the end of ".org" so that it would properly alter "test.org.gpg" into "test.ref.gpg".
2) It seems that one should use the regular expression "\.org" (rather than, say, ".org") (longer explanation below in the answers).
You can't define a variable in Emacs such that its value is obtained by running code; variables have simple, static values.
You can achieve the effect you described by advising the function org-extract-archive-file, which is the one that generates an archive location from org-archive-location:
(defadvice org-extract-archive-file (after org-to-ref activate)
(setq ad-return-value
(replace-regexp-in-string "\\.org" ".ref" ad-return-value)))
This works for me now, but of course the internals of org-mode are subject to change and this solution may not work forever.
You should not quote an expression that you want to evaluate. Note also that in a regular expression, . matches any character.
Here is an example of how to set the file, the location (e.g., main heading) in the file, and whether or not to include additional archive information:
(let* (
(org-archive-location "~/todo.org::* TASKS")
(org-archive-save-context-info nil))
...)
You can try this: #+ARCHIVE: %s.ref:: at the beginning of your org file.
Read more about it here.
Also, other interesting option is to set inside your headtree the following, for instance:
* Main Header of tree
:PROPERTIES:
:ARCHIVE: toto.ref:: * Main Header of tree in archive file
:END:
** sub tree of main header and so on
The latter I took from this video.

How can I apply a new Emacs C style to reformat all my source files?

I'd like to re-format all my source files using the Google formatting function for emacs: google-c-style.el (see here).
How can I apply this function to all my source files at once, so that they are all formatted and indented correctly according to the Google style?
There are several pieces to this:
you need to come up with EMACS functions to do all the reformatting you want. indent-region is a start, but you might also want to untabify or some other things.
you need to invoke them on each file, and since the indent functions work on ranges, you need a function that sets mark to cover the whole file: mark-whole-buffer.
you need to invoke EMACS on each file: this means invoking emacs with the --batch file.
There's a couple of nice blog posts on doing this here and here.
I have done this before by using a keyboard defined macro. I would load all of the files into emacs (something like find . -name "*.cpp" | xargs emacs) and then type the following keys. I've annotated each key combination with what it does.
C-x-( 'Begin recording macro
M-< 'Go to start of file
C-space 'Mark current location (now start of file)
M-> 'Go to end of file
M-x indent-region 'Indent entire file according to coding style
C-x C-s 'Save the current buffer
C-x C-k 'Close the current buffer
C-x-) 'End recording macro
Now you can run this on a buffer by typing C-x e. If you have loaded several files you can run something like C-u 100 C-x e to run this on 100 files. If this is more than the number of files, that is ok, you'll just get some "bell ring" or other error you can ignore once all the processing is complete.
I believe that this script does not do reformatting. Instead it's an example of how to build a custom "style" as described in: CC mode manual - Styles
CC-mode manual also says:
If you want to reformat old code, you're probably better off using some other tool instead, e.g. GNU indent, which has more powerful reformatting capabilities than CC Mode.
CC mode manual - Limitations-and-Known-Bugs
If you want to mark the source files in a dired buffer and then run a function to format each you can do something like this:
(defun clean-file(filename)
(your-function-goes-here))
(defun clean-each-dired-marked-file()
(interactive)
(for-each-dired-marked-file 'clean-file))
(defun for-each-dired-marked-file(fn)
"Do stuff for each marked file, only works in dired window"
(interactive)
(if (eq major-mode 'dired-mode)
(let ((filenames (dired-get-marked-files)))
(mapcar fn filenames))
(error (format "Not a Dired buffer \(%s\)" major-mode))))