1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
30 ;; This file contains the table editor and spreadsheed for Org-mode.
32 ;; Watch out: Here we are talking about two different kind of tables.
33 ;; Most of the code is for the tables created with the Org-mode table editor.
34 ;; Sometimes, we talk about tables created and edited with the table.el
35 ;; Emacs package. We call the former org-type tables, and the latter
36 ;; table.el-type tables.
44 (defvar orgtbl-mode
) ; defined below
45 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
47 (defvar constants-unit-system
)
49 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
50 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
51 In the optimized version, the table editor takes over all simple keys that
52 normally just insert a character. In tables, the characters are inserted
53 in a way to minimize disturbing the table structure (i.e. in overwrite mode
54 for empty fields). Outside tables, the correct binding of the keys is
57 The default for this option is t if the optimized version is also used in
58 Org-mode. See the variable `org-enable-table-editor' for details. Changing
59 this variable requires a restart of Emacs to become effective."
63 (defcustom orgtbl-radio-table-templates
64 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
65 % END RECEIVE ORGTBL %n
67 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
70 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
71 @c END RECEIVE ORGTBL %n
73 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
76 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
77 <!-- END RECEIVE ORGTBL %n -->
79 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
82 "Templates for radio tables in different major modes.
83 All occurrences of %n in a template will be replaced with the name of the
84 table, obtained by prompting the user."
87 (list (symbol :tag
"Major mode")
88 (string :tag
"Format"))))
90 (defgroup org-table-settings nil
91 "Settings for tables in Org-mode."
92 :tag
"Org Table Settings"
95 (defcustom org-table-default-size
"5x2"
96 "The default size for newly created tables, Columns x Rows."
97 :group
'org-table-settings
100 (defcustom org-table-number-regexp
101 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
102 "Regular expression for recognizing numbers in table columns.
103 If a table column contains mostly numbers, it will be aligned to the
104 right. If not, it will be aligned to the left.
106 The default value of this option is a regular expression which allows
107 anything which looks remotely like a number as used in scientific
108 context. For example, all of the following will be considered a
110 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
112 Other options offered by the customize interface are more restrictive."
113 :group
'org-table-settings
115 (const :tag
"Positive Integers"
117 (const :tag
"Integers"
119 (const :tag
"Floating Point Numbers"
120 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
121 (const :tag
"Floating Point Number or Integer"
122 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
123 (const :tag
"Exponential, Floating point, Integer"
124 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
125 (const :tag
"Very General Number-Like, including hex"
126 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
127 (string :tag
"Regexp:")))
129 (defcustom org-table-number-fraction
0.5
130 "Fraction of numbers in a column required to make the column align right.
131 In a column all non-white fields are considered. If at least this
132 fraction of fields is matched by `org-table-number-fraction',
133 alignment to the right border applies."
134 :group
'org-table-settings
137 (defgroup org-table-editing nil
138 "Behavior of tables during editing in Org-mode."
139 :tag
"Org Table Editing"
142 (defcustom org-table-automatic-realign t
143 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
144 When nil, aligning is only done with \\[org-table-align], or after column
146 :group
'org-table-editing
149 (defcustom org-table-auto-blank-field t
150 "Non-nil means, automatically blank table field when starting to type into it.
151 This only happens when typing immediately after a field motion
152 command (TAB, S-TAB or RET).
153 Only relevant when `org-enable-table-editor' is equal to `optimized'."
154 :group
'org-table-editing
157 (defcustom org-table-tab-jumps-over-hlines t
158 "Non-nil means, tab in the last column of a table with jump over a hline.
159 If a horizontal separator line is following the current line,
160 `org-table-next-field' can either create a new row before that line, or jump
161 over the line. When this option is nil, a new line will be created before
163 :group
'org-table-editing
166 (defgroup org-table-calculation nil
167 "Options concerning tables in Org-mode."
168 :tag
"Org Table Calculation"
171 (defcustom org-table-use-standard-references t
172 "Should org-mode work with table refrences like B3 instead of @3$2?
175 from accept as input, do not present for editing
176 t: accept as input and present for editing"
177 :group
'org-table-calculation
179 (const :tag
"Never, don't even check user input for them" nil
)
180 (const :tag
"Always, both as user input, and when editing" t
)
181 (const :tag
"Convert user input, don't offer during editing" 'from
)))
183 (defcustom org-table-copy-increment t
184 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
185 :group
'org-table-calculation
188 (defcustom org-calc-default-modes
189 '(calc-internal-prec 12
190 calc-float-format
(float 5)
193 calc-symbolic-mode nil
194 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " HH
":" mm
))
195 calc-display-working-message t
197 "List with Calc mode settings for use in calc-eval for table formulas.
198 The list must contain alternating symbols (Calc modes variables and values).
199 Don't remove any of the default settings, just change the values. Org-mode
200 relies on the variables to be present in the list."
201 :group
'org-table-calculation
204 (defcustom org-table-formula-evaluate-inline t
205 "Non-nil means, TAB and RET evaluate a formula in current table field.
206 If the current field starts with an equal sign, it is assumed to be a formula
207 which should be evaluated as described in the manual and in the documentation
208 string of the command `org-table-eval-formula'. This feature requires the
210 When this variable is nil, formula calculation is only available through
211 the command \\[org-table-eval-formula]."
212 :group
'org-table-calculation
215 (defcustom org-table-formula-use-constants t
216 "Non-nil means, interpret constants in formulas in tables.
217 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
218 by the value given in `org-table-formula-constants', or by a value obtained
219 from the `constants.el' package."
220 :group
'org-table-calculation
223 (defcustom org-table-formula-constants nil
224 "Alist with constant names and values, for use in table formulas.
225 The car of each element is a name of a constant, without the `$' before it.
226 The cdr is the value as a string. For example, if you'd like to use the
227 speed of light in a formula, you would configure
229 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
231 and then use it in an equation like `$1*$c'.
233 Constants can also be defined on a per-file basis using a line like
235 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
236 :group
'org-table-calculation
238 (cons (string :tag
"name")
239 (string :tag
"value"))))
241 (defcustom org-table-allow-automatic-line-recalculation t
242 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
243 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
244 :group
'org-table-calculation
259 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
260 "Detects a table line marked for automatic recalculation.")
261 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
262 "Detects a table line marked for automatic recalculation.")
263 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
264 "Detects a table line marked for automatic recalculation.")
265 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
266 "Searching from within a table (any type) this finds the first line
268 (defvar org-table-last-highlighted-reference nil
)
269 (defvar org-table-formula-history nil
)
271 (defvar org-table-column-names nil
272 "Alist with column names, derived from the `!' line.")
273 (defvar org-table-column-name-regexp nil
274 "Regular expression matching the current column names.")
275 (defvar org-table-local-parameters nil
276 "Alist with parameter names, derived from the `$' line.")
277 (defvar org-table-named-field-locations nil
278 "Alist with locations of named fields.")
280 (defvar org-table-current-line-types nil
281 "Table row types, non-nil only for the duration of a comand.")
282 (defvar org-table-current-begin-line nil
283 "Table begin line, non-nil only for the duration of a comand.")
284 (defvar org-table-current-begin-pos nil
285 "Table begin position, non-nil only for the duration of a comand.")
286 (defvar org-table-dlines nil
287 "Vector of data line line numbers in the current table.")
288 (defvar org-table-hlines nil
289 "Vector of hline line numbers in the current table.")
291 (defconst org-table-range-regexp
292 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
294 "Regular expression for matching ranges in formulas.")
296 (defconst org-table-range-regexp2
298 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
300 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
301 "Match a range for reference display.")
303 (defconst org-table-translate-regexp
304 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
305 "Match a reference that needs translation, for reference display.")
307 (defun org-table-create-with-table.el
()
308 "Use the table.el package to insert a new table.
309 If there is already a table at point, convert between Org-mode tables
310 and table.el tables."
315 (if (y-or-n-p "Convert table to Org-mode table? ")
316 (org-table-convert)))
318 (if (y-or-n-p "Convert table to table.el table? ")
319 (org-table-convert)))
320 (t (call-interactively 'table-insert
))))
322 (defun org-table-create-or-convert-from-region (arg)
323 "Convert region to table, or create an empty table.
324 If there is an active region, convert it to a table, using the function
325 `org-table-convert-region'. See the documentation of that function
326 to learn how the prefix argument is interpreted to determine the field
328 If there is no such region, create an empty table with `org-table-create'."
330 (if (org-region-active-p)
331 (org-table-convert-region (region-beginning) (region-end) arg
)
332 (org-table-create arg
)))
334 (defun org-table-create (&optional size
)
335 "Query for a size and insert a table skeleton.
336 SIZE is a string Columns x Rows like for example \"3x2\"."
339 (setq size
(read-string
340 (concat "Table size Columns x Rows [e.g. "
341 org-table-default-size
"]: ")
342 "" nil org-table-default-size
)))
345 (indent (make-string (current-column) ?\
))
346 (split (org-split-string size
" *x *"))
347 (rows (string-to-number (nth 1 split
)))
348 (columns (string-to-number (car split
)))
349 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
351 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
352 (point-at-bol) (point)))
353 (beginning-of-line 1)
355 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
356 (dotimes (i rows
) (insert line
))
359 ;; Insert a hline after the first row.
366 (defun org-table-convert-region (beg0 end0
&optional separator
)
367 "Convert region to a table.
368 The region goes from BEG0 to END0, but these borders will be moved
369 slightly, to make sure a beginning of line in the first line is included.
371 SEPARATOR specifies the field separator in the lines. It can have the
374 '(4) Use the comma as a field separator
375 '(16) Use a TAB as field separator
376 integer When a number, use that many spaces as field separator
377 nil When nil, the command tries to be smart and figure out the
378 separator in the following way:
379 - when each line contains a TAB, assume TAB-separated material
380 - when each line contains a comme, assume CSV material
381 - else, assume one or more SPACE charcters as separator."
383 (let* ((beg (min beg0 end0
))
384 (end (max beg0 end0
))
387 (beginning-of-line 1)
388 (setq beg
(move-marker (make-marker) (point)))
390 (if (bolp) (backward-char 1) (end-of-line 1))
391 (setq end
(move-marker (make-marker) (point)))
392 ;; Get the right field separator
397 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
398 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
401 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
402 ((equal separator
'(16)) "^\\|\t")
403 ((integerp separator
)
404 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
))
405 (t (error "This should not happen"))))
407 (while (re-search-forward re end t
)
408 (replace-match "| " t t
))
413 (defun org-table-import (file arg
)
414 "Import FILE as a table.
415 The file is assumed to be tab-separated. Such files can be produced by most
416 spreadsheet and database applications. If no tabs (at least one per line)
417 are found, lines will be split on whitespace into fields."
419 (or (bolp) (newline))
422 (insert-file-contents file
)
423 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
425 (defun org-table-export ()
426 "Export table as a tab-separated file.
427 Such a file can be imported into a spreadsheet program like Excel."
429 (let* ((beg (org-table-begin))
430 (end (org-table-end))
431 (table (buffer-substring beg end
))
432 (file (read-file-name "Export table to: "))
434 (unless (or (not (file-exists-p file
))
435 (y-or-n-p (format "Overwrite file %s? " file
)))
437 (with-current-buffer (find-file-noselect file
)
438 (setq buf
(current-buffer))
442 (goto-char (point-min))
443 (while (re-search-forward "^[ \t]*|[ \t]*" nil t
)
444 (replace-match "" t t
)
446 (goto-char (point-min))
447 (while (re-search-forward "[ \t]*|[ \t]*$" nil t
)
448 (replace-match "" t t
)
449 (goto-char (min (1+ (point)) (point-max))))
450 (goto-char (point-min))
451 (while (re-search-forward "^-[-+]*$" nil t
)
453 (if (looking-at "\n")
455 (goto-char (point-min))
456 (while (re-search-forward "[ \t]*|[ \t]*" nil t
)
457 (replace-match "\t" t t
))
461 (defvar org-table-aligned-begin-marker
(make-marker)
462 "Marker at the beginning of the table last aligned.
463 Used to check if cursor still is in that table, to minimize realignment.")
464 (defvar org-table-aligned-end-marker
(make-marker)
465 "Marker at the end of the table last aligned.
466 Used to check if cursor still is in that table, to minimize realignment.")
467 (defvar org-table-last-alignment nil
468 "List of flags for flushright alignment, from the last re-alignment.
469 This is being used to correctly align a single field after TAB or RET.")
470 (defvar org-table-last-column-widths nil
471 "List of max width of fields in each column.
472 This is being used to correctly align a single field after TAB or RET.")
473 (defvar org-table-overlay-coordinates nil
474 "Overlay coordinates after each align of a table.")
475 (make-variable-buffer-local 'org-table-overlay-coordinates
)
477 (defvar org-last-recalc-line nil
)
478 (defconst org-narrow-column-arrow
"=>"
479 "Used as display property in narrowed table columns.")
481 (defun org-table-align ()
482 "Align the table at point by aligning all vertical bars."
486 (beg (org-table-begin))
487 (end (org-table-end))
488 ;; Current cursor position
489 (linepos (org-current-line))
490 (colpos (org-table-current-column))
491 (winstart (window-start))
492 (winstartline (org-current-line (min winstart
(1- (point-max)))))
493 lines
(new "") lengths l typenums ty fields maxfields i
501 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
503 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
504 emptystrings links dates emph narrow fmax f1 len c e
)
506 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
507 ;; Check if we have links or dates
509 (setq links
(re-search-forward org-bracket-link-regexp end t
))
511 (setq emph
(and org-hide-emphasis-markers
512 (re-search-forward org-emph-re end t
)))
514 (setq dates
(and org-display-custom-times
515 (re-search-forward org-ts-regexp-both end t
)))
516 ;; Make sure the link properties are right
517 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
518 ;; Make sure the date properties are right
519 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
520 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
522 ;; Check if we are narrowing any columns
524 (setq narrow
(and org-format-transports-properties-p
525 (re-search-forward "<[0-9]+>" end t
)))
527 (setq lines
(org-split-string
528 (buffer-substring beg end
) "\n"))
529 ;; Store the indentation of the first line
530 (if (string-match "^ *" (car lines
))
531 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
532 ;; Mark the hlines by setting the corresponding element to nil
533 ;; At the same time, we remove trailing space.
534 (setq lines
(mapcar (lambda (l)
535 (if (string-match "^ *|-" l
)
537 (if (string-match "[ \t]+$" l
)
538 (substring l
0 (match-beginning 0))
541 ;; Get the data fields by splitting the lines.
544 (org-split-string l
" *| *"))
545 (delq nil
(copy-sequence lines
))))
546 ;; How many fields in the longest line?
548 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
550 (kill-region beg end
)
551 (org-table-create org-table-default-size
)
552 (error "Empty table - created default table")))
553 ;; A list of empty strings to fill any short rows on output
554 (setq emptystrings
(make-list maxfields
""))
555 ;; Check for special formatting.
557 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
558 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
559 ;; Check if there is an explicit width specified
561 (setq c column fmax nil
)
564 (if (and (stringp e
) (string-match "^<\\([0-9]+\\)>$" e
))
565 (setq fmax
(string-to-number (match-string 1 e
)) c nil
)))
566 ;; Find fields that are wider than fmax, and shorten them
568 (loop for xx in column do
569 (when (and (stringp xx
)
570 (> (org-string-width xx
) fmax
))
571 (org-add-props xx nil
573 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
574 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
576 (error "Cannot narrow field starting with wide link \"%s\""
577 (match-string 0 xx
)))
578 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
579 (add-text-properties (- f1
2) f1
580 (list 'display org-narrow-column-arrow
)
582 ;; Get the maximum width for each column
583 (push (apply 'max
1 (mapcar 'org-string-width column
)) lengths
)
584 ;; Get the fraction of numbers, to decide about alignment of the column
585 (setq cnt
0 frac
0.0)
586 (loop for x in column do
589 (setq frac
( / (+ (* frac cnt
)
590 (if (string-match org-table-number-regexp x
) 1 0))
591 (setq cnt
(1+ cnt
))))))
592 (push (>= frac org-table-number-fraction
) typenums
))
593 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
595 ;; Store the alignment of this table, for later editing of single fields
596 (setq org-table-last-alignment typenums
597 org-table-last-column-widths lengths
)
599 ;; With invisible characters, `format' does not get the field width right
600 ;; So we need to make these fields wide by hand.
601 (when (or links emph
)
602 (loop for i from
0 upto
(1- maxfields
) do
603 (setq len
(nth i lengths
))
604 (loop for j from
0 upto
(1- (length fields
)) do
605 (setq c
(nthcdr i
(car (nthcdr j fields
))))
606 (if (and (stringp (car c
))
607 (text-property-any 0 (length (car c
)) 'invisible
'org-link
(car c
))
608 ; (string-match org-bracket-link-regexp (car c))
609 (< (org-string-width (car c
)) len
))
610 (setcar c
(concat (car c
) (make-string (- len
(org-string-width (car c
))) ?\
)))))))
612 ;; Compute the formats needed for output of the table
613 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
614 (while (setq l
(pop lengths
))
615 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
616 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
617 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
618 (setq rfmt
(concat rfmt
"\n")
619 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
623 (if l
(apply 'format rfmt
624 (append (pop fields
) emptystrings
))
627 ;; Replace the old one
628 (delete-region beg end
)
629 (move-marker end nil
)
630 (move-marker org-table-aligned-begin-marker
(point))
632 (move-marker org-table-aligned-end-marker
(point))
633 (when (and orgtbl-mode
(not (org-mode-p)))
634 (goto-char org-table-aligned-begin-marker
)
635 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
636 ;; Try to move to the old location
637 (goto-line winstartline
)
638 (setq winstart
(point-at-bol))
640 (set-window-start (selected-window) winstart
'noforce
)
641 (org-table-goto-column colpos
)
642 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
643 (setq org-table-may-need-update nil
)
654 (defun org-table-begin (&optional table-type
)
655 "Find the beginning of the table and return its position.
656 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
658 (if (not (re-search-backward
659 (if table-type org-table-any-border-regexp
660 org-table-border-regexp
)
662 (progn (goto-char (point-min)) (point))
663 (goto-char (match-beginning 0))
664 (beginning-of-line 2)
667 (defun org-table-end (&optional table-type
)
668 "Find the end of the table and return its position.
669 With argument TABLE-TYPE, go to the end of a table.el-type table."
671 (if (not (re-search-forward
672 (if table-type org-table-any-border-regexp
673 org-table-border-regexp
)
675 (goto-char (point-max))
676 (goto-char (match-beginning 0)))
679 (defun org-table-justify-field-maybe (&optional new
)
680 "Justify the current field, text to left, number to right.
681 Optional argument NEW may specify text to replace the current field content."
683 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
684 ((org-at-table-hline-p))
686 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
688 (< (point) org-table-aligned-begin-marker
)
689 (>= (point) org-table-aligned-end-marker
)))
690 ;; This is not the same table, force a full re-align
691 (setq org-table-may-need-update t
))
692 (t ;; realign the current field, based on previous full realign
693 (let* ((pos (point)) s
694 (col (org-table-current-column))
695 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
698 (skip-chars-backward "^|\n")
699 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
701 (setq s
(match-string 1)
703 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
704 e
(not (= (match-beginning 2) (match-end 2))))
705 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
706 l
(if e
"|" (setq org-table-may-need-update t
) ""))
709 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
710 (setq n
(format f new
))
711 (setq n
(concat new
"|") org-table-may-need-update t
)))
713 (let (org-table-may-need-update)
714 (replace-match n t t
))))
715 (setq org-table-may-need-update t
))
718 (defun org-table-next-field ()
719 "Go to the next field in the current table, creating new lines as needed.
720 Before doing so, re-align the table if necessary."
722 (org-table-maybe-eval-formula)
723 (org-table-maybe-recalculate-line)
724 (if (and org-table-automatic-realign
725 org-table-may-need-update
)
727 (let ((end (org-table-end)))
728 (if (org-at-table-hline-p)
732 (re-search-forward "|" end
)
733 (if (looking-at "[ \t]*$")
734 (re-search-forward "|" end
))
735 (if (and (looking-at "-")
736 org-table-tab-jumps-over-hlines
737 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
738 (goto-char (match-beginning 1)))
741 (beginning-of-line 0)
742 (org-table-insert-row 'below
))
743 (if (looking-at " ") (forward-char 1))))
745 (org-table-insert-row 'below
)))))
747 (defun org-table-previous-field ()
748 "Go to the previous field in the table.
749 Before doing so, re-align the table if necessary."
751 (org-table-justify-field-maybe)
752 (org-table-maybe-recalculate-line)
753 (if (and org-table-automatic-realign
754 org-table-may-need-update
)
756 (if (org-at-table-hline-p)
758 (re-search-backward "|" (org-table-begin))
759 (re-search-backward "|" (org-table-begin))
760 (while (looking-at "|\\(-\\|[ \t]*$\\)")
761 (re-search-backward "|" (org-table-begin)))
762 (if (looking-at "| ?")
763 (goto-char (match-end 0))))
765 (defun org-table-next-row ()
766 "Go to the next row (same column) in the current table.
767 Before doing so, re-align the table if necessary."
769 (org-table-maybe-eval-formula)
770 (org-table-maybe-recalculate-line)
771 (if (or (looking-at "[ \t]*$")
772 (save-excursion (skip-chars-backward " \t") (bolp)))
774 (if (and org-table-automatic-realign
775 org-table-may-need-update
)
777 (let ((col (org-table-current-column)))
778 (beginning-of-line 2)
779 (if (or (not (org-at-table-p))
780 (org-at-table-hline-p))
782 (beginning-of-line 0)
783 (org-table-insert-row 'below
)))
784 (org-table-goto-column col
)
785 (skip-chars-backward "^|\n\r")
786 (if (looking-at " ") (forward-char 1)))))
788 (defun org-table-copy-down (n)
789 "Copy a field down in the current column.
790 If the field at the cursor is empty, copy into it the content of the nearest
791 non-empty field above. With argument N, use the Nth non-empty field.
792 If the current field is not empty, it is copied down to the next row, and
793 the cursor is moved with it. Therefore, repeating this command causes the
794 column to be filled row-by-row.
795 If the variable `org-table-copy-increment' is non-nil and the field is an
796 integer or a timestamp, it will be incremented while copying. In the case of
797 a timestamp, if the cursor is on the year, change the year. If it is on the
798 month or the day, change that. Point will stay on the current date field
799 in order to easily repeat the interval."
801 (let* ((colpos (org-table-current-column))
802 (col (current-column))
803 (field (org-table-get-field))
804 (non-empty (string-match "[^ \t]" field
))
805 (beg (org-table-begin))
807 (org-table-check-inside-data-field)
810 (setq txt
(org-trim field
))
812 (org-table-blank-field))
816 (while (progn (beginning-of-line 1)
817 (re-search-backward org-table-dataline-regexp
819 (org-table-goto-column colpos t
)
821 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
822 (= (setq n
(1- n
)) 0))
823 (throw 'exit
(match-string 1))))))))
826 (if (and org-table-copy-increment
827 (string-match "^[0-9]+$" txt
))
828 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
831 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
833 (org-table-maybe-recalculate-line))
835 (move-to-column col
))
836 (error "No non-empty field found"))))
838 (defun org-table-check-inside-data-field ()
839 "Is point inside a table data field?
840 I.e. not on a hline or before the first or after the last column?
841 This actually throws an error, so it aborts the current command."
842 (if (or (not (org-at-table-p))
843 (= (org-table-current-column) 0)
844 (org-at-table-hline-p)
845 (looking-at "[ \t]*$"))
846 (error "Not in table data field")))
848 (defvar org-table-clip nil
849 "Clipboard for table regions.")
851 (defun org-table-blank-field ()
852 "Blank the current table field or active region."
854 (org-table-check-inside-data-field)
855 (if (and (interactive-p) (org-region-active-p))
856 (let (org-table-clip)
857 (org-table-cut-region (region-beginning) (region-end)))
858 (skip-chars-backward "^|")
860 (if (looking-at "|[^|\n]+")
861 (let* ((pos (match-beginning 0))
862 (match (match-string 0))
863 (len (org-string-width match
)))
864 (replace-match (concat "|" (make-string (1- len
) ?\
)))
865 (goto-char (+ 2 pos
))
866 (substring match
1)))))
868 (defun org-table-get-field (&optional n replace
)
869 "Return the value of the field in column N of current row.
870 N defaults to current field.
871 If REPLACE is a string, replace field with this value. The return value
872 is always the old value."
873 (and n
(org-table-goto-column n
))
874 (skip-chars-backward "^|\n")
876 (if (looking-at "|[^|\r\n]*")
877 (let* ((pos (match-beginning 0))
878 (val (buffer-substring (1+ pos
) (match-end 0))))
880 (replace-match (concat "|" replace
) t t
))
881 (goto-char (min (point-at-eol) (+ 2 pos
)))
883 (forward-char 1) ""))
885 (defun org-table-field-info (arg)
886 "Show info about the current field, and highlight any reference at point."
888 (org-table-get-specials)
891 (col (org-table-current-column))
892 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
893 (name (car (rassoc (list (org-current-line) col
)
894 org-table-named-field-locations
)))
895 (eql (org-table-get-stored-formulas))
896 (dline (org-table-current-dline))
897 (ref (format "@%d$%d" dline col
))
898 (ref1 (org-table-convert-refs-to-an ref
))
899 (fequation (or (assoc name eql
) (assoc ref eql
)))
900 (cequation (assoc (int-to-string col
) eql
))
901 (eqn (or fequation cequation
)))
904 (org-table-show-reference 'local
)
906 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
908 (if cname
(concat " or $" cname
) "")
910 (if name
(concat " or $" name
) "")
911 ;; FIXME: formula info not correct if special table line
913 (concat ", formula: "
914 (org-table-formula-to-user
916 (if (string-match "^[$@]"(car eqn
)) "" "$")
917 (car eqn
) "=" (cdr eqn
))))
920 (defun org-table-current-column ()
921 "Find out which column we are in."
923 (let ((cnt 0) (pos (point)))
924 (beginning-of-line 1)
925 (while (search-forward "|" pos t
)
929 (defun org-table-current-dline ()
930 "Find out what table data line we are in.
931 Only datalins count for this."
933 (if (interactive-p) (org-table-check-inside-data-field))
935 (let ((cnt 0) (pos (point)))
936 (goto-char (org-table-begin))
937 (while (<= (point) pos
)
938 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
939 (beginning-of-line 2))
940 (if (interactive-p) (message "This is table line %d" cnt
))
943 (defun org-table-goto-column (n &optional on-delim force
)
944 "Move the cursor to the Nth column in the current table line.
945 With optional argument ON-DELIM, stop with point before the left delimiter
947 If there are less than N fields, just go to after the last delimiter.
948 However, when FORCE is non-nil, create new columns if necessary."
950 (let ((pos (point-at-eol)))
951 (beginning-of-line 1)
953 (while (and (> (setq n
(1- n
)) -
1)
954 (or (search-forward "|" pos t
)
956 (progn (end-of-line 1)
957 (skip-chars-backward "^|")
959 ; (backward-char 2) t)))))
960 (when (and force
(not (looking-at ".*|")))
961 (save-excursion (end-of-line 1) (insert " | ")))
964 (if (looking-at " ") (forward-char 1))))))
967 (defun org-table-insert-column ()
968 "Insert a new column into the table."
970 (if (not (org-at-table-p))
971 (error "Not at a table"))
972 (org-table-find-dataline)
973 (let* ((col (max 1 (org-table-current-column)))
974 (beg (org-table-begin))
975 (end (org-table-end))
976 ;; Current cursor position
977 (linepos (org-current-line))
980 (while (< (point) end
)
981 (if (org-at-table-hline-p)
983 (org-table-goto-column col t
)
985 (beginning-of-line 2))
986 (move-marker end nil
)
988 (org-table-goto-column colpos
)
990 (org-table-fix-formulas "$" nil
(1- col
) 1)))
992 (defun org-table-find-dataline ()
993 "Find a dataline in the current table, which is needed for column commands."
994 (if (and (org-at-table-p)
995 (not (org-at-table-hline-p)))
997 (let ((col (current-column))
998 (end (org-table-end)))
1000 (while (and (< (point) end
)
1001 (or (not (= (current-column) col
))
1002 (org-at-table-hline-p)))
1003 (beginning-of-line 2)
1004 (move-to-column col
))
1005 (if (and (org-at-table-p)
1006 (not (org-at-table-hline-p)))
1009 "Please position cursor in a data line for column operations")))))
1011 (defun org-table-delete-column ()
1012 "Delete a column from the table."
1014 (if (not (org-at-table-p))
1015 (error "Not at a table"))
1016 (org-table-find-dataline)
1017 (org-table-check-inside-data-field)
1018 (let* ((col (org-table-current-column))
1019 (beg (org-table-begin))
1020 (end (org-table-end))
1021 ;; Current cursor position
1022 (linepos (org-current-line))
1025 (while (< (point) end
)
1026 (if (org-at-table-hline-p)
1028 (org-table-goto-column col t
)
1029 (and (looking-at "|[^|\n]+|")
1030 (replace-match "|")))
1031 (beginning-of-line 2))
1032 (move-marker end nil
)
1034 (org-table-goto-column colpos
)
1036 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1039 (defun org-table-move-column-right ()
1040 "Move column to the right."
1042 (org-table-move-column nil
))
1043 (defun org-table-move-column-left ()
1044 "Move column to the left."
1046 (org-table-move-column 'left
))
1048 (defun org-table-move-column (&optional left
)
1049 "Move the current column to the right. With arg LEFT, move to the left."
1051 (if (not (org-at-table-p))
1052 (error "Not at a table"))
1053 (org-table-find-dataline)
1054 (org-table-check-inside-data-field)
1055 (let* ((col (org-table-current-column))
1056 (col1 (if left
(1- col
) col
))
1057 (beg (org-table-begin))
1058 (end (org-table-end))
1059 ;; Current cursor position
1060 (linepos (org-current-line))
1061 (colpos (if left
(1- col
) (1+ col
))))
1062 (if (and left
(= col
1))
1063 (error "Cannot move column further left"))
1064 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1065 (error "Cannot move column further right"))
1067 (while (< (point) end
)
1068 (if (org-at-table-hline-p)
1070 (org-table-goto-column col1 t
)
1071 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1072 (replace-match "|\\2|\\1|")))
1073 (beginning-of-line 2))
1074 (move-marker end nil
)
1076 (org-table-goto-column colpos
)
1078 (org-table-fix-formulas
1079 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1080 (cons (number-to-string colpos
) (number-to-string col
))))))
1082 (defun org-table-move-row-down ()
1083 "Move table row down."
1085 (org-table-move-row nil
))
1086 (defun org-table-move-row-up ()
1087 "Move table row up."
1089 (org-table-move-row 'up
))
1091 (defun org-table-move-row (&optional up
)
1092 "Move the current table line down. With arg UP, move it up."
1094 (let* ((col (current-column))
1096 (hline1p (save-excursion (beginning-of-line 1)
1097 (looking-at org-table-hline-regexp
)))
1098 (dline1 (org-table-current-dline))
1099 (dline2 (+ dline1
(if up -
1 1)))
1102 (beginning-of-line tonew
)
1103 (unless (org-at-table-p)
1105 (error "Cannot move row further"))
1106 (setq hline2p
(looking-at org-table-hline-regexp
))
1108 (beginning-of-line 1)
1110 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1111 (delete-region (point) (1+ (point-at-eol)))
1112 (beginning-of-line tonew
)
1114 (beginning-of-line 0)
1115 (move-to-column col
)
1116 (unless (or hline1p hline2p
)
1117 (org-table-fix-formulas
1118 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1119 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1121 (defun org-table-insert-row (&optional arg
)
1122 "Insert a new row above the current line into the table.
1123 With prefix ARG, insert below the current line."
1125 (if (not (org-at-table-p))
1126 (error "Not at a table"))
1127 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1128 (new (org-table-clean-line line
)))
1129 ;; Fix the first field if necessary
1130 (if (string-match "^[ \t]*| *[#$] *|" line
)
1131 (setq new
(replace-match (match-string 0 line
) t t new
)))
1132 (beginning-of-line (if arg
2 1))
1133 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1134 (beginning-of-line 0)
1135 (re-search-forward "| ?" (point-at-eol) t
)
1136 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1138 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1)))
1140 (defun org-table-insert-hline (&optional above
)
1141 "Insert a horizontal-line below the current line into the table.
1142 With prefix ABOVE, insert above the current line."
1144 (if (not (org-at-table-p))
1145 (error "Not at a table"))
1146 (let ((line (org-table-clean-line
1147 (buffer-substring (point-at-bol) (point-at-eol))))
1148 (col (current-column)))
1149 (while (string-match "|\\( +\\)|" line
)
1150 (setq line
(replace-match
1151 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1152 ?-
) "|") t t line
)))
1153 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1154 (beginning-of-line (if above
1 2))
1156 (beginning-of-line (if above
1 -
1))
1157 (move-to-column col
)
1158 (and org-table-overlay-coordinates
(org-table-align))))
1160 (defun org-table-hline-and-move (&optional same-column
)
1161 "Insert a hline and move to the row below that line."
1163 (let ((col (org-table-current-column)))
1164 (org-table-maybe-eval-formula)
1165 (org-table-maybe-recalculate-line)
1166 (org-table-insert-hline)
1168 (if (looking-at "\n[ \t]*|-")
1169 (progn (insert "\n|") (org-table-align))
1170 (org-table-next-field))
1171 (if same-column
(org-table-goto-column col
))))
1173 (defun org-table-clean-line (s)
1174 "Convert a table line S into a string with only \"|\" and space.
1175 In particular, this does handle wide and invisible characters."
1176 (if (string-match "^[ \t]*|-" s
)
1177 ;; It's a hline, just map the characters
1178 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1179 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1180 (setq s
(replace-match
1181 (concat "|" (make-string (org-string-width (match-string 1 s
))
1186 (defun org-table-kill-row ()
1187 "Delete the current row or horizontal line from the table."
1189 (if (not (org-at-table-p))
1190 (error "Not at a table"))
1191 (let ((col (current-column))
1192 (dline (org-table-current-dline)))
1193 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1194 (if (not (org-at-table-p)) (beginning-of-line 0))
1195 (move-to-column col
)
1196 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1199 (defun org-table-sort-lines (with-case &optional sorting-type
)
1200 "Sort table lines according to the column at point.
1202 The position of point indicates the column to be used for
1203 sorting, and the range of lines is the range between the nearest
1204 horizontal separator lines, or the entire table of no such lines
1205 exist. If point is before the first column, you will be prompted
1206 for the sorting column. If there is an active region, the mark
1207 specifies the first line and the sorting column, while point
1208 should be in the last line to be included into the sorting.
1210 The command then prompts for the sorting type which can be
1211 alphabetically, numerically, or by time (as given in a time stamp
1212 in the field). Sorting in reverse order is also possible.
1214 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1216 If SORTING-TYPE is specified when this function is called from a Lisp
1217 program, no prompting will take place. SORTING-TYPE must be a character,
1218 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1219 should be done in reverse order."
1221 (let* ((thisline (org-current-line))
1222 (thiscol (org-table-current-column))
1223 beg end bcol ecol tend tbeg column lns pos
)
1224 (when (equal thiscol
0)
1228 (read-string "Use column N for sorting: ")))
1230 (org-table-goto-column thiscol
))
1231 (org-table-check-inside-data-field)
1232 (if (org-region-active-p)
1234 (setq beg
(region-beginning) end
(region-end))
1236 (setq column
(org-table-current-column)
1239 (setq end
(point-at-bol 2)))
1240 (setq column
(org-table-current-column)
1242 tbeg
(org-table-begin)
1243 tend
(org-table-end))
1244 (if (re-search-backward org-table-hline-regexp tbeg t
)
1245 (setq beg
(point-at-bol 2))
1247 (setq beg
(point-at-bol 1)))
1249 (if (re-search-forward org-table-hline-regexp tend t
)
1250 (setq end
(point-at-bol 1))
1252 (setq end
(point-at-bol))))
1253 (setq beg
(move-marker (make-marker) beg
)
1254 end
(move-marker (make-marker) end
))
1257 (org-table-goto-column column
)
1258 (skip-chars-backward "^|")
1259 (setq bcol
(current-column))
1260 (org-table-goto-column (1+ column
))
1261 (skip-chars-backward "^|")
1262 (setq ecol
(1- (current-column)))
1263 (org-table-goto-column column
)
1264 (setq lns
(mapcar (lambda(x) (cons
1265 (org-sort-remove-invisible
1267 (org-split-string x
"[ \t]*|[ \t]*")))
1269 (org-split-string (buffer-substring beg end
) "\n")))
1270 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1271 (delete-region beg end
)
1272 (move-marker beg nil
)
1273 (move-marker end nil
)
1274 (insert (mapconcat 'cdr lns
"\n") "\n")
1275 (goto-line thisline
)
1276 (org-table-goto-column thiscol
)
1277 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1280 (defun org-table-cut-region (beg end
)
1281 "Copy region in table to the clipboard and blank all relevant fields."
1283 (org-table-copy-region beg end
'cut
))
1285 (defun org-table-copy-region (beg end
&optional cut
)
1286 "Copy rectangular region in table to clipboard.
1287 A special clipboard is used which can only be accessed
1288 with `org-table-paste-rectangle'."
1290 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1292 (rpl (if cut
" " nil
)))
1294 (org-table-check-inside-data-field)
1295 (setq l01
(org-current-line)
1296 c01
(org-table-current-column))
1298 (org-table-check-inside-data-field)
1299 (setq l02
(org-current-line)
1300 c02
(org-table-current-column))
1301 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1302 c1
(min c01 c02
) c2
(max c01 c02
))
1306 (if (> l1 l2
) (throw 'exit t
))
1308 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1309 (setq cols nil ic1 c1 ic2 c2
)
1310 (while (< ic1
(1+ ic2
))
1311 (push (org-table-get-field ic1 rpl
) cols
)
1312 (setq ic1
(1+ ic1
)))
1313 (push (nreverse cols
) region
)
1314 (setq l1
(1+ l1
)))))
1315 (setq org-table-clip
(nreverse region
))
1316 (if cut
(org-table-align))
1319 (defun org-table-paste-rectangle ()
1320 "Paste a rectangular region into a table.
1321 The upper right corner ends up in the current field. All involved fields
1322 will be overwritten. If the rectangle does not fit into the present table,
1323 the table is enlarged as needed. The process ignores horizontal separator
1326 (unless (and org-table-clip
(listp org-table-clip
))
1327 (error "First cut/copy a region to paste!"))
1328 (org-table-check-inside-data-field)
1329 (let* ((clip org-table-clip
)
1330 (line (org-current-line))
1331 (col (org-table-current-column))
1332 (org-enable-table-editor t
)
1333 (org-table-automatic-realign nil
)
1335 (while (setq cols
(pop clip
))
1336 (while (org-at-table-hline-p) (beginning-of-line 2))
1337 (if (not (org-at-table-p))
1338 (progn (end-of-line 0) (org-table-next-field)))
1340 (while (setq field
(pop cols
))
1341 (org-table-goto-column c nil
'force
)
1342 (org-table-get-field nil field
)
1344 (beginning-of-line 2))
1346 (org-table-goto-column col
)
1349 (defun org-table-convert ()
1350 "Convert from `org-mode' table to table.el and back.
1351 Obviously, this only works within limits. When an Org-mode table is
1352 converted to table.el, all horizontal separator lines get lost, because
1353 table.el uses these as cell boundaries and has no notion of horizontal lines.
1354 A table.el table can be converted to an Org-mode table only if it does not
1355 do row or column spanning. Multiline cells will become multiple cells.
1356 Beware, Org-mode does not test if the table can be successfully converted - it
1357 blindly applies a recipe that works for simple tables."
1360 (if (org-at-table.el-p
)
1361 ;; convert to Org-mode table
1362 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1363 (end (move-marker (make-marker) (org-table-end t
))))
1364 (table-unrecognize-region beg end
)
1366 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1369 (if (org-at-table-p)
1370 ;; convert to table.el table
1371 (let ((beg (move-marker (make-marker) (org-table-begin)))
1372 (end (move-marker (make-marker) (org-table-end))))
1373 ;; first, get rid of all horizontal lines
1375 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1377 ;; insert a hline before first
1379 (org-table-insert-hline 'above
)
1380 (beginning-of-line -
1)
1381 ;; insert a hline after each line
1382 (while (progn (beginning-of-line 3) (< (point) end
))
1383 (org-table-insert-hline))
1385 (setq end
(move-marker end
(org-table-end)))
1386 ;; replace "+" at beginning and ending of hlines
1387 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1388 (replace-match "\\1+-"))
1390 (while (re-search-forward "-|[ \t]*$" end t
)
1391 (replace-match "-+"))
1394 (defun org-table-wrap-region (arg)
1395 "Wrap several fields in a column like a paragraph.
1396 This is useful if you'd like to spread the contents of a field over several
1397 lines, in order to keep the table compact.
1399 If there is an active region, and both point and mark are in the same column,
1400 the text in the column is wrapped to minimum width for the given number of
1401 lines. Generally, this makes the table more compact. A prefix ARG may be
1402 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1403 formats the selected text to two lines. If the region was longer than two
1404 lines, the remaining lines remain empty. A negative prefix argument reduces
1405 the current number of lines by that amount. The wrapped text is pasted back
1406 into the table. If you formatted it to more lines than it was before, fields
1407 further down in the table get overwritten - so you might need to make space in
1410 If there is no region, the current field is split at the cursor position and
1411 the text fragment to the right of the cursor is prepended to the field one
1414 If there is no region, but you specify a prefix ARG, the current field gets
1415 blank, and the content is appended to the field above."
1417 (org-table-check-inside-data-field)
1418 (if (org-region-active-p)
1419 ;; There is a region: fill as a paragraph
1420 (let* ((beg (region-beginning))
1421 (cline (save-excursion (goto-char beg
) (org-current-line)))
1422 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1424 (org-table-cut-region (region-beginning) (region-end))
1425 (if (> (length (car org-table-clip
)) 1)
1426 (error "Region must be limited to single column"))
1427 (setq nlines
(if arg
1429 (+ (length org-table-clip
) arg
)
1431 (length org-table-clip
)))
1432 (setq org-table-clip
1433 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1436 (org-table-goto-column ccol
)
1437 (org-table-paste-rectangle))
1438 ;; No region, split the current field at point
1439 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1440 (skip-chars-forward "^\r\n|"))
1442 ;; combine with field above
1443 (let ((s (org-table-blank-field))
1444 (col (org-table-current-column)))
1445 (beginning-of-line 0)
1446 (while (org-at-table-hline-p) (beginning-of-line 0))
1447 (org-table-goto-column col
)
1448 (skip-chars-forward "^|")
1449 (skip-chars-backward " ")
1450 (insert " " (org-trim s
))
1453 (if (looking-at "\\([^|]+\\)+|")
1454 (let ((s (match-string 1)))
1455 (replace-match " |")
1456 (goto-char (match-beginning 0))
1457 (org-table-next-row)
1458 (insert (org-trim s
) " ")
1460 (org-table-next-row)))))
1462 (defvar org-field-marker nil
)
1464 (defun org-table-edit-field (arg)
1465 "Edit table field in a different window.
1466 This is mainly useful for fields that contain hidden parts.
1467 When called with a \\[universal-argument] prefix, just make the full field visible so that
1468 it can be edited in place."
1471 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1472 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1473 (remove-text-properties b e
'(org-cwidth t invisible t
1474 display t intangible t
))
1475 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1476 (font-lock-fontify-block)))
1477 (let ((pos (move-marker (make-marker) (point)))
1478 (field (org-table-get-field))
1479 (cw (current-window-configuration))
1481 (org-switch-to-buffer-other-window "*Org tmp*")
1483 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
1484 (let ((org-inhibit-startup t
)) (org-mode))
1485 (goto-char (setq p
(point-max)))
1486 (insert (org-trim field
))
1487 (remove-text-properties p
(point-max)
1488 '(invisible t org-cwidth t display t
1491 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1492 (org-set-local 'org-window-configuration cw
)
1493 (org-set-local 'org-field-marker pos
)
1494 (message "Edit and finish with C-c C-c"))))
1496 (defun org-table-finish-edit-field ()
1497 "Finish editing a table data field.
1498 Remove all newline characters, insert the result into the table, realign
1499 the table and kill the editing buffer."
1500 (let ((pos org-field-marker
)
1501 (cw org-window-configuration
)
1502 (cb (current-buffer))
1504 (goto-char (point-min))
1505 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1506 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1507 (replace-match " "))
1508 (setq text
(org-trim (buffer-string)))
1509 (set-window-configuration cw
)
1511 (select-window (get-buffer-window (marker-buffer pos
)))
1513 (move-marker pos nil
)
1514 (org-table-check-inside-data-field)
1515 (org-table-get-field nil text
)
1517 (message "New field value inserted")))
1536 (defvar org-timecnt
) ; dynamically scoped parameter
1538 (defun org-table-sum (&optional beg end nlast
)
1539 "Sum numbers in region of current table column.
1540 The result will be displayed in the echo area, and will be available
1541 as kill to be inserted with \\[yank].
1543 If there is an active region, it is interpreted as a rectangle and all
1544 numbers in that rectangle will be summed. If there is no active
1545 region and point is located in a table column, sum all numbers in that
1548 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1549 numbers are assumed to be times as well (in decimal hours) and the
1550 numbers are added as such.
1552 If NLAST is a number, only the NLAST fields will actually be summed."
1555 (let (col (org-timecnt 0) diff h m s org-table-clip
)
1557 ((and beg end
)) ; beg and end given explicitly
1558 ((org-region-active-p)
1559 (setq beg
(region-beginning) end
(region-end)))
1561 (setq col
(org-table-current-column))
1562 (goto-char (org-table-begin))
1563 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
1564 (error "No table data"))
1565 (org-table-goto-column col
)
1567 (goto-char (org-table-end))
1568 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
1569 (error "No table data"))
1570 (org-table-goto-column col
)
1571 (setq end
(point))))
1572 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
1573 (items1 (cond ((not nlast
) items
)
1574 ((>= nlast
(length items
)) items
)
1575 (t (setq items
(reverse items
))
1576 (setcdr (nthcdr (1- nlast
) items
) nil
)
1578 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
1580 (res (apply '+ numbers
))
1581 (sres (if (= org-timecnt
0)
1583 (setq diff
(* 3600 res
)
1584 h
(floor (/ diff
3600)) diff
(mod diff
3600)
1585 m
(floor (/ diff
60)) diff
(mod diff
60)
1587 (format "%d:%02d:%02d" h m s
))))
1591 (substitute-command-keys
1592 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
1593 (length numbers
) sres
))))
1596 (defun org-table-get-number-for-summing (s)
1598 (if (string-match "^ *|? *" s
)
1599 (setq s
(replace-match "" nil nil s
)))
1600 (if (string-match " *|? *$" s
)
1601 (setq s
(replace-match "" nil nil s
)))
1602 (setq n
(string-to-number s
))
1604 ((and (string-match "0" s
)
1605 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
1606 ((string-match "\\`[ \t]+\\'" s
) nil
)
1607 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
1608 (let ((h (string-to-number (or (match-string 1 s
) "0")))
1609 (m (string-to-number (or (match-string 2 s
) "0")))
1610 (s (string-to-number (or (match-string 4 s
) "0"))))
1611 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
1612 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
1616 (defun org-table-current-field-formula (&optional key noerror
)
1617 "Return the formula active for the current field.
1618 Assumes that specials are in place.
1619 If KEY is given, return the key to this formula.
1620 Otherwise return the formula preceeded with \"=\" or \":=\"."
1621 (let* ((name (car (rassoc (list (org-current-line)
1622 (org-table-current-column))
1623 org-table-named-field-locations
)))
1624 (col (org-table-current-column))
1625 (scol (int-to-string col
))
1626 (ref (format "@%d$%d" (org-table-current-dline) col
))
1627 (stored-list (org-table-get-stored-formulas noerror
))
1628 (ass (or (assoc name stored-list
)
1629 (assoc ref stored-list
)
1630 (assoc scol stored-list
))))
1633 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
1636 (defun org-table-get-formula (&optional equation named
)
1637 "Read a formula from the minibuffer, offer stored formula as default.
1638 When NAMED is non-nil, look for a named equation."
1639 (let* ((stored-list (org-table-get-stored-formulas))
1640 (name (car (rassoc (list (org-current-line)
1641 (org-table-current-column))
1642 org-table-named-field-locations
)))
1643 (ref (format "@%d$%d" (org-table-current-dline)
1644 (org-table-current-column)))
1645 (refass (assoc ref stored-list
))
1648 (int-to-string (org-table-current-column))))
1649 (dummy (and (or name refass
) (not named
)
1650 (not (y-or-n-p "Replace field formula with column formula? " ))
1652 (name (or name ref
))
1653 (org-table-may-need-update nil
)
1654 (stored (cdr (assoc scol stored-list
)))
1656 ((and stored equation
(string-match "^ *=? *$" equation
))
1660 (t (org-table-formula-from-user
1662 (org-table-formula-to-user
1663 (format "%s formula %s%s="
1664 (if named
"Field" "Column")
1665 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
1667 (if stored
(org-table-formula-to-user stored
) "")
1668 'org-table-formula-history
1671 (when (not (string-match "\\S-" eq
))
1673 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
1674 (org-table-store-formulas stored-list
)
1675 (error "Formula removed"))
1676 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
1677 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
1678 (if (and name
(not named
))
1679 ;; We set the column equation, delete the named one.
1680 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
1683 (setcdr (assoc scol stored-list
) eq
)
1684 (setq stored-list
(cons (cons scol eq
) stored-list
)))
1685 (if (or mustsave
(not (equal stored eq
)))
1686 (org-table-store-formulas stored-list
))
1689 (defun org-table-store-formulas (alist)
1690 "Store the list of formulas below the current table."
1691 (setq alist
(sort alist
'org-table-formula-less-p
))
1693 (goto-char (org-table-end))
1694 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
1696 ;; don't overwrite TBLFM, we might use text properties to store stuff
1697 (goto-char (match-beginning 2))
1698 (delete-region (match-beginning 2) (match-end 0)))
1699 (insert "#+TBLFM:"))
1701 (mapconcat (lambda (x)
1703 (if (equal (string-to-char (car x
)) ?
@) "" "$")
1704 (car x
) "=" (cdr x
)))
1708 (defsubst org-table-formula-make-cmp-string
(a)
1709 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a
)
1711 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a
))) "")
1712 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a
))) "")
1713 (if (match-end 5) (concat "@@" (match-string 5 a
))))))
1715 (defun org-table-formula-less-p (a b
)
1716 "Compare two formulas for sorting."
1717 (let ((as (org-table-formula-make-cmp-string (car a
)))
1718 (bs (org-table-formula-make-cmp-string (car b
))))
1719 (and as bs
(string< as bs
))))
1721 (defun org-table-get-stored-formulas (&optional noerror
)
1722 "Return an alist with the stored formulas directly after current table."
1724 (let (scol eq eq-alist strings string seen
)
1726 (goto-char (org-table-end))
1727 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
1728 (setq strings
(org-split-string (match-string 2) " *:: *"))
1729 (while (setq string
(pop strings
))
1730 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
1731 (setq scol
(if (match-end 2)
1732 (match-string 2 string
)
1733 (match-string 1 string
))
1734 eq
(match-string 3 string
)
1735 eq-alist
(cons (cons scol eq
) eq-alist
))
1736 (if (member scol seen
)
1739 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
1742 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
1743 (push scol seen
))))))
1744 (nreverse eq-alist
)))
1746 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
1747 "Modify the equations after the table structure has been edited.
1748 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
1749 For all numbers larger than LIMIT, shift them by DELTA."
1751 (goto-char (org-table-end))
1752 (when (looking-at "#\\+TBLFM:")
1753 (let ((re (concat key
"\\([0-9]+\\)"))
1757 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove
)
1758 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
1761 (while (re-search-forward re2
(point-at-eol) t
)
1762 (replace-match "")))
1763 (while (re-search-forward re
(point-at-eol) t
)
1764 (setq s
(match-string 1) n
(string-to-number s
))
1766 ((setq a
(assoc s replace
))
1767 (replace-match (concat key
(cdr a
)) t t
))
1768 ((and limit
(> n limit
))
1769 (replace-match (concat key
(int-to-string (+ n delta
))) t t
))))))))
1771 (defun org-table-get-specials ()
1772 "Get the column names and local parameters for this table."
1774 (let ((beg (org-table-begin)) (end (org-table-end))
1775 names name fields fields1 field cnt
1776 c v l line col types dlines hlines
)
1777 (setq org-table-column-names nil
1778 org-table-local-parameters nil
1779 org-table-named-field-locations nil
1780 org-table-current-begin-line nil
1781 org-table-current-begin-pos nil
1782 org-table-current-line-types nil
)
1784 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
1785 (setq names
(org-split-string (match-string 1) " *| *")
1787 (while (setq name
(pop names
))
1789 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name
)
1790 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
1791 (setq org-table-column-names
(nreverse org-table-column-names
))
1792 (setq org-table-column-name-regexp
1793 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
1795 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
1796 (setq fields
(org-split-string (match-string 1) " *| *"))
1797 (while (setq field
(pop fields
))
1798 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
1799 (push (cons (match-string 1 field
) (match-string 2 field
))
1800 org-table-local-parameters
))))
1802 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
1803 (setq c
(match-string 1)
1804 fields
(org-split-string (match-string 2) " *| *"))
1806 (beginning-of-line (if (equal c
"_") 2 0))
1807 (setq line
(org-current-line) col
1)
1808 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
1809 (setq fields1
(org-split-string (match-string 1) " *| *"))))
1810 (while (and fields1
(setq field
(pop fields
)))
1811 (setq v
(pop fields1
) col
(1+ col
))
1812 (when (and (stringp field
) (stringp v
)
1813 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field
))
1814 (push (cons field v
) org-table-local-parameters
)
1815 (push (list field line col
) org-table-named-field-locations
))))
1816 ;; Analyse the line types
1818 (setq org-table-current-begin-line
(org-current-line)
1819 org-table-current-begin-pos
(point)
1820 l org-table-current-begin-line
)
1821 (while (looking-at "[ \t]*|\\(-\\)?")
1822 (push (if (match-end 1) 'hline
'dline
) types
)
1823 (if (match-end 1) (push l hlines
) (push l dlines
))
1824 (beginning-of-line 2)
1826 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
1827 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
1828 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
)))))))
1830 (defun org-table-maybe-eval-formula ()
1831 "Check if the current field starts with \"=\" or \":=\".
1832 If yes, store the formula and apply it."
1833 ;; We already know we are in a table. Get field will only return a formula
1834 ;; when appropriate. It might return a separator line, but no problem.
1835 (when org-table-formula-evaluate-inline
1836 (let* ((field (org-trim (or (org-table-get-field) "")))
1838 (when (string-match "^:?=\\(.*\\)" field
)
1839 (setq named
(equal (string-to-char field
) ?
:)
1840 eq
(match-string 1 field
))
1841 (if (or (fboundp 'calc-eval
)
1842 (equal (substring eq
0 (min 2 (length eq
))) "'("))
1843 (org-table-eval-formula (if named
'(4) nil
)
1844 (org-table-formula-from-user eq
))
1845 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
1847 (defvar org-recalc-commands nil
1848 "List of commands triggering the recalculation of a line.
1849 Will be filled automatically during use.")
1851 (defvar org-recalc-marks
1852 '((" " .
"Unmarked: no special line, no automatic recalculation")
1853 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
1854 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
1855 ("!" .
"Column name definition line. Reference in formula as $name.")
1856 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
1857 ("_" .
"Names for values in row below this one.")
1858 ("^" .
"Names for values in row above this one.")))
1860 (defun org-table-rotate-recalc-marks (&optional newchar
)
1861 "Rotate the recalculation mark in the first column.
1862 If in any row, the first field is not consistent with a mark,
1863 insert a new column for the markers.
1864 When there is an active region, change all the lines in the region,
1865 after prompting for the marking character.
1866 After each change, a message will be displayed indicating the meaning
1869 (unless (org-at-table-p) (error "Not at a table"))
1870 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
1871 (beg (org-table-begin))
1872 (end (org-table-end))
1873 (l (org-current-line))
1874 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
1875 (l2 (if (org-region-active-p) (org-current-line (region-end))))
1879 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
1880 (col (org-table-current-column))
1881 (forcenew (car (assoc newchar org-recalc-marks
)))
1884 (message "Change region to what mark? Type # * ! $ or SPC: ")
1885 (setq newchar
(char-to-string (read-char-exclusive))
1886 forcenew
(car (assoc newchar org-recalc-marks
))))
1887 (if (and newchar
(not forcenew
))
1888 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
1890 (if l1
(goto-line l1
))
1892 (beginning-of-line 1)
1893 (unless (looking-at org-table-dataline-regexp
)
1894 (error "Not at a table data line")))
1896 (org-table-goto-column 1)
1897 (org-table-insert-column)
1898 (org-table-goto-column (1+ col
)))
1899 (setq epos
(point-at-eol))
1901 (beginning-of-line 1)
1902 (org-table-get-field
1903 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
1905 (setq new
(or forcenew
1906 (cadr (member (match-string 1) marks
))))
1912 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
1913 (and (looking-at org-table-dataline-regexp
)
1914 (org-table-get-field 1 (concat " " new
" "))))
1916 (if (not (= epos
(point-at-eol))) (org-table-align))
1918 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks
))))))
1920 (defun org-table-maybe-recalculate-line ()
1921 "Recompute the current line if marked for it, and if we haven't just done it."
1923 (and org-table-allow-automatic-line-recalculation
1924 (not (and (memq last-command org-recalc-commands
)
1925 (equal org-last-recalc-line
(org-current-line))))
1926 (save-excursion (beginning-of-line 1)
1927 (looking-at org-table-auto-recalculate-regexp
))
1928 (org-table-recalculate) t
))
1930 (defvar org-table-formula-debug nil
1931 "Non-nil means, debug table formulas.
1932 When nil, simply write \"#ERROR\" in corrupted fields.")
1933 (make-variable-buffer-local 'org-table-formula-debug
)
1936 (defsubst org-set-calc-mode
(var &optional value
)
1938 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
1939 ("R" calc-angle-mode rad
)
1940 ("F" calc-prefer-frac t
)
1941 ("S" calc-symbolic-mode t
)))
1942 value
(nth 2 var
) var
(nth 1 var
)))
1943 (if (memq var modes
)
1944 (setcar (cdr (memq var modes
)) value
)
1945 (cons var
(cons value modes
)))
1948 (defun org-table-eval-formula (&optional arg equation
1949 suppress-align suppress-const
1950 suppress-store suppress-analysis
)
1951 "Replace the table field value at the cursor by the result of a calculation.
1953 This function makes use of Dave Gillespie's Calc package, in my view the
1954 most exciting program ever written for GNU Emacs. So you need to have Calc
1955 installed in order to use this function.
1957 In a table, this command replaces the value in the current field with the
1958 result of a formula. It also installs the formula as the \"current\" column
1959 formula, by storing it in a special line below the table. When called
1960 with a `C-u' prefix, the current field must ba a named field, and the
1961 formula is installed as valid in only this specific field.
1963 When called with two `C-u' prefixes, insert the active equation
1964 for the field back into the current field, so that it can be
1965 edited there. This is useful in order to use \\[org-table-show-reference]
1966 to check the referenced fields.
1968 When called, the command first prompts for a formula, which is read in
1969 the minibuffer. Previously entered formulas are available through the
1970 history list, and the last used formula is offered as a default.
1971 These stored formulas are adapted correctly when moving, inserting, or
1972 deleting columns with the corresponding commands.
1974 The formula can be any algebraic expression understood by the Calc package.
1975 For details, see the Org-mode manual.
1977 This function can also be called from Lisp programs and offers
1978 additional arguments: EQUATION can be the formula to apply. If this
1979 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
1980 used to speed-up recursive calls by by-passing unnecessary aligns.
1981 SUPPRESS-CONST suppresses the interpretation of constants in the
1982 formula, assuming that this has been done already outside the function.
1983 SUPPRESS-STORE means the formula should not be stored, either because
1984 it is already stored, or because it is a modified equation that should
1985 not overwrite the stored one."
1987 (org-table-check-inside-data-field)
1988 (or suppress-analysis
(org-table-get-specials))
1989 (if (equal arg
'(16))
1990 (let ((eq (org-table-current-field-formula)))
1991 (or eq
(error "No equation active for current field"))
1992 (org-table-get-field nil eq
)
1994 (setq org-table-may-need-update t
))
1996 (ndown (if (integerp arg
) arg
1))
1997 (org-table-automatic-realign nil
)
1998 (case-fold-search nil
)
2000 (formula (if (and equation suppress-store
)
2002 (org-table-get-formula equation
(equal arg
'(4)))))
2003 (n0 (org-table-current-column))
2004 (modes (copy-sequence org-calc-default-modes
))
2005 (numbers nil
) ; was a variable, now fixed default
2007 n form form0 bw fmt x ev orig c lispp literal
)
2008 ;; Parse the format string. Since we have a lot of modes, this is
2009 ;; a lot of work. However, I think calc still uses most of the time.
2010 (if (string-match ";" formula
)
2011 (let ((tmp (org-split-string formula
";")))
2012 (setq formula
(car tmp
)
2013 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2015 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2016 (setq c
(string-to-char (match-string 1 fmt
))
2017 n
(string-to-number (match-string 2 fmt
)))
2019 (setq modes
(org-set-calc-mode 'calc-internal-prec n
))
2020 (setq modes
(org-set-calc-mode
2022 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2023 (?s . sci
) (?e . eng
))))
2025 (setq fmt
(replace-match "" t t fmt
)))
2026 (if (string-match "[NT]" fmt
)
2027 (setq numbers
(equal (match-string 0 fmt
) "N")
2028 fmt
(replace-match "" t t fmt
)))
2029 (if (string-match "L" fmt
)
2031 fmt
(replace-match "" t t fmt
)))
2032 (if (string-match "E" fmt
)
2034 fmt
(replace-match "" t t fmt
)))
2035 (while (string-match "[DRFS]" fmt
)
2036 (setq modes
(org-set-calc-mode (match-string 0 fmt
)))
2037 (setq fmt
(replace-match "" t t fmt
)))
2038 (unless (string-match "\\S-" fmt
)
2040 (if (and (not suppress-const
) org-table-formula-use-constants
)
2041 (setq formula
(org-table-formula-substitute-names formula
)))
2042 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2044 (setq fields
(org-split-string
2046 (buffer-substring (point-at-bol) (point-at-eol)))
2049 (setq fields
(mapcar
2050 (lambda (x) (number-to-string (string-to-number x
)))
2052 (setq ndown
(1- ndown
))
2053 (setq form
(copy-sequence formula
)
2054 lispp
(and (> (length form
) 2)(equal (substring form
0 2) "'(")))
2055 (if (and lispp literal
) (setq lispp
'literal
))
2056 ;; Check for old vertical references
2057 (setq form
(org-rewrite-old-row-references form
))
2058 ;; Insert complex ranges
2059 (while (string-match org-table-range-regexp form
)
2063 (org-table-make-reference
2064 (org-table-get-range (match-string 0 form
) nil n0
)
2065 keep-empty numbers lispp
))
2067 ;; Insert simple ranges
2068 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2072 (org-table-make-reference
2074 fields
(string-to-number (match-string 1 form
))
2075 (string-to-number (match-string 2 form
)))
2076 keep-empty numbers lispp
))
2079 ;; Insert the references to fields in same row
2080 (while (string-match "\\$\\([0-9]+\\)" form
)
2081 (setq n
(string-to-number (match-string 1 form
))
2082 x
(nth (1- (if (= n
0) n0 n
)) fields
))
2083 (unless x
(error "Invalid field specifier \"%s\""
2084 (match-string 0 form
)))
2085 (setq form
(replace-match
2087 (org-table-make-reference x nil numbers lispp
))
2091 (setq ev
(condition-case nil
2092 (eval (eval (read form
)))
2094 ev
(if (numberp ev
) (number-to-string ev
) ev
))
2095 (or (fboundp 'calc-eval
)
2096 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2097 (setq ev
(calc-eval (cons form modes
)
2098 (if numbers
'num
))))
2100 (when org-table-formula-debug
2101 (with-output-to-temp-buffer "*Substitution History*"
2102 (princ (format "Substitution history of formula
2106 $1-> %s\n" orig formula form0 form
))
2108 (princ (format " %s^\nError: %s"
2109 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2110 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2112 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2113 (setq bw
(get-buffer-window "*Substitution History*"))
2114 (shrink-window-if-larger-than-buffer bw
)
2115 (unless (and (interactive-p) (not ndown
))
2116 (unless (let (inhibit-redisplay)
2117 (y-or-n-p "Debugging Formula. Continue to next? "))
2122 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2123 (org-table-justify-field-maybe
2124 (if fmt
(format fmt
(string-to-number ev
)) ev
))
2125 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2126 (call-interactively 'org-return
)
2128 (and down
(org-table-maybe-recalculate-line))
2129 (or suppress-align
(and org-table-may-need-update
2130 (org-table-align))))))
2132 (defun org-table-put-field-property (prop value
)
2134 (put-text-property (progn (skip-chars-backward "^|") (point))
2135 (progn (skip-chars-forward "^|") (point))
2138 (defun org-table-get-range (desc &optional tbeg col highlight
)
2139 "Get a calc vector from a column, accorting to descriptor DESC.
2140 Optional arguments TBEG and COL can give the beginning of the table and
2141 the current column, to avoid unnecessary parsing.
2142 HIGHLIGHT means, just highlight the range."
2143 (if (not (equal (string-to-char desc
) ?
@))
2144 (setq desc
(concat "@" desc
)))
2146 (or tbeg
(setq tbeg
(org-table-begin)))
2147 (or col
(setq col
(org-table-current-column)))
2148 (let ((thisline (org-current-line))
2149 beg end c1 c2 r1 r2 rangep tmp
)
2150 (unless (string-match org-table-range-regexp desc
)
2151 (error "Invalid table range specifier `%s'" desc
))
2152 (setq rangep
(match-end 3)
2153 r1
(and (match-end 1) (match-string 1 desc
))
2154 r2
(and (match-end 4) (match-string 4 desc
))
2155 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2156 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2158 (and c1
(setq c1
(+ (string-to-number c1
)
2159 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2160 (and c2
(setq c2
(+ (string-to-number c2
)
2161 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2162 (if (equal r1
"") (setq r1 nil
))
2163 (if (equal r2
"") (setq r2 nil
))
2164 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2165 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2166 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2167 (if (not r1
) (setq r1 thisline
))
2168 (if (not r2
) (setq r2 thisline
))
2169 (if (not c1
) (setq c1 col
))
2170 (if (not c2
) (setq c2 col
))
2171 (if (or (not rangep
) (and (= r1 r2
) (= c1 c2
)))
2175 (while (not (looking-at org-table-dataline-regexp
))
2176 (beginning-of-line 2))
2177 (prog1 (org-trim (org-table-get-field c1
))
2178 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2179 ;; A range, return a vector
2180 ;; First sort the numbers to get a regular ractangle
2181 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2182 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2184 (while (not (looking-at org-table-dataline-regexp
))
2185 (beginning-of-line 2))
2186 (org-table-goto-column c1
)
2189 (while (not (looking-at org-table-dataline-regexp
))
2190 (beginning-of-line 0))
2191 (org-table-goto-column c2
)
2194 (org-table-highlight-rectangle
2195 beg
(progn (skip-chars-forward "^|\n") (point))))
2196 ;; return string representation of calc vector
2198 (apply 'append
(org-table-copy-region beg end
)))))))
2200 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2201 "Analyze descriptor DESC and retrieve the corresponding line number.
2202 The cursor is currently in line CLINE, the table begins in line BLINE,
2203 and TABLE is a vector with line types."
2204 (if (string-match "^[0-9]+$" desc
)
2205 (aref org-table-dlines
(string-to-number desc
))
2206 (setq cline
(or cline
(org-current-line))
2207 bline
(or bline org-table-current-begin-line
)
2208 table
(or table org-table-current-line-types
))
2210 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2212 (and (not (match-end 3)) (not (match-end 6)))
2213 (and (match-end 3) (match-end 6) (not (match-end 5))))
2214 (error "invalid row descriptor `%s'" desc
))
2215 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2216 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2217 (odir (and (match-end 5) (match-string 5 desc
)))
2218 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2220 (rel (and (match-end 6)
2221 (or (and (match-end 1) (not (match-end 3)))
2223 (if (and hn
(not hdir
))
2226 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2227 (if (and (not hn
) on
(not odir
))
2228 (error "should never happen");;(aref org-table-dlines on)
2229 (if (and hn
(> hn
0))
2230 (setq i
(org-find-row-type table i
'hline
(equal hdir
"-") nil hn
)))
2232 (setq i
(org-find-row-type table i
'dline
(equal odir
"-") rel on
)))
2235 (defun org-find-row-type (table i type backwards relative n
)
2236 (let ((l (length table
)))
2238 (while (and (setq i
(+ i
(if backwards -
1 1)))
2240 (not (eq (aref table i
) type
))
2241 (if (and relative
(eq (aref table i
) 'hline
))
2242 (progn (setq i
(- i
(if backwards -
1 1)) n
1) nil
)
2245 (if (or (< i
0) (>= i l
))
2246 (error "Row descriptor leads outside table")
2249 (defun org-rewrite-old-row-references (s)
2250 (if (string-match "&[-+0-9I]" s
)
2251 (error "Formula contains old &row reference, please rewrite using @-syntax")
2254 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2255 "Convert list ELEMENTS to something appropriate to insert into formula.
2256 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2257 NUMBERS indicates that everything should be converted to numbers.
2258 LISPP means to return something appropriate for a Lisp list."
2259 (if (stringp elements
) ; just a single val
2261 (if (eq lispp
'literal
)
2263 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2264 (if (equal elements
"") (setq elements
"0"))
2265 (if numbers
(number-to-string (string-to-number elements
)) elements
))
2269 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2271 (setq elements
(or elements
'("0")))
2275 (if (eq lispp
'literal
)
2277 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2279 (concat "[" (mapconcat
2281 (if numbers
(number-to-string (string-to-number x
)) x
))
2285 (defun org-table-recalculate (&optional all noalign
)
2286 "Recalculate the current table line by applying all stored formulas.
2287 With prefix arg ALL, do this for all lines in the table."
2289 (or (memq this-command org-recalc-commands
)
2290 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2291 (unless (org-at-table-p) (error "Not at a table"))
2292 (if (equal all
'(16))
2294 (org-table-get-specials)
2295 (let* ((eqlist (sort (org-table-get-stored-formulas)
2296 (lambda (a b
) (string< (car a
) (car b
)))))
2297 (inhibit-redisplay (not debug-on-error
))
2298 (line-re org-table-dataline-regexp
)
2299 (thisline (org-current-line))
2300 (thiscol (org-table-current-column))
2301 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name
)
2302 ;; Insert constants in all formulas
2305 (setcdr x
(org-table-formula-substitute-names (cdr x
)))
2308 ;; Split the equation list
2309 (while (setq eq
(pop eqlist
))
2310 (if (<= (string-to-char (car eq
)) ?
9)
2313 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
2316 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
2317 (goto-char (setq beg
(org-table-begin)))
2318 (if (re-search-forward org-table-calculate-mark-regexp end t
)
2319 ;; This is a table with marked lines, compute selected lines
2320 (setq line-re org-table-recalculate-regexp
)
2321 ;; Move forward to the first non-header line
2322 (if (and (re-search-forward org-table-dataline-regexp end t
)
2323 (re-search-forward org-table-hline-regexp end t
)
2324 (re-search-forward org-table-dataline-regexp end t
))
2325 (setq beg
(match-beginning 0))
2326 nil
))) ;; just leave beg where it is
2327 (setq beg
(point-at-bol)
2328 end
(move-marker (make-marker) (1+ (point-at-eol)))))
2330 (and all
(message "Re-applying formulas to full table..."))
2332 ;; First find the named fields, and mark them untouchanble
2333 (remove-text-properties beg end
'(org-untouchable t
))
2334 (while (setq eq
(pop eqlname
))
2336 a
(assoc name org-table-named-field-locations
))
2338 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
2340 (aref org-table-dlines
2341 (string-to-number (match-string 1 name
)))
2342 (string-to-number (match-string 2 name
)))))
2343 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
2344 (message "Re-applying formula to field: %s" name
)
2345 (goto-line (nth 1 a
))
2346 (org-table-goto-column (nth 2 a
))
2347 (push (append a
(list (cdr eq
))) eqlname1
)
2348 (org-table-put-field-property :org-untouchable t
)))
2350 ;; Now evauluate the column formulas, but skip fields covered by
2353 (while (re-search-forward line-re end t
)
2354 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2355 ;; Unprotected line, recalculate
2356 (and all
(message "Re-applying formulas to full table...(line %d)"
2357 (setq cnt
(1+ cnt
))))
2358 (setq org-last-recalc-line
(org-current-line))
2360 (while (setq entry
(pop eql
))
2361 (goto-line org-last-recalc-line
)
2362 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
2363 (unless (get-text-property (point) :org-untouchable
)
2364 (org-table-eval-formula nil
(cdr entry
)
2365 'noalign
'nocst
'nostore
'noanalysis
)))))
2367 ;; Now evaluate the field formulas
2368 (while (setq eq
(pop eqlname1
))
2369 (message "Re-applying formula to field: %s" (car eq
))
2370 (goto-line (nth 1 eq
))
2371 (org-table-goto-column (nth 2 eq
))
2372 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
2373 'nostore
'noanalysis
))
2375 (goto-line thisline
)
2376 (org-table-goto-column thiscol
)
2377 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
2378 (or noalign
(and org-table-may-need-update
(org-table-align))
2379 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
2381 ;; back to initial position
2382 (message "Re-applying formulas...done")
2383 (goto-line thisline
)
2384 (org-table-goto-column thiscol
)
2385 (or noalign
(and org-table-may-need-update
(org-table-align))
2386 (and all
(message "Re-applying formulas...done"))))))
2388 (defun org-table-iterate (&optional arg
)
2389 "Recalculate the table until it does not change anymore."
2391 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
2393 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2398 (org-table-recalculate 'all
)
2399 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
2400 (if (not (string= lasttbl thistbl
))
2401 (setq lasttbl thistbl
)
2403 (message "Convergence after %d iterations" i
)
2404 (message "Table was already stable"))
2406 (error "No convergence after %d iterations" i
))))
2408 (defun org-table-formula-substitute-names (f)
2409 "Replace $const with values in string F."
2410 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
2411 ;; First, check for column names
2412 (while (setq start
(string-match org-table-column-name-regexp f start
))
2413 (setq start
(1+ start
))
2414 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
2415 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
2416 ;; Parameters and constants
2418 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start
))
2419 (setq start
(1+ start
))
2420 (if (setq a
(save-match-data
2421 (org-table-get-constant (match-string 1 f
))))
2422 (setq f
(replace-match
2423 (concat (if pp
"(") a
(if pp
")")) t t f
))))
2424 (if org-table-formula-debug
2425 (put-text-property 0 (length f
) :orig-formula f1 f
))
2428 (defun org-table-get-constant (const)
2429 "Find the value for a parameter or constant in a formula.
2430 Parameters get priority."
2431 (or (cdr (assoc const org-table-local-parameters
))
2432 (cdr (assoc const org-table-formula-constants-local
))
2433 (cdr (assoc const org-table-formula-constants
))
2434 (and (fboundp 'constants-get
) (constants-get const
))
2435 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
2436 (org-entry-get nil
(substring const
5) 'inherit
))
2439 (defvar org-table-fedit-map
2440 (let ((map (make-sparse-keymap)))
2441 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
2442 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
2443 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
2444 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
2445 (org-defkey map
"\C-c?" 'org-table-show-reference
)
2446 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
2447 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
2448 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
2449 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
2450 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
2451 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
2452 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
2453 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
2454 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
2455 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
2456 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
2457 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
2458 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
2459 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
2462 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
2464 ["Finish and Install" org-table-fedit-finish t
]
2465 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
2466 ["Abort" org-table-fedit-abort t
]
2468 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
2469 ["Complete Lisp Symbol" lisp-complete-symbol t
]
2471 "Shift Reference at Point"
2472 ["Up" org-table-fedit-ref-up t
]
2473 ["Down" org-table-fedit-ref-down t
]
2474 ["Left" org-table-fedit-ref-left t
]
2475 ["Right" org-table-fedit-ref-right t
]
2477 "Change Test Row for Column Formulas"
2478 ["Up" org-table-fedit-line-up t
]
2479 ["Down" org-table-fedit-line-down t
]
2481 ["Scroll Table Window" org-table-fedit-scroll t
]
2482 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
2483 ["Show Table Grid" org-table-fedit-toggle-coordinates
2484 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
2485 org-table-overlay-coordinates
)]
2487 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
2488 :style toggle
:selected org-table-buffer-is-an
]))
2492 (defun org-table-edit-formulas ()
2493 "Edit the formulas of the current table in a separate buffer."
2495 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
2496 (beginning-of-line 0))
2497 (unless (org-at-table-p) (error "Not at a table"))
2498 (org-table-get-specials)
2499 (let ((key (org-table-current-field-formula 'key
'noerror
))
2500 (eql (sort (org-table-get-stored-formulas 'noerror
)
2501 'org-table-formula-less-p
))
2502 (pos (move-marker (make-marker) (point)))
2504 (wc (current-window-configuration))
2505 (titles '((column .
"# Column Formulas\n")
2506 (field .
"# Field Formulas\n")
2507 (named .
"# Named Field Formulas\n")))
2509 (org-switch-to-buffer-other-window "*Edit Formulas*")
2511 ;; Keep global-font-lock-mode from turning on font-lock-mode
2512 (let ((font-lock-global-modes '(not fundamental-mode
)))
2514 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
2515 (org-set-local 'org-pos pos
)
2516 (org-set-local 'org-window-configuration wc
)
2517 (use-local-map org-table-fedit-map
)
2518 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
2519 (easy-menu-add org-table-fedit-menu
)
2520 (setq startline
(org-current-line))
2521 (while (setq entry
(pop eql
))
2523 ((equal (string-to-char (car entry
)) ?
@) 'field
)
2524 ((string-match "^[0-9]" (car entry
)) 'column
)
2526 (when (setq title
(assq type titles
))
2527 (or (bobp) (insert "\n"))
2528 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
2529 (setq titles
(delq title titles
)))
2530 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
2531 (setq s
(concat (if (equal (string-to-char (car entry
)) ?
@) "" "$")
2532 (car entry
) " = " (cdr entry
) "\n"))
2533 (remove-text-properties 0 (length s
) '(face nil
) s
)
2535 (if (eq org-table-use-standard-references t
)
2536 (org-table-fedit-toggle-ref-type))
2537 (goto-line startline
)
2538 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
2540 (defun org-table-fedit-post-command ()
2541 (when (not (memq this-command
'(lisp-complete-symbol)))
2542 (let ((win (selected-window)))
2545 (org-table-show-reference)
2547 (select-window win
)))))
2549 (defun org-table-formula-to-user (s)
2550 "Convert a formula from internal to user representation."
2551 (if (eq org-table-use-standard-references t
)
2552 (org-table-convert-refs-to-an s
)
2555 (defun org-table-formula-from-user (s)
2556 "Convert a formula from user to internal representation."
2557 (if org-table-use-standard-references
2558 (org-table-convert-refs-to-rc s
)
2561 (defun org-table-convert-refs-to-rc (s)
2562 "Convert spreadsheet references from AB7 to @7$28.
2563 Works for single references, but also for entire formulas and even the
2566 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start
)
2569 ;; format match, just advance
2570 (setq start
(match-end 0)))
2571 ((and (> (match-beginning 0) 0)
2572 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
2573 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
2574 ;; 3.e5 or something like this.
2575 (setq start
(match-end 0)))
2577 (setq start
(match-beginning 0)
2579 (if (equal (match-string 2 s
) "&")
2580 (format "$%d" (org-letters-to-number (match-string 1 s
)))
2582 (string-to-number (match-string 2 s
))
2583 (org-letters-to-number (match-string 1 s
))))
2587 (defun org-table-convert-refs-to-an (s)
2588 "Convert spreadsheet references from to @7$28 to AB7.
2589 Works for single references, but also for entire formulas and even the
2591 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
2592 (setq s
(replace-match
2594 (org-number-to-letters
2595 (string-to-number (match-string 2 s
)))
2596 (string-to-number (match-string 1 s
)))
2598 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
2599 (setq s
(replace-match (concat "\\1"
2600 (org-number-to-letters
2601 (string-to-number (match-string 2 s
))) "&")
2605 (defun org-letters-to-number (s)
2606 "Convert a base 26 number represented by letters into an integer.
2607 For example: AB -> 28."
2610 (while (> (length s
) 0)
2611 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
2615 (defun org-number-to-letters (n)
2616 "Convert an integer into a base 26 number represented by letters.
2617 For example: 28 -> AB."
2620 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
2624 (defun org-table-fedit-convert-buffer (function)
2625 "Convert all references in this buffer, using FUNTION."
2626 (let ((line (org-current-line)))
2627 (goto-char (point-min))
2629 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
2630 (delete-region (point) (point-at-eol))
2631 (or (eobp) (forward-char 1)))
2634 (defun org-table-fedit-toggle-ref-type ()
2635 "Convert all references in the buffer from B3 to @3$2 and back."
2637 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
2638 (org-table-fedit-convert-buffer
2639 (if org-table-buffer-is-an
2640 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
2641 (message "Reference type switched to %s"
2642 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
2644 (defun org-table-fedit-ref-up ()
2645 "Shift the reference at point one row/hline up."
2647 (org-table-fedit-shift-reference 'up
))
2648 (defun org-table-fedit-ref-down ()
2649 "Shift the reference at point one row/hline down."
2651 (org-table-fedit-shift-reference 'down
))
2652 (defun org-table-fedit-ref-left ()
2653 "Shift the reference at point one field to the left."
2655 (org-table-fedit-shift-reference 'left
))
2656 (defun org-table-fedit-ref-right ()
2657 "Shift the reference at point one field to the right."
2659 (org-table-fedit-shift-reference 'right
))
2661 (defun org-table-fedit-shift-reference (dir)
2663 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
2664 (if (memq dir
'(left right
))
2665 (org-rematch-and-replace 1 (eq dir
'left
))
2666 (error "Cannot shift reference in this direction")))
2667 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
2668 ;; A B3-like reference
2669 (if (memq dir
'(up down
))
2670 (org-rematch-and-replace 2 (eq dir
'up
))
2671 (org-rematch-and-replace 1 (eq dir
'left
))))
2673 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
2674 ;; An internal reference
2675 (if (memq dir
'(up down
))
2676 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
2677 (org-rematch-and-replace 5 (eq dir
'left
))))))
2679 (defun org-rematch-and-replace (n &optional decr hline
)
2680 "Re-match the group N, and replace it with the shifted refrence."
2681 (or (match-end n
) (error "Cannot shift reference in this direction"))
2682 (goto-char (match-beginning n
))
2683 (and (looking-at (regexp-quote (match-string n
)))
2684 (replace-match (org-shift-refpart (match-string 0) decr hline
)
2687 (defun org-shift-refpart (ref &optional decr hline
)
2688 "Shift a refrence part REF.
2689 If DECR is set, decrease the references row/column, else increase.
2690 If HLINE is set, this may be a hline reference, it certainly is not
2691 a translation reference."
2693 (let* ((sign (string-match "^[-+]" ref
)) n
)
2695 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
2697 ((and hline
(string-match "^I+" ref
))
2698 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
2699 (setq n
(+ n
(if decr -
1 1)))
2700 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
2702 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
2704 (concat sign
(make-string n ?I
)))
2706 ((string-match "^[0-9]+" ref
)
2707 (setq n
(string-to-number (concat sign ref
)))
2708 (setq n
(+ n
(if decr -
1 1)))
2710 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
2711 (number-to-string (max 1 n
))))
2713 ((string-match "^[a-zA-Z]+" ref
)
2714 (org-number-to-letters
2715 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
2717 (t (error "Cannot shift reference"))))))
2719 (defun org-table-fedit-toggle-coordinates ()
2720 "Toggle the display of coordinates in the refrenced table."
2722 (let ((pos (marker-position org-pos
)))
2723 (with-current-buffer (marker-buffer org-pos
)
2726 (org-table-toggle-coordinate-overlays)))))
2728 (defun org-table-fedit-finish (&optional arg
)
2729 "Parse the buffer for formula definitions and install them.
2730 With prefix ARG, apply the new formulas to the table."
2732 (org-table-remove-rectangle-highlight)
2733 (if org-table-use-standard-references
2735 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
2736 (setq org-table-buffer-is-an nil
)))
2737 (let ((pos org-pos
) eql var form
)
2738 (goto-char (point-min))
2739 (while (re-search-forward
2740 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
2742 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
2743 form
(match-string 3))
2744 (setq form
(org-trim form
))
2745 (when (not (equal form
""))
2746 (while (string-match "[ \t]*\n[ \t]*" form
)
2747 (setq form
(replace-match " " t t form
)))
2748 (when (assoc var eql
)
2749 (error "Double formulas for %s" var
))
2750 (push (cons var form
) eql
)))
2752 (set-window-configuration org-window-configuration
)
2753 (select-window (get-buffer-window (marker-buffer pos
)))
2755 (unless (org-at-table-p)
2756 (error "Lost table position - cannot install formulae"))
2757 (org-table-store-formulas eql
)
2758 (move-marker pos nil
)
2759 (kill-buffer "*Edit Formulas*")
2761 (org-table-recalculate 'all
)
2762 (message "New formulas installed - press C-u C-c C-c to apply."))))
2764 (defun org-table-fedit-abort ()
2765 "Abort editing formulas, without installing the changes."
2767 (org-table-remove-rectangle-highlight)
2768 (let ((pos org-pos
))
2769 (set-window-configuration org-window-configuration
)
2770 (select-window (get-buffer-window (marker-buffer pos
)))
2772 (move-marker pos nil
)
2773 (message "Formula editing aborted without installing changes")))
2775 (defun org-table-fedit-lisp-indent ()
2776 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
2778 (let ((pos (point)) beg end ind
)
2779 (beginning-of-line 1)
2781 ((looking-at "[ \t]")
2783 (call-interactively 'lisp-indent-line
))
2784 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
2785 ((not (fboundp 'pp-buffer
))
2786 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
2787 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
2788 (goto-char (- (match-end 0) 2))
2790 (setq ind
(make-string (current-column) ?\
))
2791 (condition-case nil
(forward-sexp 1)
2793 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
2796 (narrow-to-region beg end
)
2797 (if (eq last-command this-command
)
2799 (goto-char (point-min))
2800 (setq this-command nil
)
2801 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
2802 (replace-match " ")))
2804 (untabify (point-min) (point-max))
2805 (goto-char (1+ (point-min)))
2806 (while (re-search-forward "^." nil t
)
2807 (beginning-of-line 1)
2809 (goto-char (point-max))
2810 (backward-delete-char 1)))
2814 (defvar org-show-positions nil
)
2816 (defun org-table-show-reference (&optional local
)
2817 "Show the location/value of the $ expression at point."
2819 (org-table-remove-rectangle-highlight)
2821 (let ((pos (if local
(point) org-pos
))
2823 (org-inhibit-highlight-removal t
)
2824 (win (selected-window))
2825 (org-show-positions nil
)
2826 var name e what match dest
)
2827 (if local
(org-table-get-specials))
2829 ((or (org-at-regexp-p org-table-range-regexp2
)
2830 (org-at-regexp-p org-table-translate-regexp
)
2831 (org-at-regexp-p org-table-range-regexp
))
2834 (org-table-convert-refs-to-rc (match-string 0))))
2836 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
2837 ((org-at-regexp-p "\\$[0-9]+") 'column
)
2839 (t (error "No reference at point")))
2840 match
(and what
(or match
(match-string 0))))
2841 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
2842 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
2843 'secondary-selection
))
2844 (org-add-hook 'before-change-functions
2845 'org-table-remove-rectangle-highlight
)
2846 (if (eq what
'name
) (setq var
(substring match
1)))
2847 (when (eq what
'range
)
2848 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
2849 (setq match
(org-table-formula-substitute-names match
)))
2853 (re-search-backward "^\\S-" nil t
)
2854 (beginning-of-line 1)
2855 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
2858 (org-table-convert-refs-to-rc (match-string 1))))
2859 (org-table-add-rectangle-overlay
2860 (match-beginning 1) (match-end 1) face2
))))
2861 (if (and (markerp pos
) (marker-buffer pos
))
2862 (if (get-buffer-window (marker-buffer pos
))
2863 (select-window (get-buffer-window (marker-buffer pos
)))
2864 (org-switch-to-buffer-other-window (get-buffer-window
2865 (marker-buffer pos
)))))
2867 (org-table-force-dataline)
2869 (setq name
(substring dest
1))
2871 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
2872 (setq e
(assoc name org-table-named-field-locations
))
2873 (goto-line (nth 1 e
))
2874 (org-table-goto-column (nth 2 e
)))
2875 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
2876 (let ((l (string-to-number (match-string 1 dest
)))
2877 (c (string-to-number (match-string 2 dest
))))
2878 (goto-line (aref org-table-dlines l
))
2879 (org-table-goto-column c
)))
2880 (t (org-table-goto-column (string-to-number name
))))
2881 (move-marker pos
(point))
2882 (org-table-highlight-rectangle nil nil face2
))
2884 ((equal dest match
))
2889 (org-table-get-range match nil nil
'highlight
))
2891 ((setq e
(assoc var org-table-named-field-locations
))
2892 (goto-line (nth 1 e
))
2893 (org-table-goto-column (nth 2 e
))
2894 (org-table-highlight-rectangle (point) (point))
2895 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
2896 ((setq e
(assoc var org-table-column-names
))
2897 (org-table-goto-column (string-to-number (cdr e
)))
2898 (org-table-highlight-rectangle (point) (point))
2899 (goto-char (org-table-begin))
2900 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
2903 (goto-char (match-beginning 1))
2904 (org-table-highlight-rectangle)
2905 (message "Named column (column %s)" (cdr e
)))
2906 (error "Column name not found")))
2909 (org-table-goto-column (string-to-number (substring match
1)))
2910 (org-table-highlight-rectangle (point) (point))
2911 (message "Column %s" (substring match
1)))
2912 ((setq e
(assoc var org-table-local-parameters
))
2913 (goto-char (org-table-begin))
2914 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
2916 (goto-char (match-beginning 1))
2917 (org-table-highlight-rectangle)
2918 (message "Local parameter."))
2919 (error "Parameter not found")))
2922 ((not var
) (error "No reference at point"))
2923 ((setq e
(assoc var org-table-formula-constants-local
))
2924 (message "Local Constant: $%s=%s in #+CONSTANTS line."
2926 ((setq e
(assoc var org-table-formula-constants
))
2927 (message "Constant: $%s=%s in `org-table-formula-constants'."
2929 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
2930 (message "Constant: $%s=%s, from `constants.el'%s."
2931 var e
(format " (%s units)" constants-unit-system
)))
2932 (t (error "Undefined name $%s" var
)))))
2934 (when (and org-show-positions
2935 (not (memq this-command
'(org-table-fedit-scroll
2936 org-table-fedit-scroll-down
))))
2937 (push pos org-show-positions
)
2938 (push org-table-current-begin-pos org-show-positions
)
2939 (let ((min (apply 'min org-show-positions
))
2940 (max (apply 'max org-show-positions
)))
2941 (goto-char min
) (recenter 0)
2943 (or (pos-visible-in-window-p max
) (recenter -
1))))
2944 (select-window win
))))
2946 (defun org-table-force-dataline ()
2947 "Make sure the cursor is in a dataline in a table."
2948 (unless (save-excursion
2949 (beginning-of-line 1)
2950 (looking-at org-table-dataline-regexp
))
2951 (let* ((re org-table-dataline-regexp
)
2952 (p1 (save-excursion (re-search-forward re nil
'move
)))
2953 (p2 (save-excursion (re-search-backward re nil
'move
))))
2955 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
2957 ((or p1 p2
) (goto-char (or p1 p2
)))
2958 (t (error "No table dataline around here"))))))
2960 (defun org-table-fedit-line-up ()
2961 "Move cursor one line up in the window showing the table."
2963 (org-table-fedit-move 'previous-line
))
2965 (defun org-table-fedit-line-down ()
2966 "Move cursor one line down in the window showing the table."
2968 (org-table-fedit-move 'next-line
))
2970 (defun org-table-fedit-move (command)
2971 "Move the cursor in the window shoinw the table.
2972 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
2973 (let ((org-table-allow-automatic-line-recalculation nil
)
2974 (pos org-pos
) (win (selected-window)) p
)
2975 (select-window (get-buffer-window (marker-buffer org-pos
)))
2977 (call-interactively command
)
2978 (while (and (org-at-table-p)
2979 (org-at-table-hline-p))
2980 (call-interactively command
))
2981 (or (org-at-table-p) (goto-char p
))
2982 (move-marker pos
(point))
2983 (select-window win
)))
2985 (defun org-table-fedit-scroll (N)
2987 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
2988 (scroll-other-window N
)))
2990 (defun org-table-fedit-scroll-down (N)
2992 (org-table-fedit-scroll (- N
)))
2994 (defvar org-table-rectangle-overlays nil
)
2996 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
2997 "Add a new overlay."
2998 (let ((ov (org-make-overlay beg end
)))
2999 (org-overlay-put ov
'face
(or face
'secondary-selection
))
3000 (push ov org-table-rectangle-overlays
)))
3002 (defun org-table-highlight-rectangle (&optional beg end face
)
3003 "Highlight rectangular region in a table."
3004 (setq beg
(or beg
(point)) end
(or end
(point)))
3005 (let ((b (min beg end
))
3008 (and (boundp 'org-show-positions
)
3009 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3010 (goto-char (min beg end
))
3011 (setq l1
(org-current-line)
3012 c1
(org-table-current-column))
3013 (goto-char (max beg end
))
3014 (setq l2
(org-current-line)
3015 c2
(org-table-current-column))
3016 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3018 (beginning-of-line 1)
3019 (loop for line from l1 to l2 do
3020 (when (looking-at org-table-dataline-regexp
)
3021 (org-table-goto-column c1
)
3022 (skip-chars-backward "^|\n") (setq beg
(point))
3023 (org-table-goto-column c2
)
3024 (skip-chars-forward "^|\n") (setq end
(point))
3025 (org-table-add-rectangle-overlay beg end face
))
3026 (beginning-of-line 2))
3028 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3030 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3031 "Remove the rectangle overlays."
3032 (unless org-inhibit-highlight-removal
3033 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3034 (mapc 'org-delete-overlay org-table-rectangle-overlays
)
3035 (setq org-table-rectangle-overlays nil
)))
3037 (defvar org-table-coordinate-overlays nil
3038 "Collects the cooordinate grid overlays, so that they can be removed.")
3039 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3041 (defun org-table-overlay-coordinates ()
3042 "Add overlays to the table at point, to show row/column coordinates."
3044 (mapc 'org-delete-overlay org-table-coordinate-overlays
)
3045 (setq org-table-coordinate-overlays nil
)
3047 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3048 (goto-char (org-table-begin))
3049 (while (org-at-table-p)
3050 (setq eol
(point-at-eol))
3051 (setq ov
(org-make-overlay (point-at-bol) (1+ (point-at-bol))))
3052 (push ov org-table-coordinate-overlays
)
3053 (setq hline
(looking-at org-table-hline-regexp
))
3054 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3055 (format "%4d" (setq id
(1+ id
)))))
3056 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3059 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3060 (setq beg
(1+ (match-beginning 0))
3062 s1
(concat "$" (int-to-string ic
))
3063 s2
(org-number-to-letters ic
)
3064 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3065 (setq ov
(org-make-overlay beg
(+ beg
(length str
))))
3066 (push ov org-table-coordinate-overlays
)
3067 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3068 (beginning-of-line 2)))))
3070 (defun org-table-toggle-coordinate-overlays ()
3071 "Toggle the display of Row/Column numbers in tables."
3073 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3074 (message "Row/Column number display turned %s"
3075 (if org-table-overlay-coordinates
"on" "off"))
3076 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3078 (unless org-table-overlay-coordinates
3079 (mapc 'org-delete-overlay org-table-coordinate-overlays
)
3080 (setq org-table-coordinate-overlays nil
)))
3082 (defun org-table-toggle-formula-debugger ()
3083 "Toggle the formula debugger in tables."
3085 (setq org-table-formula-debug
(not org-table-formula-debug
))
3086 (message "Formula debugging has been turned %s"
3087 (if org-table-formula-debug
"on" "off")))
3089 ;;; The orgtbl minor mode
3091 ;; Define a minor mode which can be used in other modes in order to
3092 ;; integrate the org-mode table editor.
3094 ;; This is really a hack, because the org-mode table editor uses several
3095 ;; keys which normally belong to the major mode, for example the TAB and
3096 ;; RET keys. Here is how it works: The minor mode defines all the keys
3097 ;; necessary to operate the table editor, but wraps the commands into a
3098 ;; function which tests if the cursor is currently inside a table. If that
3099 ;; is the case, the table editor command is executed. However, when any of
3100 ;; those keys is used outside a table, the function uses `key-binding' to
3101 ;; look up if the key has an associated command in another currently active
3102 ;; keymap (minor modes, major mode, global), and executes that command.
3103 ;; There might be problems if any of the keys used by the table editor is
3104 ;; otherwise used as a prefix key.
3106 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3107 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3108 ;; addresses this by checking explicitly for both bindings.
3110 ;; The optimized version (see variable `orgtbl-optimized') takes over
3111 ;; all keys which are bound to `self-insert-command' in the *global map*.
3112 ;; Some modes bind other commands to simple characters, for example
3113 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3114 ;; active, this binding is ignored inside tables and replaced with a
3115 ;; modified self-insert.
3117 (defvar orgtbl-mode nil
3118 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
3119 table editor in arbitrary modes.")
3120 (make-variable-buffer-local 'orgtbl-mode
)
3122 (defvar orgtbl-mode-map
(make-keymap)
3123 "Keymap for `orgtbl-mode'.")
3126 (defun turn-on-orgtbl ()
3127 "Unconditionally turn on `orgtbl-mode'."
3130 (defvar org-old-auto-fill-inhibit-regexp nil
3131 "Local variable used by `orgtbl-mode'")
3133 (defconst orgtbl-line-start-regexp
"[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
3134 "Matches a line belonging to an orgtbl.")
3136 (defconst orgtbl-extra-font-lock-keywords
3137 (list (list (concat "^" orgtbl-line-start-regexp
".*")
3138 0 (quote 'org-table
) 'prepend
))
3139 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
3142 (defun orgtbl-mode (&optional arg
)
3143 "The `org-mode' table editor as a minor mode for use in other modes."
3145 (org-load-modules-maybe)
3147 ;; Exit without error, in case some hook functions calls this
3148 ;; by accident in org-mode.
3149 (message "Orgtbl-mode is not useful in org-mode, command ignored")
3151 (if arg
(> (prefix-numeric-value arg
) 0) (not orgtbl-mode
)))
3154 (and (orgtbl-setup) (defun orgtbl-setup () nil
))
3155 ;; Make sure we are first in minor-mode-map-alist
3156 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
3157 (and c
(setq minor-mode-map-alist
3158 (cons c
(delq c minor-mode-map-alist
)))))
3159 (org-set-local (quote org-table-may-need-update
) t
)
3160 (org-add-hook 'before-change-functions
'org-before-change-function
3162 (org-set-local 'org-old-auto-fill-inhibit-regexp
3163 auto-fill-inhibit-regexp
)
3164 (org-set-local 'auto-fill-inhibit-regexp
3165 (if auto-fill-inhibit-regexp
3166 (concat orgtbl-line-start-regexp
"\\|"
3167 auto-fill-inhibit-regexp
)
3168 orgtbl-line-start-regexp
))
3169 (org-add-to-invisibility-spec '(org-cwidth))
3170 (when (fboundp 'font-lock-add-keywords
)
3171 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
3172 (org-restart-font-lock))
3173 (easy-menu-add orgtbl-mode-menu
)
3174 (run-hooks 'orgtbl-mode-hook
))
3175 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
3176 (org-cleanup-narrow-column-properties)
3177 (org-remove-from-invisibility-spec '(org-cwidth))
3178 (remove-hook 'before-change-functions
'org-before-change-function t
)
3179 (when (fboundp 'font-lock-remove-keywords
)
3180 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
3181 (org-restart-font-lock))
3182 (easy-menu-remove orgtbl-mode-menu
)
3183 (force-mode-line-update 'all
))))
3185 (defun org-cleanup-narrow-column-properties ()
3186 "Remove all properties related to narrow-column invisibility."
3188 (while (setq s
(text-property-any s
(point-max)
3189 'display org-narrow-column-arrow
))
3190 (remove-text-properties s
(1+ s
) '(display t
)))
3192 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
3193 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
3195 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
3196 (remove-text-properties s
(1+ s
) '(invisible t
)))))
3198 ;; Install it as a minor mode.
3199 (put 'orgtbl-mode
:included t
)
3200 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
3201 (add-minor-mode 'orgtbl-mode
" OrgTbl" orgtbl-mode-map
)
3203 (defun orgtbl-make-binding (fun n
&rest keys
)
3204 "Create a function for binding in the table minor mode.
3205 FUN is the command to call inside a table. N is used to create a unique
3206 command name. KEYS are keys that should be checked in for a command
3207 to execute outside of tables."
3210 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
3212 (concat "In tables, run `" (symbol-name fun
) "'.\n"
3213 "Outside of tables, run the binding of `"
3214 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
3219 (list 'call-interactively
(list 'quote fun
))
3220 (list 'let
'(orgtbl-mode)
3221 (list 'call-interactively
3224 (list 'key-binding k
))
3226 '('orgtbl-error
))))))))
3228 (defun orgtbl-error ()
3229 "Error when there is no default binding for a table key."
3231 (error "This key has no function outside tables"))
3233 (defun orgtbl-setup ()
3234 "Setup orgtbl keymaps."
3238 '([(meta shift left
)] org-table-delete-column
)
3239 '([(meta left
)] org-table-move-column-left
)
3240 '([(meta right
)] org-table-move-column-right
)
3241 '([(meta shift right
)] org-table-insert-column
)
3242 '([(meta shift up
)] org-table-kill-row
)
3243 '([(meta shift down
)] org-table-insert-row
)
3244 '([(meta up
)] org-table-move-row-up
)
3245 '([(meta down
)] org-table-move-row-down
)
3246 '("\C-c\C-w" org-table-cut-region
)
3247 '("\C-c\M-w" org-table-copy-region
)
3248 '("\C-c\C-y" org-table-paste-rectangle
)
3249 '("\C-c-" org-table-insert-hline
)
3250 '("\C-c}" org-table-toggle-coordinate-overlays
)
3251 '("\C-c{" org-table-toggle-formula-debugger
)
3252 '("\C-m" org-table-next-row
)
3253 '([(shift return
)] org-table-copy-down
)
3254 '("\C-c\C-q" org-table-wrap-region
)
3255 '("\C-c?" org-table-field-info
)
3256 '("\C-c " org-table-blank-field
)
3257 '("\C-c+" org-table-sum
)
3258 '("\C-c=" org-table-eval-formula
)
3259 '("\C-c'" org-table-edit-formulas
)
3260 '("\C-c`" org-table-edit-field
)
3261 '("\C-c*" org-table-recalculate
)
3262 '("\C-c|" org-table-create-or-convert-from-region
)
3263 '("\C-c^" org-table-sort-lines
)
3264 '([(control ?
#)] org-table-rotate-recalc-marks
)))
3266 (while (setq elt
(pop bindings
))
3267 (setq nfunc
(1+ nfunc
))
3268 (setq key
(org-key (car elt
))
3270 cmd
(orgtbl-make-binding fun nfunc key
))
3271 (org-defkey orgtbl-mode-map key cmd
))
3273 ;; Special treatment needed for TAB and RET
3274 (org-defkey orgtbl-mode-map
[(return)]
3275 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
3276 (org-defkey orgtbl-mode-map
"\C-m"
3277 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
3279 (org-defkey orgtbl-mode-map
[(tab)]
3280 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
3281 (org-defkey orgtbl-mode-map
"\C-i"
3282 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
3284 (org-defkey orgtbl-mode-map
[(shift tab
)]
3285 (orgtbl-make-binding 'org-table-previous-field
104
3286 [(shift tab
)] [(tab)] "\C-i"))
3288 (org-defkey orgtbl-mode-map
"\M-\C-m"
3289 (orgtbl-make-binding 'org-table-wrap-region
105
3290 "\M-\C-m" [(meta return
)]))
3291 (org-defkey orgtbl-mode-map
[(meta return
)]
3292 (orgtbl-make-binding 'org-table-wrap-region
106
3293 [(meta return
)] "\M-\C-m"))
3295 (org-defkey orgtbl-mode-map
"\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c
)
3296 (when orgtbl-optimized
3297 ;; If the user wants maximum table support, we need to hijack
3298 ;; some standard editing functions
3299 (org-remap orgtbl-mode-map
3300 'self-insert-command
'orgtbl-self-insert-command
3301 'delete-char
'org-delete-char
3302 'delete-backward-char
'org-delete-backward-char
)
3303 (org-defkey orgtbl-mode-map
"|" 'org-force-self-insert
))
3304 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map
"OrgTbl menu"
3306 ["Align" org-ctrl-c-ctrl-c
:active
(org-at-table-p) :keys
"C-c C-c"]
3307 ["Next Field" org-cycle
:active
(org-at-table-p) :keys
"TAB"]
3308 ["Previous Field" org-shifttab
:active
(org-at-table-p) :keys
"S-TAB"]
3309 ["Next Row" org-return
:active
(org-at-table-p) :keys
"RET"]
3311 ["Blank Field" org-table-blank-field
:active
(org-at-table-p) :keys
"C-c SPC"]
3312 ["Edit Field" org-table-edit-field
:active
(org-at-table-p) :keys
"C-c ` "]
3313 ["Copy Field from Above"
3314 org-table-copy-down
:active
(org-at-table-p) :keys
"S-RET"]
3317 ["Move Column Left" org-metaleft
:active
(org-at-table-p) :keys
"M-<left>"]
3318 ["Move Column Right" org-metaright
:active
(org-at-table-p) :keys
"M-<right>"]
3319 ["Delete Column" org-shiftmetaleft
:active
(org-at-table-p) :keys
"M-S-<left>"]
3320 ["Insert Column" org-shiftmetaright
:active
(org-at-table-p) :keys
"M-S-<right>"])
3322 ["Move Row Up" org-metaup
:active
(org-at-table-p) :keys
"M-<up>"]
3323 ["Move Row Down" org-metadown
:active
(org-at-table-p) :keys
"M-<down>"]
3324 ["Delete Row" org-shiftmetaup
:active
(org-at-table-p) :keys
"M-S-<up>"]
3325 ["Insert Row" org-shiftmetadown
:active
(org-at-table-p) :keys
"M-S-<down>"]
3326 ["Sort lines in region" org-table-sort-lines
:active
(org-at-table-p) :keys
"C-c ^"]
3328 ["Insert Hline" org-table-insert-hline
:active
(org-at-table-p) :keys
"C-c -"])
3330 ["Copy Rectangle" org-copy-special
:active
(org-at-table-p)]
3331 ["Cut Rectangle" org-cut-special
:active
(org-at-table-p)]
3332 ["Paste Rectangle" org-paste-special
:active
(org-at-table-p)]
3333 ["Fill Rectangle" org-table-wrap-region
:active
(org-at-table-p)])
3336 ["Insert table template" orgtbl-insert-radio-table
3337 (assq major-mode orgtbl-radio-table-templates
)]
3338 ["Comment/uncomment table" orgtbl-toggle-comment t
])
3340 ["Set Column Formula" org-table-eval-formula
:active
(org-at-table-p) :keys
"C-c ="]
3341 ["Set Field Formula" (org-table-eval-formula '(4)) :active
(org-at-table-p) :keys
"C-u C-c ="]
3342 ["Edit Formulas" org-table-edit-formulas
:active
(org-at-table-p) :keys
"C-c '"]
3343 ["Recalculate line" org-table-recalculate
:active
(org-at-table-p) :keys
"C-c *"]
3344 ["Recalculate all" (org-table-recalculate '(4)) :active
(org-at-table-p) :keys
"C-u C-c *"]
3345 ["Iterate all" (org-table-recalculate '(16)) :active
(org-at-table-p) :keys
"C-u C-u C-c *"]
3346 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks
:active
(org-at-table-p) :keys
"C-c #"]
3347 ["Sum Column/Rectangle" org-table-sum
3348 :active
(or (org-at-table-p) (org-region-active-p)) :keys
"C-c +"]
3349 ["Which Column?" org-table-current-column
:active
(org-at-table-p) :keys
"C-c ?"]
3351 org-table-toggle-formula-debugger
:active
(org-at-table-p)
3353 :style toggle
:selected org-table-formula-debug
]
3354 ["Show Col/Row Numbers"
3355 org-table-toggle-coordinate-overlays
:active
(org-at-table-p)
3357 :style toggle
:selected org-table-overlay-coordinates
]
3361 (defun orgtbl-ctrl-c-ctrl-c (arg)
3362 "If the cursor is inside a table, realign the table.
3363 It it is a table to be sent away to a receiver, do it.
3364 With prefix arg, also recompute table."
3366 (let ((pos (point)) action
)
3368 (beginning-of-line 1)
3369 (setq action
(cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
3370 ((looking-at "[ \t]*|") pos
)
3371 ((looking-at "#\\+TBLFM:") 'recalc
))))
3375 (org-table-maybe-eval-formula)
3377 (call-interactively 'org-table-recalculate
)
3378 (org-table-maybe-recalculate-line))
3379 (call-interactively 'org-table-align
)
3380 (orgtbl-send-table 'maybe
))
3381 ((eq action
'recalc
)
3383 (beginning-of-line 1)
3384 (skip-chars-backward " \r\n\t")
3385 (if (org-at-table-p)
3386 (org-call-with-arg 'org-table-recalculate t
))))
3387 (t (let (orgtbl-mode)
3388 (call-interactively (key-binding "\C-c\C-c")))))))
3390 (defun orgtbl-tab (arg)
3391 "Justification and field motion for `orgtbl-mode'."
3393 (if arg
(org-table-edit-field t
)
3394 (org-table-justify-field-maybe)
3395 (org-table-next-field)))
3397 (defun orgtbl-ret ()
3398 "Justification and field motion for `orgtbl-mode'."
3400 (org-table-justify-field-maybe)
3401 (org-table-next-row))
3403 (defun orgtbl-self-insert-command (N)
3404 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
3405 If the cursor is in a table looking at whitespace, the whitespace is
3406 overwritten, and the table is not marked as requiring realignment."
3408 (if (and (org-at-table-p)
3410 (and org-table-auto-blank-field
3411 (member last-command
3412 '(orgtbl-hijacker-command-100
3413 orgtbl-hijacker-command-101
3414 orgtbl-hijacker-command-102
3415 orgtbl-hijacker-command-103
3416 orgtbl-hijacker-command-104
3417 orgtbl-hijacker-command-105
))
3418 (org-table-blank-field))
3421 (looking-at "[^|\n]* +|"))
3422 (let (org-table-may-need-update)
3423 (goto-char (1- (match-end 0)))
3424 (delete-backward-char 1)
3425 (goto-char (match-beginning 0))
3426 (self-insert-command N
))
3427 (setq org-table-may-need-update t
)
3429 (call-interactively (key-binding (vector last-input-event
))))))
3431 (defvar orgtbl-exp-regexp
"^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
3432 "Regular expression matching exponentials as produced by calc.")
3434 (declare-function org-table-clean-before-export
"org-exp" (lines))
3435 (declare-function org-format-org-table-html
"org-exp" (lines &optional splice
))
3436 (defun orgtbl-export (table target
)
3438 (let ((func (intern (concat "orgtbl-to-" (symbol-name target
))))
3439 (lines (org-split-string table
"[ \t]*\n[ \t]*"))
3440 org-table-last-alignment org-table-last-column-widths
3442 (if (not (fboundp func
))
3443 (error "Cannot export orgtbl table to %s" target
))
3444 (setq lines
(org-table-clean-before-export lines
))
3448 (if (string-match org-table-hline-regexp x
)
3450 (org-split-string (org-trim x
) "\\s-*|\\s-*")))
3452 (setq maxcol
(apply 'max
(mapcar (lambda (x) (if (listp x
) (length x
) 0))
3454 (loop for i from
(1- maxcol
) downto
0 do
3455 (setq column
(mapcar (lambda (x) (if (listp x
) (nth i x
) nil
)) table
))
3456 (setq column
(delq nil column
))
3457 (push (apply 'max
(mapcar 'string-width column
)) org-table-last-column-widths
)
3458 (push (> (/ (apply '+ (mapcar (lambda (x) (if (string-match org-table-number-regexp x
) 1 0)) column
)) maxcol
) org-table-number-fraction
) org-table-last-alignment
))
3459 (funcall func table nil
)))
3461 (defun orgtbl-send-table (&optional maybe
)
3462 "Send a tranformed version of this table to the receiver position.
3463 With argument MAYBE, fail quietly if no transformation is defined for
3467 (unless (org-at-table-p) (error "Not at a table"))
3468 ;; when non-interactive, we assume align has just happened.
3469 (when (interactive-p) (org-table-align))
3471 (goto-char (org-table-begin))
3472 (beginning-of-line 0)
3473 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
3476 (error "Don't know how to transform this table."))))
3477 (let* ((name (match-string 1))
3479 (transform (intern (match-string 2)))
3480 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
3481 (skip (plist-get params
:skip
))
3482 (skipcols (plist-get params
:skipcols
))
3483 (txt (buffer-substring-no-properties
3484 (org-table-begin) (org-table-end)))
3485 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
3486 (lines (org-table-clean-before-export lines
))
3487 (i0 (if org-table-clean-did-remove-column
2 1))
3490 (if (string-match org-table-hline-regexp x
)
3492 (org-remove-by-index
3493 (org-split-string (org-trim x
) "\\s-*|\\s-*")
3496 (fun (if (= i0
2) 'cdr
'identity
))
3497 (org-table-last-alignment
3498 (org-remove-by-index (funcall fun org-table-last-alignment
)
3500 (org-table-last-column-widths
3501 (org-remove-by-index (funcall fun org-table-last-column-widths
)
3504 (unless (fboundp transform
)
3505 (error "No such transformation function %s" transform
))
3506 (setq txt
(funcall transform table params
))
3507 ;; Find the insertion place
3509 (goto-char (point-min))
3510 (unless (re-search-forward
3511 (concat "BEGIN RECEIVE ORGTBL +" name
"\\([ \t]\\|$\\)") nil t
)
3512 (error "Don't know where to insert translated table"))
3513 (goto-char (match-beginning 0))
3514 (beginning-of-line 2)
3516 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name
) nil t
)
3517 (error "Cannot find end of insertion region"))
3518 (beginning-of-line 1)
3519 (delete-region beg
(point))
3522 (message "Table converted and installed at receiver location"))))
3524 (defun org-remove-by-index (list indices
&optional i0
)
3525 "Remove the elements in LIST with indices in INDICES.
3526 First element has index 0, or I0 if given."
3529 (if (integerp indices
) (setq indices
(list indices
)))
3530 (setq i0
(1- (or i0
0)))
3531 (delq :rm
(mapcar (lambda (x)
3533 (if (memq i0 indices
) :rm x
))
3536 (defun orgtbl-toggle-comment ()
3537 "Comment or uncomment the orgtbl at point."
3539 (let* ((re1 (concat "^" (regexp-quote comment-start
) orgtbl-line-start-regexp
))
3540 (re2 (concat "^" orgtbl-line-start-regexp
))
3541 (commented (save-excursion (beginning-of-line 1)
3542 (cond ((looking-at re1
) t
)
3543 ((looking-at re2
) nil
)
3544 (t (error "Not at an org table")))))
3545 (re (if commented re1 re2
))
3548 (beginning-of-line 1)
3549 (while (looking-at re
) (beginning-of-line 0))
3550 (beginning-of-line 2)
3552 (while (looking-at re
) (beginning-of-line 2))
3554 (comment-region beg end
(if commented
'(4) nil
))))
3556 (defun orgtbl-insert-radio-table ()
3557 "Insert a radio table template appropriate for this major mode."
3559 (let* ((e (assq major-mode orgtbl-radio-table-templates
))
3562 (unless e
(error "No radio table setup defined for %s" major-mode
))
3563 (setq name
(read-string "Table name: "))
3564 (while (string-match "%n" txt
)
3565 (setq txt
(replace-match name t t txt
)))
3566 (or (bolp) (insert "\n"))
3571 (defun org-get-param (params header i sym
&optional hsym
)
3572 "Get parameter value for symbol SYM.
3573 If this is a header line, actually get the value for the symbol with an
3574 additional \"h\" inserted after the colon.
3575 If the value is a protperty list, get the element for the current column.
3576 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
3577 (let ((val (plist-get params sym
)))
3578 (and hsym header
(setq val
(or (plist-get params hsym
) val
)))
3579 (if (consp val
) (plist-get val i
) val
)))
3581 (defun orgtbl-to-generic (table params
)
3582 "Convert the orgtbl-mode TABLE to some other format.
3583 This generic routine can be used for many standard cases.
3584 TABLE is a list, each entry either the symbol `hline' for a horizontal
3585 separator line, or a list of fields for that line.
3586 PARAMS is a property list of parameters that can influence the conversion.
3587 For the generic converter, some parameters are obligatory: You need to
3588 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
3589 :splice, you must have :tstart and :tend.
3591 Valid parameters are
3593 :tstart String to start the table. Ignored when :splice is t.
3594 :tend String to end the table. Ignored when :splice is t.
3596 :splice When set to t, return only table body lines, don't wrap
3597 them into :tstart and :tend. Default is nil.
3599 :hline String to be inserted on horizontal separation lines.
3600 May be nil to ignore hlines.
3602 :lstart String to start a new table line.
3603 :lend String to end a table line
3604 :sep Separator between two fields
3605 :lfmt Format for entire line, with enough %s to capture all fields.
3606 If this is present, :lstart, :lend, and :sep are ignored.
3607 :fmt A format to be used to wrap the field, should contain
3608 %s for the original field value. For example, to wrap
3609 everything in dollars, you could use :fmt \"$%s$\".
3610 This may also be a property list with column numbers and
3611 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
3613 :hlstart :hlend :hlsep :hlfmt :hfmt
3614 Same as above, specific for the header lines in the table.
3615 All lines before the first hline are treated as header.
3616 If any of these is not present, the data line value is used.
3618 :efmt Use this format to print numbers with exponentials.
3619 The format should have %s twice for inserting mantissa
3620 and exponent, for example \"%s\\\\times10^{%s}\". This
3621 may also be a property list with column numbers and
3622 formats. :fmt will still be applied after :efmt.
3624 In addition to this, the parameters :skip and :skipcols are always handled
3625 directly by `orgtbl-send-table'. See manual."
3628 (splicep (plist-get p
:splice
))
3629 (hline (plist-get p
:hline
))
3630 rtn line i fm efm lfmt h
)
3632 ;; Do we have a header?
3633 (if (and (not splicep
) (listp (car table
)) (memq 'hline table
))
3638 (push (or (plist-get p
:tstart
) "ERROR: no :tstart") rtn
))
3640 ;; Now loop over all lines
3641 (while (setq line
(pop table
))
3642 (if (eq line
'hline
)
3643 ;; A horizontal separator line
3644 (progn (if hline
(push hline rtn
))
3645 (setq h nil
)) ; no longer in header
3646 ;; A normal line. Convert the fields, push line onto the result list
3652 fm
(org-get-param p h i
:fmt
:hfmt
)
3653 efm
(org-get-param p h i
:efmt
))
3654 (if (and efm
(string-match orgtbl-exp-regexp f
))
3656 efm
(match-string 1 f
) (match-string 2 f
))))
3657 (if fm
(setq f
(format fm f
)))
3660 (if (setq lfmt
(org-get-param p h i
:lfmt
:hlfmt
))
3661 (push (apply 'format lfmt line
) rtn
)
3663 (org-get-param p h i
:lstart
:hlstart
)
3664 (mapconcat 'identity line
(org-get-param p h i
:sep
:hsep
))
3665 (org-get-param p h i
:lend
:hlend
))
3669 (push (or (plist-get p
:tend
) "ERROR: no :tend") rtn
))
3671 (mapconcat 'identity
(nreverse rtn
) "\n")))
3673 (defun orgtbl-to-latex (table params
)
3674 "Convert the orgtbl-mode TABLE to LaTeX.
3675 TABLE is a list, each entry either the symbol `hline' for a horizontal
3676 separator line, or a list of fields for that line.
3677 PARAMS is a property list of parameters that can influence the conversion.
3678 Supports all parameters from `orgtbl-to-generic'. Most important for
3681 :splice When set to t, return only table body lines, don't wrap
3682 them into a tabular environment. Default is nil.
3684 :fmt A format to be used to wrap the field, should contain %s for the
3685 original field value. For example, to wrap everything in dollars,
3686 use :fmt \"$%s$\". This may also be a property list with column
3687 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
3689 :efmt Format for transforming numbers with exponentials. The format
3690 should have %s twice for inserting mantissa and exponent, for
3691 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
3692 This may also be a property list with column numbers and formats.
3694 The general parameters :skip and :skipcols have already been applied when
3695 this function is called."
3696 (let* ((alignment (mapconcat (lambda (x) (if x
"r" "l"))
3697 org-table-last-alignment
""))
3700 :tstart
(concat "\\begin{tabular}{" alignment
"}")
3701 :tend
"\\end{tabular}"
3702 :lstart
"" :lend
" \\\\" :sep
" & "
3703 :efmt
"%s\\,(%s)" :hline
"\\hline")))
3704 (orgtbl-to-generic table
(org-combine-plists params2 params
))))
3706 (defun orgtbl-to-html (table params
)
3707 "Convert the orgtbl-mode TABLE to LaTeX.
3708 TABLE is a list, each entry either the symbol `hline' for a horizontal
3709 separator line, or a list of fields for that line.
3710 PARAMS is a property list of parameters that can influence the conversion.
3711 Currently this function recognizes the following parameters:
3713 :splice When set to t, return only table body lines, don't wrap
3714 them into a <table> environment. Default is nil.
3716 The general parameters :skip and :skipcols have already been applied when
3717 this function is called. The function does *not* use `orgtbl-to-generic',
3718 so you cannot specify parameters for it."
3719 (let* ((splicep (plist-get params
:splice
))
3721 ;; Just call the formatter we already have
3722 ;; We need to make text lines for it, so put the fields back together.
3723 (setq html
(org-format-org-table-html
3728 (concat "| " (mapconcat 'identity x
" | ") " |")))
3731 (if (string-match "\n+\\'" html
)
3732 (setq html
(replace-match "" t t html
)))
3735 (defun orgtbl-to-texinfo (table params
)
3736 "Convert the orgtbl-mode TABLE to TeXInfo.
3737 TABLE is a list, each entry either the symbol `hline' for a horizontal
3738 separator line, or a list of fields for that line.
3739 PARAMS is a property list of parameters that can influence the conversion.
3740 Supports all parameters from `orgtbl-to-generic'. Most important for
3743 :splice nil/t When set to t, return only table body lines, don't wrap
3744 them into a multitable environment. Default is nil.
3746 :fmt fmt A format to be used to wrap the field, should contain
3747 %s for the original field value. For example, to wrap
3748 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
3749 This may also be a property list with column numbers and
3750 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
3752 :cf \"f1 f2..\" The column fractions for the table. By default these
3753 are computed automatically from the width of the columns
3756 The general parameters :skip and :skipcols have already been applied when
3757 this function is called."
3758 (let* ((total (float (apply '+ org-table-last-column-widths
)))
3759 (colfrac (or (plist-get params
:cf
)
3761 (lambda (x) (format "%.3f" (/ (float x
) total
)))
3762 org-table-last-column-widths
" ")))
3765 :tstart
(concat "@multitable @columnfractions " colfrac
)
3766 :tend
"@end multitable"
3767 :lstart
"@item " :lend
"" :sep
" @tab "
3768 :hlstart
"@headitem ")))
3769 (orgtbl-to-generic table
(org-combine-plists params2 params
))))
3771 (provide 'org-table
)
3773 ;;; org-table.el ends here