0

I usually have a bulk of items separated by either spaces or new lines and I want to have them all full a table with a set number of columns.

Basically if I want the table to always have 3 columns, then this text:

test1 test2     test3 test4
   test5  test6 test7

will become:

|test1|test2|test3|
|test4|test5|test6|
|test7|     |     |

How to achieve that?

2

Here is your text

test1 test2     test3 test4
   test5  test6 test7

Use C-M-% (query-replace-regexp) to group the text by three, i.e.,

;; Type C-q C-j to get <newline>
C-M-% [ <newline>]+ → \,(if (zerop (% (1+ \#) 3)) "\n" "|")

then you'll get

test1|test2|test3
test4|test5|test6
test7|

Use C-x r t (string-rectangle) to prepend | to each line, then you'll get

|test1|test2|test3
|test4|test5|test6
|test7|

Switch to org-mode and press TAB, then you'll get

| test1 | test2 | test3 |
| test4 | test5 | test6 |
| test7 |       |       |

If you want an Emacs command to do the above, you can refer to the code below:

(defun my-org-table-convert-region (b e)
  (interactive "*r")
  (let ((s (delete-and-extract-region b e))
        (old-point (point))
        (counter 0))
    (insert
     (replace-regexp-in-string
      (rx (1+ (in "\s\t\n")))
      (lambda (_)
        (if (zerop (% (cl-incf counter) 3))
            "\n"
          " "))
      (string-trim s)))
    (org-table-convert-region old-point (point) " +")))
  • Beautiful! but just to make it easier, I switched "|" to " " and afterwards applied org-table-create-or-convert-from-region. Is there a way to lump all what I described in my comment here in a function that I can call on a marked region? – SFbay007 Jan 16 at 17:24
  • 1
    @SFbay007 Not sure if I understand you correctly (my English is not very good), I've just added a function to automate the process. – xuchunyang Jan 16 at 17:50
  • That was exactly what I asked for. Thank you very much! – SFbay007 Jan 16 at 18:05
  • I found a small bug that I cant explain. When there are many variables (over 20) I noticed that the [first row, third column] is always empty! – SFbay007 Jan 16 at 18:37
  • 1
    @SFbay007 Now I understand the bug, I've update the code, I use string-trim (from subr-x.el) to remove whitespace at the beginning. – xuchunyang Jan 17 at 5:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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