Emacs orgtbl-mode export to LaTeX matrix


11.02.11 Posted in Emacs by

Here’s one thing I know: I love Emacs, LaTeX, and matrices.

I often find myself typesetting matrices, and it’s a huge pain. I’m just not good at hitting the ‘&’ character.

To mitigate my suffering (#firstworldproblems), I wrote a few lines of Lisp that will allow me to use orgtbl-mode to typeset matrices. If you’re not familiar with orgtbl-mode and how it can improve your life, check this out for a simple LaTeX table example.

With the below code somewhere in your Emacs init file, you can use the much simpler org-mode table shortcuts to create a table, and then have that immediately exported to a LaTeX bmatrix environment.

Check out the cool behavior with matrices pasted from MATLAB. You’ll definitely want to bump this up to 720p.

To typeset a matrix from MATLAB copy it to your clipboard and do the following:

M-x orgtbl-mode (if you don’t have orgtbl-mode in your LaTeX mode hook)
M-x orgtbl-insert-matrix
Paste your matrix
C-x C-x  (which exchages point and mark to easily select pasted text)
C-c | (orgtbl-create-or-convert-from-region)
C-c C-c (to perform the export)

That’s it!

Here’s the code.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
(defun orgtbl-to-latex-matrix (table params)
  "Convert the Orgtbl mode TABLE to a LaTeX Matrix."
  (interactive)
  (let* ((params2
          (list
           :tstart (concat "\\[\n\\begin{bmatrix}")
           :tend "\\end{bmatrix}\n\\]"
           :lstart "" :lend " \\\\" :sep " & "
           :efmt "%s\\,(%s)" :hline "\\hline")))
    (orgtbl-to-generic table (org-combine-plists params2 params))))


(defun orgtbl-insert-matrix ()
  "Insert a radio table template appropriate for this major mode."
  (interactive)
  (let* ((txt orgtbl-latex-matrix-string)
         name pos)
    (setq name (read-string "Table name: "))
    (while (string-match "%n" txt)
      (setq txt (replace-match name t t txt)))
    (or (bolp) (insert "\n"))
    (setq pos (point))
    (insert txt)
    (previous-line)
    (previous-line)))

(defcustom orgtbl-latex-matrix-string  "% BEGIN RECEIVE ORGTBL %n
% END RECEIVE ORGTBL %n
\\begin{comment}
#+ORGTBL: SEND %n orgtbl-to-latex-matrix :splice nil :skip 0

\\end{comment}\n"

  "Template for the latex matrix orgtbl translator
All occurrences of %n in a template will be replaced with the name of the
table, obtained by prompting the user."

  :type 'string
  :group 'org-table)


Comments are closed.

Social Networks
Links
Search the Archives: