Starter Kit Org

This is part of the Emacs Starter Kit.

Starter Kit Org

Configuration for the eminently useful Org Mode.

Org-mode is for keeping notes, maintaining ToDo lists, doing project planning, and authoring with a fast and effective plain-text system. Org Mode can be used as a very simple folding outliner or as a complex GTD system or tool for reproducible research and literate programming.

For more information on org-mode check out worg, a large Org-mode wiki which is also implemented using Org-mode and git.

Org-Mode hooks

Keybindings

(add-hook 'org-mode-hook
            (lambda ()
              (local-set-key "\C-n" 'outline-next-visible-heading)
              (local-set-key "\C-p" 'outline-previous-visible-heading)
              (local-set-key "\C-u" 'outline-up-heading)
              ;; table
              (local-set-key "\M-\C-w" 'org-table-copy-region)
              (local-set-key "\M-\C-y" 'org-table-paste-rectangle)
              (local-set-key "\M-\C-l" 'org-table-sort-lines)
              ;; display images
              (local-set-key "\M-I" 'org-toggle-inline-image)))

Minor mode

(add-hook 'org-mode-hook
          (lambda ()
            (yas-minor-mode -1)
            (org-indent-mode  t)
            (org-bullets-mode t)
            (auto-complete-mode t)
            (linum-mode -1)
            (hl-line-mode t)
            (diminish 'org-indent-mode)))

Org-Mode keybindings

ox-latex

(require 'ox-latex)
(define-key org-mode-map (kbd "s-p") 'org-latex-export-to-pdf)
(define-key org-mode-map (kbd "s-l") 'org-latex-export-to-latex)
(define-key org-mode-map (kbd "s-h") 'org-html-export-to-html)

ox-beamer

(require 'ox-beamer)
(define-key org-beamer-mode-map (kbd "s-p") 'org-beamer-export-to-pdf)
(define-key org-beamer-mode-map (kbd "s-l") 'org-beamer-export-to-latex)

Source block

(define-key org-mode-map "\C-x\C-a" 'org-babel-mark-block)

Org-Mode settings

Setting org timestamp directory

(setq org-publish-timestamp-directory (concat temporary-file-directory "org-timestamps"))

Ellipsis

(setq org-ellipsis "…"
      org-columns-ellipses "…")

Using ido completing

(setq org-completion-use-ido t)

Use speed keys

Speed commands enable single-letter commands in Org-mode files when the point is at the beginning of a headline, or at the beginning of a code block.

See the org-speed-commands-default variable for a list of the keys and commands enabled at the beginning of headlines. All code blocks are available at the beginning of a code block, the following key sequence C-c C-v h (bound to org-babel-describe-bindings) will display a list of the code blocks commands and their related keys.

(setq org-use-speed-commands t)

Easy templates

(add-to-list 'org-structure-template-alist '("al" "#+BEGIN_SRC latex :results drawer :exports results\n\\begin{align*}\n?\\end{align*}\n#+END_SRC"))

Special word faces

(defface my/highlight-face
  '((t (:weight normal :slant normal :box '(:line-width 1 :color "#CC0000")
                :foreground "#CC0000" :background "#FFFF88")))
  "Face for making FIXME and other warnings stand out.")

(defvar my/highlight-org-regexps
  "\\(FIXME\\|BUG\\|XXX\\|[Ee]rror\\|[Ww]arning\\|WARNING\\)"
  "Patterns to highlight (for Org mode only, to ensure no conflict with the
  Org mode TODO keyword).")

;; set up highlighting of special patterns for Org mode only
(dolist (mode '(org-mode
                orgtbl-mode))
  (font-lock-add-keywords mode
                          `((,my/highlight-org-regexps 1 'my/highlight-face
                                                       prepend))))

Turn on automatic renumbering of footnotes

(setq org-footnote-auto-adjust t)

Random footnote label

(setq org-footnote-auto-label 'random)

Code blocks

This activates a number of widely used languages, you are encouraged to activate more languages using the customize interface for the org-babel-load-languages variable, or with an elisp form like the one below. The customize interface of org-babel-load-languages contains an up to date list of the currently supported languages.

Supported languages

(org-babel-do-load-languages
 'org-babel-load-languages
 '((emacs-lisp . t)
   (shell . t)
   (C . t)
   (python . t)
   (latex . t)
   (gnuplot . t)))

You are encouraged to add the following to your personal configuration although it is not added by default as a security precaution.

(setq org-confirm-babel-evaluate nil)

Fontification

The following displays the contents of code blocks in Org-mode files using the major-mode of the code. It also changes the behavior of TAB to as if it were used in the appropriate major mode. This means that reading and editing code form inside of your Org-mode files is much more like reading and editing of code using its major mode.

(setq org-src-fontify-natively  t)
(setq org-src-tab-acts-natively t)

Code progression

A progress indicator for code blocks in org-mode courtesy of John Kitchin

(defadvice org-babel-execute-src-block (around progress nil activate)
  ;; (set-face-attribute
  ;;  'org-block-background nil :background "LightSteelBlue")
  (message "Running your code block")
  ad-do-it
  ;; (set-face-attribute 'org-block-background nil :background "gray")
  (message "Done with code block"))

Narrowing code block

Stolen from http://endlessparentheses.com/emacs-narrow-or-widen-dwim.html

(defun narrow-or-widen-dwim (p)
  "If the buffer is narrowed, it widens. Otherwise, it narrows intelligently.
  Intelligently means: region, org-src-block, org-subtree, or defun,
  whichever applies first.
  Narrowing to org-src-block actually calls `org-edit-src-code'.

  With prefix P, don't widen, just narrow even if buffer is already
  narrowed."
  (interactive "P")
  (declare (interactive-only))
  (cond ((and (buffer-narrowed-p) (not p)) (widen))
        ((region-active-p)
         (narrow-to-region (region-beginning) (region-end)))
        ((derived-mode-p 'org-mode)
         ;; `org-edit-src-code' is not a real narrowing command.
         ;; Remove this first conditional if you don't want it.
         (cond ((ignore-errors (org-edit-src-code))
                (delete-other-windows))
               ((org-at-block-p)
                (org-narrow-to-block))
               (t (org-narrow-to-subtree))))
        (t (narrow-to-defun))))

;; This line actually replaces Emacs' entire narrowing keymap, that's
;; how much I like this command. Only copy it if that's what you want.
(define-key org-mode-map "\C-x\C-n" #'narrow-or-widen-dwim)

The Library of Babel

The library of babel contains makes many useful functions available for use by code blocks in any emacs file. See the actual library-of-babel.org (located in the Org-mode contrib/babel directory) file for information on the functions, and see worg:library-of-babel for more usage information.

Code blocks can be loaded into the library of babel from any Org-mode file using the org-babel-lob-ingest function.

(org-babel-lob-ingest (expand-file-name "starter-kit-org.org" starter-kit-dir))

LaTeX hacks

VC status

Use smart quote when exporting

(setq org-export-with-smart-quotes nil)

Add cite link

(org-add-link-type "cite" 'ebib
 (lambda (path desc format)
   (cond
    ((eq format 'html)  (format "(<cite>%s</cite>)" path))
    ((eq format 'latex) (format "\\cite{%s}" path)))))

Keep LaTeX logfiles

(setq org-latex-remove-logfiles nil)

Default list of LaTeX packages

(add-to-list 'org-latex-packages-alist '("" "org-preamble"))

Defining org-latex classes

(unless (boundp 'org-latex-classes)
  (setq org-latex-classes nil))
  • General article class
    (add-to-list 'org-latex-classes
                 '("article"
                   "\\documentclass{article}
                    [NO-DEFAULT-PACKAGES]
                     \\usepackage{libertineotf}"
                   ("\\section{%s}" . "\\section*{%s}")
                   ("\\subsection{%s}" . "\\subsection*{%s}")
                   ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
                   ("\\paragraph{%s}" . "\\paragraph*{%s}")
                   ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
    
  • SuperNEMO articles
    • DocDB article
      (add-to-list 'org-latex-classes
                   '("snemo-article"
                     "\\documentclass{scrartcl}
                      \\setkomafont{disposition}{\\normalfont\\bfseries}
                      [PACKAGES]
                      \\usepackage{supernemo-article-style}
                      [NO-DEFAULT-PACKAGES]"
                     ("\\section{%s}" . "\\section*{%s}")
                     ("\\subsection{%s}" . "\\subsection*{%s}")
                     ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
                     ("\\paragraph{%s}" . "\\paragraph*{%s}")
                     ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
      
    • Note taking
      (add-to-list 'org-latex-classes
                   '("snemo-note"
                     "\\documentclass{scrartcl}
                      [PACKAGES]
                      \\usepackage{supernemo-note-style}
                      [NO-DEFAULT-PACKAGES]"
                     ("\\section{%s}" . "\\section*{%s}")
                     ("\\subsection{%s}" . "\\subsection*{%s}")
                     ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
                     ("\\paragraph{%s}" . "\\paragraph*{%s}")
                     ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
      
    • SN@ilWare markup filter
      (defun snailware-markup-filter (contents backend info)
         (when (eq backend 'latex)
           (replace-regexp-in-string "SN@ilware" "\\\\Snailware" contents)))
       (add-to-list 'org-export-filter-final-output-functions 'snailware-markup-filter)
      
  • Memoir article
    (add-to-list 'org-latex-classes
                 '("memoir-article"
                   "\\documentclass[11pt,oneside,article]{memoir}
                    [PACKAGES]
                    \\usepackage{memoir-article-style}
                    [NO-DEFAULT-PACKAGES]"
                   ("\\section{%s}" . "\\section*{%s}")
                   ("\\subsection{%s}" . "\\subsection*{%s}")
                   ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
                   ("\\paragraph{%s}" . "\\paragraph*{%s}")
                   ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
    
  • Beamer template
    (add-to-list 'org-latex-classes
                 '("beamer"
                   "\\documentclass[c]{beamer}
                    [PACKAGES]
                    \\usepackage{custom-beamer}
                    [NO-DEFAULT-PACKAGES]"
                   ("\\section{%s}" . "\\section*{%s}")
                   ("\\subsection{%s}" . "\\subsection*{%s}")
                   ("\\subsubsection{%s}" . "\\subsubsection*{%s}")
                   ("\\paragraph{%s}" . "\\paragraph*{%s}")
                   ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))
    
    • bold becomes structure

      We also translate bold into beamer structure.

      (defun sk-beamer-bold (contents backend info)
        (when (eq backend 'beamer)
          (replace-regexp-in-string "\\`\\\\[A-Za-z0-9]+" "\\\\structure" contents)))
      (defun sk-beamer-underline (contents backend info)
        (when (eq backend 'beamer)
          (replace-regexp-in-string "\\`\\\\[A-Za-z0-9]+" "\\\\textbf" contents)))
      (defun sk-beamer-strike (contents backend info)
        (when (eq backend 'beamer)
          (replace-regexp-in-string "\\`\\\\[A-Za-z0-9]+" "\\\\alert" contents)))
      
      (add-to-list 'org-export-filter-bold-functions 'sk-beamer-bold)
      (add-to-list 'org-export-filter-underline-functions 'sk-beamer-underline)
      (add-to-list 'org-export-filter-strike-through-functions 'sk-beamer-strike)
      
    • Use strike as alert

      Change the face of strike-through

      (require 'cl)
      (setq org-emphasis-alist
            (cons '("+" '(:inherit org-warning :inherit bold))
                  (delete* "+" org-emphasis-alist :key 'car :test 'equal)))
      
    • Add frame option to footnote
      (defun sk-beamer-footnote (contents backend info)
        (when (eq backend 'beamer)
          (replace-regexp-in-string "\\`\\\\[A-Za-z0-9]+" "\\\\footnote[frame]" contents)))
      (add-to-list 'org-export-filter-footnote-reference-functions 'sk-beamer-footnote)
      
    • Add email
      (setq user-mail-address nil)
      (defun sk-beamer-email (options backend)
        "Insert EMAIL as \email{EMAIL} in the latex backend when EMAIL is present."
        (when (and (org-export-derived-backend-p backend 'latex)
                   (plist-get options :with-email))
          (plist-put options :latex-header
                     (mapconcat 'identity
                                (remove nil
                                        (list
                                         (plist-get options :latex-header)
                                         (format "\\email{%s}"
                                                 (plist-get options :email))))
                                "\n"))
          ;; don't insert email in \thanks{.}
          (plist-put options :with-email nil))
        options)
      
      (add-to-list 'org-export-filter-options-functions 'sk-beamer-email)
      
    • Colored box environment

      We define a new environment for "colored" box

      (add-to-list 'org-beamer-environments-extra
                   '("cbox" "c" "\\begin{cbox}%o(%h)" "\\end{cbox}"))
      

      Since 26/09/2014, it seems that fragment block are not "lowercased" anymore so we execute a hook before parsing file to change CBOX into cbox.

      (defun sk-beamer-cbox (backend)
        (when (eq backend 'beamer)
          (replace-regexp "CBOX" "cbox")))
      (add-to-list 'org-export-before-parsing-hook 'sk-beamer-cbox)
      
    • Empty outline title
      (setq org-beamer-outline-frame-title "")
      (setq org-beamer-outline-frame-options "plain")
      

Filters

  • Ignore headline

    Add a new tag to skip headline tagged as such.

    (defun sk-ignore-headline (backend)
      (when (org-export-derived-backend-p backend 'latex)
        (delete-matching-lines "::")))
    (add-to-list 'org-export-before-parsing-hook 'sk-ignore-headline)
    
  • Remove section number

    Add a new tag to remove section number from headline.

    (defun sk-ignore-section-number (contents backend info)
      (when (and (org-export-derived-backend-p backend 'latex)
                 (string-match "\\`.*.*\n"
                               (downcase contents)))
        (replace-regexp-in-string "\\`\\\\[A-Za-z0-9]+" "\\\\section\*"
        (replace-regexp-in-string "\\\\textsc{}" "" contents))))
      (add-to-list 'org-export-filter-headline-functions 'sk-ignore-section-number)
    
  • Change table into figure env

    When graphics are placed into table cells then change the default table environment into figure

    (defun sk-multicolumn-figure (contents backend info)
      (when (and (org-export-derived-backend-p backend 'latex)
                 (string-match "table" contents)
                 (string-match "includegraphics" contents))
        (replace-regexp-in-string "table" "figure" contents)))
    (add-to-list 'org-export-filter-table-functions 'sk-multicolumn-figure)
    

KOMA/LaTeX script

Define a special org-latex-classes to make use of KOMA/LaTeX letter style. The ox-koma-letter backend from org-mode contribution directory must be properly installed or loaded. To produce org-mode to LaTeX to PDF export, you should use the org-koma-letter-export-to-pdf command.

(setq org-koma-letter-email  nil)
(setq org-koma-letter-author nil)
(setq org-koma-letter-from-address "")
(add-to-list 'org-latex-classes
             '("koma-letter"
               "\\documentclass{scrlttr2}
                [NO-DEFAULT-PACKAGES]"))

Define org-latex-pdf-process command

(setq org-latex-pdf-process (list "xelatex -shell-escape %f"))

Add new LATEX_CMD option to choose between pdflatex and xelatex

From org-faq

(defun sk-latexmk-cmd (backend)
  "When exporting from .org with latex, automatically run latex,
     pdflatex, or xelatex as appropriate, using latexmk."
  (when (org-export-derived-backend-p backend 'latex)
    (let ((texcmd)))
    ;; default command: xelatex
    (setq texcmd "jobname=$(basename %f | sed 's/\.tex//');latexmk -xelatex -shell-escape -quiet %f && mkdir -p latex.d && mv ${jobname}.* latex.d/. && mv latex.d/${jobname}.{org,pdf,fdb_latexmk,aux} .")
    ;; pdflatex -> .png
    (if (string-match "LATEX_CMD: pdflatex" (buffer-string))
        (setq texcmd "latexmk -pdf -shell-escape -quiet %f"))
    ;; xelatex -> .png
    (if (string-match "LATEX_CMD: xelatex" (buffer-string))
        (setq texcmd "latexmk -xelatex -shell-escape -quiet %f"))
    ;; LaTeX compilation command
    (setq org-latex-pdf-process (list texcmd))))

(org-add-hook 'org-export-before-processing-hook 'sk-latexmk-cmd)

Minted setup

(setq org-latex-listings 'minted)
(setq org-latex-minted-options
      '(;;("frame" "lines")
        ("fontsize" "\\footnotesize")
        ("mathescape" "")
        ("samepage" "")
        ("xrightmargin" "0.5cm")
        ("xleftmargin"  "0.5cm")
        ))

Place table caption below table

(setq org-latex-table-caption-above nil)

Configuring org-latex-preview

  • Set the program to create formula (either dvipng or imagemagick)
(setq org-latex-create-formula-image-program 'imagemagick)
  • Set the output directory
(setq org-latex-preview-ltxpng-directory "ltxpng/")

Org-reveal   nottangle

org-reveal exports org documents to reveal.js presentations.

(require 'ox-reveal)
(setq org-reveal-root "http://cdn.jsdelivr.net/reveal.js/2.5.0/")
(setq org-reveal-hlevel 2)
(setq org-reveal-control nil)
;;(setq org-reveal-theme "solarized")

Filters

  • Change pdf file to png image
    (defun sk-change-pdf-to-png (backend)
      (when (org-export-derived-backend-p backend 'reveal)
        (while (re-search-forward "\\(.png\\)" nil t)
          (replace-match ".png"))))
    
    (add-hook 'org-export-before-parsing-hook 'sk-change-pdf-to-png)
    

Prevent editing invisible text

The following setting prevents accidentally editing hidden text when the point is inside a folded region. This can happen if you are in the body of a heading and globally fold the org-file with S-TAB

I find invisible edits (and undo's) hard to deal with so now I can't edit invisible text. C-c C-r (org-reveal) will display where the point is if it is buried in invisible text to allow editing again.

(setq org-catch-invisible-edits 'error)

Org fold to store folding state

Stolen from Dan Davison git account. Just changing the directory where the .fold file is saved.

(setq org-fold-directory (concat temporary-file-directory "org-fold/"))
(unless (file-exists-p org-fold-directory)
  (make-directory org-fold-directory))

(defun org-fold-get-fold-info-file-name ()
  (concat org-fold-directory (buffer-name) ".fold"))

(defun org-fold-save ()
  (save-excursion
    (goto-char (point-min))
    (let (foldstates)
      (unless (looking-at outline-regexp)
        (outline-next-visible-heading 1))
      (while (not (eobp))
        (push (if (some (lambda (o) (overlay-get o 'invisible))
                        (overlays-at (line-end-position)))
                  t)
              foldstates)
        (outline-next-visible-heading 1))
      (with-temp-file (org-fold-get-fold-info-file-name)
        (prin1 (nreverse foldstates) (current-buffer))))))

(defun org-fold-restore ()
  (save-excursion
    (goto-char (point-min))
    (let* ((foldfile (org-fold-get-fold-info-file-name))
           (foldstates
            (if (file-readable-p foldfile)
                (with-temp-buffer
                  (insert-file-contents foldfile)
                  (read (current-buffer))))))
      (when foldstates
        (show-all)
        (goto-char (point-min))
        (unless (looking-at outline-regexp)
          (outline-next-visible-heading 1))
        (while (and foldstates (not (eobp)))
          (if (pop foldstates)
              (hide-subtree))
          (outline-next-visible-heading 1))
        (message "Restored saved folding state")))))

(add-hook 'org-mode-hook 'org-fold-activate)

(defun org-fold-activate ()
  (org-fold-restore)
  (add-hook 'before-save-hook 'org-fold-save        nil t)
  (add-hook 'auto-save-hook   'org-fold-kill-buffer nil t))

(defun org-fold-kill-buffer ()
  ;; don't save folding info for unsaved buffers
  (unless (buffer-modified-p)
    (org-fold-save)))

Functions for orgtbl

Sending all table

From Carsten Dominik

(defun sk-org-send-all-tables ()
   (interactive)
   (org-table-map-tables
      (lambda () (orgtbl-send-table 'maybe))))

Aligning all table

(defun sk-org-align-all-tables ()
  (interactive)
  (org-table-map-tables 'org-table-align 'quietly))

Org capture

Emacs Org-mode has a feature called Org-capture that makes it easy to keep track of all the to-do's that crop up as we work on projects. With Org-capture you can make comments across all your files and projects and link to them all from one place.

Setting the TODO file location

(setq org-default-notes-file "~/Development/org-notes/misc/todo-list.org")

Closing items

The most basic logging is to keep track of when a certain TODO item was finished. This is achieved with

(setq org-log-done 'time)

Org calendar

Synchronization with LAL owncloud   nottangle

(setq org-caldav-calendar-id "teaching"
      org-caldav-url "https://owncloud.lal.in2p3.fr/remote.php/caldav/calendars/garrido"
      org-caldav-files '("~/Development/org-caldav/org/teaching.org")
      org-caldav-inbox "~/Development/org-caldav/org/inbox.org")

Playing with calfw   nottangle

(require 'calfw-org)
(setq calendar-week-start-day 1) ; 0:Sunday, 1:Monday
(setq org-agenda-files nil)
(defun my-open-calendar ()
  (interactive)
  (let ((cp (cfw:create-calendar-component-buffer
             :view 'month
             :contents-sources
             (list
              (cfw:org-create-file-source
               "schedule"
               "~/Development/org-caldav/org/teaching.org"
               "#859900")))))
    (switch-to-buffer (cfw:cp-get-buffer cp))))

Misc.

Edit email from thunerbird within emacs

External editor allows to edit mail from thunderbird within emacs. Here, we just set the default writing mode to be org for .eml files.

(add-to-list 'auto-mode-alist '("\\.eml\\'" . org-mode))
File under version control - commit 135971e - 2014-11-29