fix(org-latex): tabularx filter with lYYY column spec matching template

document.org template defines Y column type (RaggedRight + auto-width X).
Filter now computes proper column spec:
  - 1 col  → Y
  - N cols → l + (N-1)*Y  (first col natural-width, rest auto-width)

Also handles tabularx{colspec} → tabularx{\linewidth}{lYYY} (missing width fix).
Works with ltablex (loaded by template) which makes tabularx also support page breaks.
This commit is contained in:
2026-02-23 15:19:26 +01:00
parent 854a6de40a
commit e084ff35ea

View File

@@ -325,31 +325,41 @@ Bound to cmd+v in org-mode and markdown-mode."
;;; ORG MODE — LATEX EXPORT
;;; ============================================================
;; LaTeX table export: tabular → tabularx{\linewidth}
;; LaTeX table export: tabular → tabularx{\linewidth} with lYYY column spec.
;; Filter on rendered LaTeX string — no buffer modification, no recursion.
;; Handles both cases:
;; \begin{tabular}{lll} → \begin{tabularx}{\linewidth}{lll}
;; \begin{tabularx}{lll} → \begin{tabularx}{\linewidth}{lll} (missing width)
;; Uses Y column type (defined in document.org template: RaggedRight + auto-width X).
;; Handles:
;; \begin{tabular}{lll} → \begin{tabularx}{\linewidth}{lYY}
;; \begin{tabularx}{lll} → \begin{tabularx}{\linewidth}{lYY} (missing width fix)
(defun my/org-latex-col-to-lyyy (spec)
"Convert tabular column SPEC to tabularx lYYY format.
Counts l/r/c columns; first → l, rest → Y (auto-width, defined in template)."
(let* ((ncols (length (replace-regexp-in-string "[^lrcLRCpP]" "" spec)))
(ncols (max 1 ncols)))
(if (= ncols 1) "Y"
(concat "l" (make-string (1- ncols) ?Y)))))
(defun my/org-latex-fix-tabularx (table _backend _info)
"Convert tabular → tabularx{\\linewidth} in LaTeX table transcoder output."
"Convert tabular → tabularx{\\linewidth}{lYYY} in LaTeX table output."
(when (stringp table)
;; Fix tabularx with missing width (org versions that don't add \linewidth)
;; Fix tabularx{colspec} missing width (some org versions omit \linewidth)
(setq table
(replace-regexp-in-string
"\\\\begin{tabularx}{\\([^\\\\][^}]*\\)}"
"\\\\begin{tabularx}{\\\\linewidth}{\\1}"
(lambda (m)
(format "\\begin{tabularx}{\\linewidth}{%s}"
(my/org-latex-col-to-lyyy (match-string 1 m))))
table))
;; Convert plain tabular to tabularx
;; Convert tabular{colspec} → tabularx{\linewidth}{lYYY}
(setq table
(replace-regexp-in-string
"\\\\begin{tabular}{\\([^}]*\\)}"
"\\\\begin{tabularx}{\\\\linewidth}{\\1}"
(lambda (m)
(format "\\begin{tabularx}{\\linewidth}{%s}"
(my/org-latex-col-to-lyyy (match-string 1 m))))
table))
(setq table
(replace-regexp-in-string
"\\\\end{tabular}"
"\\\\end{tabularx}"
table)))
(replace-regexp-in-string "\\\\end{tabular}" "\\\\end{tabularx}" table)))
table)
;; Register filter on ox-latex load AND ensure it via a pre-processing hook