Search code examples
emacsorg-modeliterate-programmingorg-babel

org-mode File Specific Functions


I am working on a literate program in org-mode. I have couple of functions in my .emacs that I use to setup a repl for the program, is it possible to move these functions to the org-mode file and they are evaluated every time the file is opened (like buffer local vars but with functions.)


Solution

  • You should be able to do this using the special eval file-local variable (emphasis mine):

    Some "variable names" have special meanings in a local variables list:

    • mode enables the specified major mode.
    • eval evaluates the specified Lisp expression (the value returned by that expression is ignored).
    • coding specifies the coding system for character code conversion of this file. See Coding Systems.
    • unibyte says to load or compile a file of Emacs Lisp in unibyte mode, if the value is t. See Disabling Multibyte.

    So, for example, an Org file that has this first line

    # -*- eval: (message "foo"); -*-
    

    or a block like this within the last 3000 characters of the file

    # Local Variables:
    # eval: (message "foo")
    # End:
    

    will evaluate (message "foo") when the file is opened.

    This is a security risk, so you will be prompted when you open the file. You can use y to evaluate it once or ! to save it as a safe evaluation in your custom file and avoid future prompts.

    Edit:

    This is a bit awkward, but here is a way to evaluate a named source block on file load:

    # -*- eval: (progn (org-babel-goto-named-src-block "foo") (org-babel-execute-src-block-maybe)) -*-
    
    #+NAME: foo
    #+BEGIN_SRC emacs-lisp :results silent
      (message "Yes, it worked")
    #+END_SRC
    

    Unfortunately I don't see any way to call the named block directly, and this way you get prompted for security two times: once for the eval and once for the code block foo.