diff --git a/config.el b/config.el index ac8fc5e..79bce88 100644 --- a/config.el +++ b/config.el @@ -325,49 +325,18 @@ Bound to cmd+v in org-mode and markdown-mode." ;;; ORG MODE — LATEX EXPORT ;;; ============================================================ -;; Count data columns in an Org table line -(defun my/org-count-table-columns (line) - "Count the number of data columns in Org table LINE." - (length (cl-remove-if - (lambda (s) (string-match-p "^-*$" (string-trim s))) - (cdr (butlast (split-string line "|")))))) - -;; Generate tabularx column spec: first column left-aligned, rest Y (auto-width) -(defun my/org-table-attr-latex-spec (ncols) - "Return tabularx column spec for NCOLS columns: first l, rest Y." - (concat "l" (make-string (max 0 (1- ncols)) ?Y))) - -;; Automatically insert #+ATTR_LATEX tabularx before tables on LaTeX export. -;; inhibit-modification-hooks prevents org-element-cache from recursing -;; during the insert (which caused max-lisp-eval-depth on Emacs 31). -(defun my/org-auto-tabularx (backend) - "Insert #+ATTR_LATEX tabularx before each table when exporting to LaTeX." +;; LaTeX table export: use tabularx automatically — no buffer modification. +;; Setting a buffer-local variable in the hook is safe (no insert = no recursion). +;; org-latex.el natively handles tabularx/tabulary by adding \linewidth width arg. +(defun my/org-set-tabularx (backend) + "Set tabularx as default LaTeX table environment for this export." (when (org-export-derived-backend-p backend 'latex) - (let ((inhibit-modification-hooks t)) - (save-excursion - (goto-char (point-min)) - (while (not (eobp)) - (cond - ((looking-at "^|") - (let ((prev-line (save-excursion - (forward-line -1) - (buffer-substring-no-properties - (line-beginning-position) (line-end-position))))) - (when (not (string-match-p "^|" prev-line)) - (when (not (string-match-p "^#\\+ATTR_LATEX" prev-line)) - (let* ((table-line (buffer-substring-no-properties - (line-beginning-position) (line-end-position))) - (ncols (my/org-count-table-columns table-line)) - (spec (my/org-table-attr-latex-spec ncols)) - (attr (format "#+ATTR_LATEX: :environment tabularx :width \\textwidth :align %s\n" - spec))) - (when (> ncols 0) - (insert attr))))) - (forward-line)) - (t - (forward-line))))))))) + (setq-local org-latex-default-table-environment "tabularx"))) -(add-hook 'org-export-before-processing-hook #'my/org-auto-tabularx) +(add-hook 'org-export-before-processing-hook #'my/org-set-tabularx) + +(with-eval-after-load 'ox-latex + (add-to-list 'org-latex-packages-alist '("" "tabularx"))) ;; Optional: enable booktabs style (horizontal rules in tables) ;; (setq org-latex-tables-booktabs t)