table: Gracefully align hrule-only tables

* lisp/org-table.el (org-table-align): Try to align the table even
when it only consists of horizontal rules.
* testing/lisp/test-org-table.el (test-org-table/align): Add test.
This commit is contained in:
Nicolas Goaziou 2020-06-15 21:31:06 +02:00
parent a8cc4f7244
commit e3a7247b68
2 changed files with 48 additions and 29 deletions

View File

@ -4348,13 +4348,23 @@ FIELD is a string. WIDTH is a number. ALIGN is either \"c\",
(org-table-with-shrunk-columns
(let* ((table (org-table-to-lisp))
(rows (remq 'hline table))
;; Compute number of columns.
(columns-number (apply #'max (mapcar #'length rows)))
(widths nil)
(alignments nil))
(alignments nil)
(columns-number 1))
(if (null rows)
;; Table contains only horizontal rules. Compute the
;; number of columns anyway, and choose an arbitrary width
;; and alignment.
(let ((end (line-end-position)))
(save-excursion
(while (search-forward "+" end t)
(cl-incf columns-number)))
(setq widths (make-list columns-number 1))
(setq alignments (make-list columns-number "l")))
;; Compute alignment and width for each column.
(setq columns-number (apply #'max (mapcar #'length rows)))
(dotimes (i columns-number)
(let* ((max-width 1)
(let ((max-width 1)
(fixed-align? nil)
(numbers 0)
(non-empty 0))
@ -4376,7 +4386,7 @@ FIELD is a string. WIDTH is a number. ALIGN is either \"c\",
(t "l"))
alignments)))
(setq widths (nreverse widths))
(setq alignments (nreverse alignments))
(setq alignments (nreverse alignments)))
;; Store alignment of this table, for later editing of single
;; fields.
(setq org-table-last-alignment alignments)

View File

@ -1768,7 +1768,16 @@ See also `test-org-table/copy-field'."
(equal "| <c> |\n| 1 |\n| 123 |"
(org-test-with-temp-text "| <c> |\n| 1 |\n| 123 |"
(let ((org-table-number-fraction 0.5)) (org-table-align))
(buffer-string)))))
(buffer-string))))
;; Handle gracefully tables with only horizontal rules.
(should
(org-test-with-temp-text "|-<point>--|"
(org-table-align)
t))
(should
(org-test-with-temp-text "|-<point>--|---------|\n|---|---|-----|"
(org-table-align)
t)))
(ert-deftest test-org-table/align-buffer-tables ()
"Align all tables when updating buffer."