1

Given the following org-table:

| col1 | col2 | col3 | col4 |
|------+------+------+------|
|   11 |   12 | A    |   14 |
|   21 |   22 | A    |   24 |
|   31 |   32 | A    |   34 |
|   41 |   42 | B    |   44 |
|   51 |   52 | C    |   54 |
|   61 |   62 | C    |   64 |
|   71 |   72 | D    |   74 |
|------+------+------+------|

I'd like to add (either programmatically or using #+TBLFM) an hline each time the value of col3 changes. Here's the final result I'd like to obtain:

| col1 | col2 | col3 | col4 |
|------+------+------+------|
|   11 |   12 | A    |   14 |
|   21 |   22 | A    |   24 |
|   31 |   32 | A    |   34 |
|------+------+------+------|
|   41 |   42 | B    |   44 |
|------+------+------+------|
|   51 |   52 | C    |   54 |
|   61 |   62 | C    |   64 |
|------+------+------+------|
|   71 |   72 | D    |   74 |
|------+------+------+------|

Any ideas as to how this could be done ?

1 Answer 1

2

I'd like to add an hline each time the value of col3 changes

This can be done easily with an Elisp source block.

There follows the Org-mode code that does what you want.
The Elisp code is commented inside the source block.

#+NAME: mytable
| col1 | col2 | col3 | col4 |
|------+------+------+------|
|   11 |   12 | A    |   14 |
|   21 |   22 | A    |   24 |
|   31 |   32 | A    |   34 |
|   41 |   42 | B    |   44 |
|   51 |   52 | C    |   54 |
|   61 |   62 | C    |   64 |
|   71 |   72 | D    |   74 |
|------+------+------+------|

#+BEGIN_SRC emacs-lisp :var table=mytable col=3 :hlines yes :export no
(setq col (1- col)) ;;< zero-based indexing in Elisp
(append
 (list (car table) 'hline) ;;< copy headerline
 (cl-loop for row-ptr on (cddr table)
      collect (car row-ptr) ;;< copy current line
      if (and
          ;; exclude special cases:
          (cdr row-ptr)
          (null (eq (cadr row-ptr) 'hline))
          ;; "normal" test: If next line differs from current line:
          (null (equal (nth col (car row-ptr))
               (nth col (cadr row-ptr)))))
      ;; ... insert a hline:
      collect 'hline
      ))
#+END_SRC

#+RESULTS:
| col1 | col2 | col3 | col4 |
|------+------+------+------|
|   11 |   12 | A    |   14 |
|   21 |   22 | A    |   24 |
|   31 |   32 | A    |   34 |
|------+------+------+------|
|   41 |   42 | B    |   44 |
|------+------+------+------|
|   51 |   52 | C    |   54 |
|   61 |   62 | C    |   64 |
|------+------+------+------|
|   71 |   72 | D    |   74 |
|------+------+------+------|
1
  • Thank you so much: it works like a charm!
    – picchiolu
    Commented Apr 13, 2019 at 11:17

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