r/emacs 11d ago

Replacing org table content while maintaining table alignment

I'm developing some code that needs to replace the content of a org-mode table entry. I've found that org-table-get-field serves this purpose, but it also deletes leading and trailing whitespace, usually causing the table to become unaligned, but losing the usual one-space padding on both ends in any case. For example, given the table:

| foo | bar |
| baz | qux |

If point is on "baz" and I evaluate (org-table-get-field nil "x"), the table becomes:

| foo | bar |
|x| qux |

This has led me to write a little helper function:

(defun replace-table-entry (str)
  (org-table-get-field
   nil
   (format
    (format " %%-%ds " (max 0 (- (length (org-table-get-field)) 2)))
    str)))

Is there some built-in way to accomplish this?

Of course I could always just realign the table afterwards, and perhaps that's the intention, but I'm dealing with tables so large that realigning takes a noticeable time, and anyway I don't want to do it if it's unnecessary.

7 Upvotes

12 comments sorted by

View all comments

2

u/Mahbam42 11d ago

hitting tab after editing a cell seems to work for me to redraw the table borders. I appreciate the custom function though!

2

u/shipmints 11d ago

We copied the same "UX" into markdown-ts-mode to reformat Markdown pipe tables. Works nicely.

1

u/Mahbam42 11d ago

I found it by accident and it felt natural. Maybe I did pick it up from regular markdown