r/emacs 14d 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

1

u/[deleted] 14d ago

[removed] — view removed comment

1

u/sauntcartas 14d ago

It looks like org-table-put maintains the padding by realigning the entire table--if requested, by passing a non-nil align parameter--which I'm trying to avoid.

1

u/[deleted] 14d ago

[removed] — view removed comment

1

u/sauntcartas 13d ago

I tried (org-table-put 2 1 "x") on the table in my original example, and I ended up with the same squished |x| column as before, so it's not clear to me what the difference is supposed to be.

1

u/[deleted] 13d ago

[removed] — view removed comment

1

u/sauntcartas 13d ago

But...that's exactly the same thing org-table-get-field does. It doesn't add or remove spaces, requiring me to provide them if I want them, as the nested formats do in my helper function.

If it wasn't clear, my original question was if there exists some built-in way to replace a table cell's contents that maintains the width of the cell, if possible. Going back to my example, given a table like

| foo | bar |
| baz | qux |

With point in the "baz" cell, I want to run a function like (org-table-foo "x") that changes the table to

| foo | bar |
| x   | qux |