This solution requires no change in init.el
(with minor modifications). It involves file-local evaluations, though - but that's exactly what the OP asked for. Advantages of the solution are:
- asks for confirmation to evaluate code
- elisp code can be edited and tested within the org-babel environment
- as the solution doesn't require modifications to
init.el
the orgmode file may be shared among (trusted) users
I'm rephrasing the solution here.
Add a src-block somewhere in your file:
#+NAME: startup
#+BEGIN_SRC emacs-lisp
(your-code-here)
#+END_SRC
Then, put this at the end of your orgmode-file:
# Local Variables:
# eval: (progn (org-babel-goto-named-src-block "startup") (org-babel-execute-src-block) (outline-hide-sublevels 1))
# End:
I've added (outline-hide-sublevels 1)
because I like to hide the src-block inside a heading and want the sublevels to be hidden on startup. Without this statement, the sublevels will become expanded by (org-babel-goto-named-src-block "startup")
.
With this solution, emacs will ask 2 times for permission to execute (1st: apply Local Variables; 2nd: execute "startup"-src-block). As I have a lot of src-blocks in my file, I've set another file-local-variable, org-confirm-babel-evaluate
, like this:
# Local Variables:
# org-confirm-babel-evaluate: nil
# eval: (progn (org-babel-goto-named-src-block "startup") (org-babel-execute-src-block) (outline-hide-sublevels 1))
# End:
Warning: With this addition, emacs will prompt only once for permission to execute - all src-blocks in that file may now be executed without further confirmation. As others have pointed out before, this behavior could be dangerous and you should be very careful with this setting.
However, I'd argue that this solution (especially the first version) is more secure than the one given by Joe Corneli because at least you will be asked for confirmation to execute. Joe's solution will evaluate the special block without confirmation, if it is found in the file. An attacker would have to guess the name of the special block, of course...
I'm using this approach to write large documents which require, e.g., adaptions to the org-export mechanisms.
# -*- eval: (lisp code here) -*-
but you also have to be aware of the dangers. Even if you don't share these documents with anyone else, the interpreted nature of Emacs Lisp will mean that a change may accidentally result in loss of data. Also, mode hook sounds like a better option if you want to run the same code for more than one file.