30

I like to write in Markdown and often find myself needing tables. Are there any good ways of editing Markdown's pipe tables in Emacs? I am referring to this kind of syntax:

| Header | Header | Right |
|--------|--------|------:|
|  Cell  |  Cell  |  $10  |
|  Cell  |  Cell  |  $20  |

I first tried Emacs' table mode which is nice, but is designed for "grid tables" which are not supported by Markdown (let's say in Github's Markdown).

There is also org-mode's table mode which can be used as a minor mode. This comes pretty close; but the intersections are now replaced by + characters and there is no support the alignment colon. So org-tblmode first gives me something like this:

| Header | Header | Right |
|--------+--------+-------|
| Cell   | Cell   | $10   |
| Cell   | Cell   | $20   |

which I then need to manually edit to the following (editing intersection characters and adding alignment colon):

| Header | Header | Right |
|--------|--------|------:|
| Cell   | Cell   | $10   |
| Cell   | Cell   | $20   |

Is there some may that org-tblmode can also handle this? What else do you use/suggest for editing Markdown's pipe tables in Emacs?

0

7 Answers 7

11

OrgMode has nice function orgtbl-to-generic for converting orgmode' tables to alien formats. I found simple example defining custom convertor based on orgtbl-to-generic: https://gist.github.com/yryozo/5807243. Also see explanation of ORGTBL RECEIVE/SEND features here: http://dynamic-thinking.blogspot.ru/2009/11/orgtbl-mode.html. You need to define custom orgtbl-to-gfm function in Emacs and place it to your autoload then you may use minor mode orgtbl-mode for editing tables.

Small restriction: only right and left column alignments supported because Emacs OrgMode inside self doesn't supports central alignment.

See above sample org-mode source:

<!---
#+ORGTBL: SEND sample orgtbl-to-gfm
| Column 1      | Column 2 |
|---------------+----------|
|               | <l>      |
| Sample line 1 | 100      |
| Sample line 2 | 200      |
-->

And the result in markdown converted from the org-mode source:

<!--- BEGIN RECEIVE ORGTBL sample -->
| Column 1 | Column 2 |
|---|---|
| Sample line 1 | 100 |
| Sample line 2 | 200 |
<!--- END RECEIVE ORGTBL sample -->

Both them placed in the same file.

2
  • Adding samples was much appreciated. Mar 1, 2014 at 0:04
  • 1
    @CharlesMerriam I added samples to the answer. Jul 1, 2014 at 14:57
10

This is what I use to deal with tables in markdown mode. May be a bit of a hack but works well enough for me. It adds a local hook to a markdown buffer which, on save, replaces "-+-" with "-|-" in the entire buffer.

(require 'org-table)

(defun cleanup-org-tables ()
  (save-excursion
    (goto-char (point-min))
    (while (search-forward "-+-" nil t) (replace-match "-|-"))
    ))

(add-hook 'markdown-mode-hook 'orgtbl-mode)
(add-hook 'markdown-mode-hook
          (lambda()
            (add-hook 'after-save-hook 'cleanup-org-tables  nil 'make-it-local)))
0
10

markdown-mode has the markdown-do command (bound to C-c C-d). When point is in a table, it pads all the columns so they're aligned.

https://github.com/jrblevin/markdown-mode#usage

1
  • 1
    In my case, the TAB key works, too.
    – Glenn
    Feb 25, 2022 at 1:59
4

Bind the function to a key for a right-aligned conversion of a region:

(defun markdown-regexp-right (beg end)
  (interactive "r")
  (replace-regexp "-\|[^-]" "-:|\n" nil beg end)    
  (replace-regexp "-\\+-" "-|-" nil beg end)
)

This will replace -+- with -|- and replace -| with :| in the right alignment case.

Note that \n is included, because this makes sure the other -|- don't get changed to -:|, but only -| when it is followed by a new-line.

8
  • I appreciate your input but unfortunately when I try this code it crashes Emacs for me :/ With the second line commented out it seems to work, so maybe it is endlessly looping and causing a stack overflow.. Jan 14, 2013 at 8:46
  • Does it do the job otherwise? Jan 14, 2013 at 9:55
  • Oh, and are you calling it on a region? Jan 14, 2013 at 9:55
  • Yes I call it on a region, and without the (replace-regexp "-\|[^-]" "-:|\n" nil beg end) line it works fine (it just replaces the intersections) Jan 14, 2013 at 10:02
  • Anything else that you think should be added? Jan 14, 2013 at 22:38
3

Org-mode is so enticingly close that I believe this is a case for its minor mode orgtbl with arbitrary syntax to convert. A line containing :-, -: or :-: would thus have its colons removed, and a second line with <l>, <c> and <r> added to inform org-mode of the alignment. The translation back shouldn't be too hard then. Sadly I'm not good enough at Emacs to write it right now. Incidentally, pandoc's markdown parser does accept + as generated by org-mode.

Having looked a bit more at it, I believe the existing hooks in org-mode require a bit much cruft around the text, and some editing functions are in order. Since this is my first attempt at emacs lisp, my emacs lisp to convert between orgtbl and markdown is nothing short of horrid, but I have managed to convert a test table.

1

I ran into this exact problem as well (I'm a recent emacs convert), and I wrote a little AWK script that can convert the "grid tables" you mentioned (i.e. not using org-mode tables) into GFM tables.

There's a couple ways you can use this script. All you have to do is mark the table, then type C-u M-| name-of-awk-script RET (I learned this trick from this Stackoverflow thread). That will use the region as the stdin of the AWK script and replace the region with the output. I'm very much a noob at writing ELisp, but I also wrote a couple of helper functions. The table-gfm-export function currently does not replace the text in the same way as doing it interactively with C-u M-| would, because it still leaves the original table in the buffer.

(defun table-gfm-capture (start end)
  "convert Markdown table to Emacs table
there should be no pipes beginning or ending the line,
although this is valid syntax. Loses justification."
  (interactive "r")
  ;; should prompt user for justification
  (table-capture start end "|"
         "[\n][:|-]*" 'center))

(defun table-gfm-export (start end)
  "uses AWK script to convert Emacs table to
GFM Markdown table"
  (interactive "r")
  ;; replace gfm_table_format if necessary
  (shell-command-on-region start end "gfm_table_format" t t)
  (table-unrecognize))

One neat thing about this script is that it can also recognize the justification of the columns using some simple regexes. The other function table-gfm-capture, is unable to maintain the justification, so you can't freely switch back and forth. This system is pretty much designed for doing all editing in table mode and then exporting to GFM at the very end. You would Emacs would already have the ability to generate Markdown tables using table-generate-source, but alas.

#!/usr/bin/env awk -f
# -*- mode: awk -*-

BEGIN {
    FS="|";
    first=1;
}

function detect_justification(f) {
    if (match(f, /^ .* $/)) {
        return 0;               # center-justified
    } else if (match(f, / $/)) {
        return -1;              # left-justified
    } else { return 1; }        # right-justified
}

function gen_field(len, just) {
    str = sprintf("%*s", len, "");
    gsub(/ /, "-", str);
    if (just <= 0) {
        # left or center, start with :
        sub(/-/, ":", str);
    }
    if (just >= 0) {
        # right or center, end with :
        sub(/-$/, ":", str);
    }
    return str;
}

function gen_rule() {
    str = "";
    # ignore first and last empty fields
    for (i=1; i < NF; i++) {
        len = length($i);
        just = detect_justification($i);
        str = sprintf("%s%s|", str, gen_field(len, just));
    }
    return str;
}

function sanitize_line(line) {
    # strip outer pipes and trailing whitespace
    if (index(line, "|") == 1) {
        line = substr(line, 2);
    }
    sub(/[ |]*$/, "", line);
    return line;
}

! /^\+/ {
    print(sanitize_line($0));
    if (first) {
        print(sanitize_line(gen_rule()));
        first = 0;
    }
}
0

Markdown-mode package provides table support for GitHub flavored markdown.

Markdown-mode is part of Spacemacs (and probably other community configurations). Note that if using markdown and org layers in Spacemacs, orgtbl will hijack some key bindings, i.e. TAB and format tables using org syntax. Disabling orgtbl-mode removed the orgtbl highjack.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.