1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004-2011 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 of the License, or
15 ;; (at your option) any later version.
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. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;; This file contains the table editor and spreadsheet for Org-mode.
30 ;; Watch out: Here we are talking about two different kind of tables.
31 ;; Most of the code is for the tables created with the Org-mode table editor.
32 ;; Sometimes, we talk about tables created and edited with the table.el
33 ;; Emacs package. We call the former org-type tables, and the latter
34 ;; table.el-type tables.
42 (declare-function org-table-clean-before-export
"org-exp"
43 (lines &optional maybe-quoted
))
44 (declare-function org-format-org-table-html
"org-html" (lines &optional splice
))
45 (defvar orgtbl-mode
) ; defined below
46 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
47 (defvar org-export-html-table-tag
) ; defined in org-exp.el
48 (defvar constants-unit-system
)
50 (defvar orgtbl-after-send-table-hook nil
51 "Hook for functions attaching to `C-c C-c', if the table is sent.
52 This can be used to add additional functionality after the table is sent
53 to the receiver position, othewise, if table is not sent, the functions
56 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
57 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
58 In the optimized version, the table editor takes over all simple keys that
59 normally just insert a character. In tables, the characters are inserted
60 in a way to minimize disturbing the table structure (i.e. in overwrite mode
61 for empty fields). Outside tables, the correct binding of the keys is
64 The default for this option is t if the optimized version is also used in
65 Org-mode. See the variable `org-enable-table-editor' for details. Changing
66 this variable requires a restart of Emacs to become effective."
70 (defcustom orgtbl-radio-table-templates
71 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
72 % END RECEIVE ORGTBL %n
74 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
77 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
78 @c END RECEIVE ORGTBL %n
80 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
83 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
84 <!-- END RECEIVE ORGTBL %n -->
86 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
89 "Templates for radio tables in different major modes.
90 All occurrences of %n in a template will be replaced with the name of the
91 table, obtained by prompting the user."
94 (list (symbol :tag
"Major mode")
95 (string :tag
"Format"))))
97 (defgroup org-table-settings nil
98 "Settings for tables in Org-mode."
99 :tag
"Org Table Settings"
102 (defcustom org-table-default-size
"5x2"
103 "The default size for newly created tables, Columns x Rows."
104 :group
'org-table-settings
107 (defcustom org-table-number-regexp
108 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
109 "Regular expression for recognizing numbers in table columns.
110 If a table column contains mostly numbers, it will be aligned to the
111 right. If not, it will be aligned to the left.
113 The default value of this option is a regular expression which allows
114 anything which looks remotely like a number as used in scientific
115 context. For example, all of the following will be considered a
117 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
119 Other options offered by the customize interface are more restrictive."
120 :group
'org-table-settings
122 (const :tag
"Positive Integers"
124 (const :tag
"Integers"
126 (const :tag
"Floating Point Numbers"
127 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
128 (const :tag
"Floating Point Number or Integer"
129 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
130 (const :tag
"Exponential, Floating point, Integer"
131 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
132 (const :tag
"Very General Number-Like, including hex"
133 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
134 (string :tag
"Regexp:")))
136 (defcustom org-table-number-fraction
0.5
137 "Fraction of numbers in a column required to make the column align right.
138 In a column all non-white fields are considered. If at least this
139 fraction of fields is matched by `org-table-number-fraction',
140 alignment to the right border applies."
141 :group
'org-table-settings
144 (defgroup org-table-editing nil
145 "Behavior of tables during editing in Org-mode."
146 :tag
"Org Table Editing"
149 (defcustom org-table-automatic-realign t
150 "Non-nil means automatically re-align table when pressing TAB or RETURN.
151 When nil, aligning is only done with \\[org-table-align], or after column
153 :group
'org-table-editing
156 (defcustom org-table-auto-blank-field t
157 "Non-nil means automatically blank table field when starting to type into it.
158 This only happens when typing immediately after a field motion
159 command (TAB, S-TAB or RET).
160 Only relevant when `org-enable-table-editor' is equal to `optimized'."
161 :group
'org-table-editing
164 (defcustom org-table-tab-jumps-over-hlines t
165 "Non-nil means tab in the last column of a table with jump over a hline.
166 If a horizontal separator line is following the current line,
167 `org-table-next-field' can either create a new row before that line, or jump
168 over the line. When this option is nil, a new line will be created before
170 :group
'org-table-editing
173 (defgroup org-table-calculation nil
174 "Options concerning tables in Org-mode."
175 :tag
"Org Table Calculation"
178 (defcustom org-table-use-standard-references t
179 "Should org-mode work with table references like B3 instead of @3$2?
182 from accept as input, do not present for editing
183 t: accept as input and present for editing"
184 :group
'org-table-calculation
186 (const :tag
"Never, don't even check user input for them" nil
)
187 (const :tag
"Always, both as user input, and when editing" t
)
188 (const :tag
"Convert user input, don't offer during editing" 'from
)))
190 (defcustom org-table-copy-increment t
191 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
192 :group
'org-table-calculation
195 (defcustom org-calc-default-modes
196 '(calc-internal-prec 12
197 calc-float-format
(float 8)
200 calc-symbolic-mode nil
201 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
202 calc-display-working-message t
204 "List with Calc mode settings for use in `calc-eval' for table formulas.
205 The list must contain alternating symbols (Calc modes variables and values).
206 Don't remove any of the default settings, just change the values. Org-mode
207 relies on the variables to be present in the list."
208 :group
'org-table-calculation
211 (defcustom org-table-formula-evaluate-inline t
212 "Non-nil means TAB and RET evaluate a formula in current table field.
213 If the current field starts with an equal sign, it is assumed to be a formula
214 which should be evaluated as described in the manual and in the documentation
215 string of the command `org-table-eval-formula'. This feature requires the
217 When this variable is nil, formula calculation is only available through
218 the command \\[org-table-eval-formula]."
219 :group
'org-table-calculation
222 (defcustom org-table-formula-use-constants t
223 "Non-nil means interpret constants in formulas in tables.
224 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
225 by the value given in `org-table-formula-constants', or by a value obtained
226 from the `constants.el' package."
227 :group
'org-table-calculation
230 (defcustom org-table-formula-constants nil
231 "Alist with constant names and values, for use in table formulas.
232 The car of each element is a name of a constant, without the `$' before it.
233 The cdr is the value as a string. For example, if you'd like to use the
234 speed of light in a formula, you would configure
236 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
238 and then use it in an equation like `$1*$c'.
240 Constants can also be defined on a per-file basis using a line like
242 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
243 :group
'org-table-calculation
245 (cons (string :tag
"name")
246 (string :tag
"value"))))
248 (defcustom org-table-allow-automatic-line-recalculation t
249 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
250 Automatically means when TAB or RET or C-c C-c are pressed in the line."
251 :group
'org-table-calculation
254 (defcustom org-table-error-on-row-ref-crossing-hline t
255 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
259 (defcustom org-table-relative-ref-may-cross-hline t
260 "Non-nil means relative formula references may cross hlines.
261 Here are the allowed values:
263 nil Relative references may not cross hlines. They will reference the
264 field next to the hline instead. Coming from below, the reference
265 will be to the field below the hline. Coming from above, it will be
267 t Relative references may cross hlines.
268 error An attempt to cross a hline will throw an error.
270 It is probably good to never set this variable to nil, for the sake of
271 portability of tables."
272 :group
'org-table-calculation
274 (const :tag
"Allow to cross" t
)
275 (const :tag
"Stick to hline" nil
)
276 (const :tag
"Error on attempt to cross" error
)))
278 (defgroup org-table-import-export nil
279 "Options concerning table import and export in Org-mode."
280 :tag
"Org Table Import Export"
283 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
284 "Default export parameters for `org-table-export'.
285 These can be overridden for a specific table by setting the
286 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
287 radio tables for the different export transformations and
288 available parameters."
289 :group
'org-table-import-export
292 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
293 "Detects a table line marked for automatic recalculation.")
294 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
295 "Detects a table line marked for automatic recalculation.")
296 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
297 "Detects a table line marked for automatic recalculation.")
298 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
299 "Searching from within a table (any type) this finds the first line outside the table.")
300 (defvar org-table-last-highlighted-reference nil
)
301 (defvar org-table-formula-history nil
)
303 (defvar org-table-column-names nil
304 "Alist with column names, derived from the `!' line.")
305 (defvar org-table-column-name-regexp nil
306 "Regular expression matching the current column names.")
307 (defvar org-table-local-parameters nil
308 "Alist with parameter names, derived from the `$' line.")
309 (defvar org-table-named-field-locations nil
310 "Alist with locations of named fields.")
312 (defvar org-table-current-line-types nil
313 "Table row types, non-nil only for the duration of a command.")
314 (defvar org-table-current-begin-line nil
315 "Table begin line, non-nil only for the duration of a command.")
316 (defvar org-table-current-begin-pos nil
317 "Table begin position, non-nil only for the duration of a command.")
318 (defvar org-table-dlines nil
319 "Vector of data line line numbers in the current table.")
320 (defvar org-table-hlines nil
321 "Vector of hline line numbers in the current table.")
323 (defconst org-table-range-regexp
324 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
326 "Regular expression for matching ranges in formulas.")
328 (defconst org-table-range-regexp2
330 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
332 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
333 "Match a range for reference display.")
335 (defun org-table-colgroup-line-p (line)
336 "Is this a table line colgroup information?"
338 (and (string-match "[<>]\\|&[lg]t;" line
)
339 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
345 (not (member s
'("" "<" ">" "<>" "<" ">" "<>"))))
346 (org-split-string (match-string 1 line
) "[ \t]*|[ \t]*")))))))
348 (defun org-table-cookie-line-p (line)
349 "Is this a table line with only alignment/width cookies?"
351 (and (string-match "[<>]\\|&[lg]t;" line
)
353 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line
)
354 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line
))
355 (not (delq nil
(mapcar
357 (not (or (equal s
"")
359 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s
)
361 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'"
363 (org-split-string (match-string 1 line
)
364 "[ \t]*|[ \t]*")))))))
366 (defconst org-table-translate-regexp
367 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
368 "Match a reference that needs translation, for reference display.")
370 (defun org-table-create-with-table.el
()
371 "Use the table.el package to insert a new table.
372 If there is already a table at point, convert between Org-mode tables
373 and table.el tables."
378 (if (y-or-n-p "Convert table to Org-mode table? ")
379 (org-table-convert)))
381 (when (y-or-n-p "Convert table to table.el table? ")
383 (org-table-convert)))
384 (t (call-interactively 'table-insert
))))
386 (defun org-table-create-or-convert-from-region (arg)
387 "Convert region to table, or create an empty table.
388 If there is an active region, convert it to a table, using the function
389 `org-table-convert-region'. See the documentation of that function
390 to learn how the prefix argument is interpreted to determine the field
392 If there is no such region, create an empty table with `org-table-create'."
394 (if (org-region-active-p)
395 (org-table-convert-region (region-beginning) (region-end) arg
)
396 (org-table-create arg
)))
398 (defun org-table-create (&optional size
)
399 "Query for a size and insert a table skeleton.
400 SIZE is a string Columns x Rows like for example \"3x2\"."
403 (setq size
(read-string
404 (concat "Table size Columns x Rows [e.g. "
405 org-table-default-size
"]: ")
406 "" nil org-table-default-size
)))
409 (indent (make-string (current-column) ?\
))
410 (split (org-split-string size
" *x *"))
411 (rows (string-to-number (nth 1 split
)))
412 (columns (string-to-number (car split
)))
413 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
415 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
416 (point-at-bol) (point)))
417 (beginning-of-line 1)
419 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
420 (dotimes (i rows
) (insert line
))
423 ;; Insert a hline after the first row.
430 (defun org-table-convert-region (beg0 end0
&optional separator
)
431 "Convert region to a table.
432 The region goes from BEG0 to END0, but these borders will be moved
433 slightly, to make sure a beginning of line in the first line is included.
435 SEPARATOR specifies the field separator in the lines. It can have the
438 '(4) Use the comma as a field separator
439 '(16) Use a TAB as field separator
440 integer When a number, use that many spaces as field separator
441 nil When nil, the command tries to be smart and figure out the
442 separator in the following way:
443 - when each line contains a TAB, assume TAB-separated material
444 - when each line contains a comma, assume CSV material
445 - else, assume one or more SPACE characters as separator."
447 (let* ((beg (min beg0 end0
))
448 (end (max beg0 end0
))
451 (beginning-of-line 1)
452 (setq beg
(move-marker (make-marker) (point)))
454 (if (bolp) (backward-char 1) (end-of-line 1))
455 (setq end
(move-marker (make-marker) (point)))
456 ;; Get the right field separator
461 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
462 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
465 (if (equal separator
'(4))
466 (while (< (point) end
)
467 ;; parse the csv stuff
469 ((looking-at "^") (insert "| "))
470 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
471 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
472 (replace-match "\\1")
473 (if (looking-at "\"") (insert "\"")))
474 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
475 ((looking-at "[ \t]*,") (replace-match " | "))
476 (t (beginning-of-line 2))))
478 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
479 ((equal separator
'(16)) "^\\|\t")
480 ((integerp separator
)
481 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
))
482 (t (error "This should not happen"))))
483 (while (re-search-forward re end t
)
484 (replace-match "| " t t
)))
488 (defun org-table-import (file arg
)
489 "Import FILE as a table.
490 The file is assumed to be tab-separated. Such files can be produced by most
491 spreadsheet and database applications. If no tabs (at least one per line)
492 are found, lines will be split on whitespace into fields."
494 (or (bolp) (newline))
497 (insert-file-contents file
)
498 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
501 (defvar org-table-last-alignment
)
502 (defvar org-table-last-column-widths
)
503 (defun org-table-export (&optional file format
)
504 "Export table to a file, with configurable format.
505 Such a file can be imported into a spreadsheet program like Excel.
506 FILE can be the output file name. If not given, it will be taken from
507 a TABLE_EXPORT_FILE property in the current entry or higher up in the
508 hierarchy, or the user will be prompted for a file name.
509 FORMAT can be an export format, of the same kind as it used when
510 `orgtbl-mode' sends a table in a different format. The default format can
511 be found in the variable `org-table-export-default-format', but the function
512 first checks if there is an export format specified in a TABLE_EXPORT_FORMAT
513 property, locally or anywhere up in the hierarchy."
515 (unless (org-at-table-p)
516 (error "No table at point"))
518 (org-table-align) ;; make sure we have everything we need
519 (let* ((beg (org-table-begin))
520 (end (org-table-end))
521 (txt (buffer-substring-no-properties beg end
))
524 (org-entry-get beg
"TABLE_EXPORT_FILE" t
)
528 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)
532 (setq file
(read-file-name "Export table to: "))
533 (unless (or (not (file-exists-p file
))
534 (y-or-n-p (format "Overwrite file %s? " file
)))
536 (if (file-directory-p file
)
537 (error "This is a directory path, not a file"))
538 (if (and (buffer-file-name)
539 (equal (file-truename file
)
540 (file-truename (buffer-file-name))))
541 (error "Please specify a file name that is different from current"))
543 (setq deffmt-readable org-table-export-default-format
)
544 (while (string-match "\t" deffmt-readable
)
545 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
546 (while (string-match "\n" deffmt-readable
)
547 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
548 (setq format
(org-completing-read
550 '("orgtbl-to-tsv" "orgtbl-to-csv"
551 "orgtbl-to-latex" "orgtbl-to-html"
552 "orgtbl-to-generic" "orgtbl-to-texinfo"
553 "orgtbl-to-orgtbl") nil nil
555 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
556 (let* ((transform (intern (match-string 1 format
)))
557 (params (if (match-end 2)
558 (read (concat "(" (match-string 2 format
) ")"))))
559 (skip (plist-get params
:skip
))
560 (skipcols (plist-get params
:skipcols
))
561 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
562 (lines (org-table-clean-before-export lines
))
563 (i0 (if org-table-clean-did-remove-column
2 1))
566 (if (string-match org-table-hline-regexp x
)
569 (org-split-string (org-trim x
) "\\s-*|\\s-*")
572 (fun (if (= i0
2) 'cdr
'identity
))
573 (org-table-last-alignment
574 (org-remove-by-index (funcall fun org-table-last-alignment
)
576 (org-table-last-column-widths
577 (org-remove-by-index (funcall fun org-table-last-column-widths
)
580 (unless (fboundp transform
)
581 (error "No such transformation function %s" transform
))
582 (setq txt
(funcall transform table params
))
584 (with-current-buffer (find-file-noselect file
)
585 (setq buf
(current-buffer))
591 (message "Export done."))
592 (error "TABLE_EXPORT_FORMAT invalid"))))
594 (defvar org-table-aligned-begin-marker
(make-marker)
595 "Marker at the beginning of the table last aligned.
596 Used to check if cursor still is in that table, to minimize realignment.")
597 (defvar org-table-aligned-end-marker
(make-marker)
598 "Marker at the end of the table last aligned.
599 Used to check if cursor still is in that table, to minimize realignment.")
600 (defvar org-table-last-alignment nil
601 "List of flags for flushright alignment, from the last re-alignment.
602 This is being used to correctly align a single field after TAB or RET.")
603 (defvar org-table-last-column-widths nil
604 "List of max width of fields in each column.
605 This is being used to correctly align a single field after TAB or RET.")
606 (defvar org-table-formula-debug nil
607 "Non-nil means debug table formulas.
608 When nil, simply write \"#ERROR\" in corrupted fields.")
609 (make-variable-buffer-local 'org-table-formula-debug
)
610 (defvar org-table-overlay-coordinates nil
611 "Overlay coordinates after each align of a table.")
612 (make-variable-buffer-local 'org-table-overlay-coordinates
)
614 (defvar org-last-recalc-line nil
)
615 (defvar org-table-do-narrow t
) ; for dynamic scoping
616 (defconst org-narrow-column-arrow
"=>"
617 "Used as display property in narrowed table columns.")
619 (defun org-table-align ()
620 "Align the table at point by aligning all vertical bars."
624 (beg (org-table-begin))
625 (end (org-table-end))
626 ;; Current cursor position
627 (linepos (org-current-line))
628 (colpos (org-table-current-column))
629 (winstart (window-start))
630 (winstartline (org-current-line (min winstart
(1- (point-max)))))
631 lines
(new "") lengths l typenums ty fields maxfields i
639 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
641 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
642 emptystrings links dates emph raise narrow
643 falign falign1 fmax f1 len c e space
)
645 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
646 ;; Check if we have links or dates
648 (setq links
(re-search-forward org-bracket-link-regexp end t
))
650 (setq emph
(and org-hide-emphasis-markers
651 (re-search-forward org-emph-re end t
)))
653 (setq raise
(and org-use-sub-superscripts
654 (re-search-forward org-match-substring-regexp end t
)))
656 (setq dates
(and org-display-custom-times
657 (re-search-forward org-ts-regexp-both end t
)))
658 ;; Make sure the link properties are right
659 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
660 ;; Make sure the date properties are right
661 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
662 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
663 (when raise
(goto-char beg
) (while (org-raise-scripts end
)))
665 ;; Check if we are narrowing any columns
667 (setq narrow
(and org-table-do-narrow
668 org-format-transports-properties-p
669 (re-search-forward "<[lrc]?[0-9]+>" end t
)))
671 (setq falign
(re-search-forward "<[lrc][0-9]*>" end t
))
674 (setq lines
(org-split-string
675 (buffer-substring beg end
) "\n"))
676 ;; Store the indentation of the first line
677 (if (string-match "^ *" (car lines
))
678 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
679 ;; Mark the hlines by setting the corresponding element to nil
680 ;; At the same time, we remove trailing space.
681 (setq lines
(mapcar (lambda (l)
682 (if (string-match "^ *|-" l
)
684 (if (string-match "[ \t]+$" l
)
685 (substring l
0 (match-beginning 0))
688 ;; Get the data fields by splitting the lines.
691 (org-split-string l
" *| *"))
692 (delq nil
(copy-sequence lines
))))
693 ;; How many fields in the longest line?
695 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
697 (kill-region beg end
)
698 (org-table-create org-table-default-size
)
699 (error "Empty table - created default table")))
700 ;; A list of empty strings to fill any short rows on output
701 (setq emptystrings
(make-list maxfields
""))
702 ;; Check for special formatting.
704 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
705 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
706 ;; Check if there is an explicit width specified
708 (when (or narrow falign
)
709 (setq c column fmax nil falign1 nil
)
712 (when (and (stringp e
) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e
))
713 (if (match-end 1) (setq falign1
(match-string 1 e
)))
714 (if (and org-table-do-narrow
(match-end 2))
715 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
716 ;; Find fields that are wider than fmax, and shorten them
718 (loop for xx in column do
719 (when (and (stringp xx
)
720 (> (org-string-width xx
) fmax
))
721 (org-add-props xx nil
723 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
724 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
726 (error "Cannot narrow field starting with wide link \"%s\""
727 (match-string 0 xx
)))
728 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
729 (add-text-properties (- f1
2) f1
730 (list 'display org-narrow-column-arrow
)
732 ;; Get the maximum width for each column
733 (push (apply 'max
(or fmax
1) 1 (mapcar 'org-string-width column
))
735 ;; Get the fraction of numbers, to decide about alignment of the column
737 (push (equal (downcase falign1
) "r") typenums
)
738 (setq cnt
0 frac
0.0)
739 (loop for x in column do
742 (setq frac
( / (+ (* frac cnt
)
743 (if (string-match org-table-number-regexp x
) 1 0))
744 (setq cnt
(1+ cnt
))))))
745 (push (>= frac org-table-number-fraction
) typenums
)))
746 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
748 ;; Store the alignment of this table, for later editing of single fields
749 (setq org-table-last-alignment typenums
750 org-table-last-column-widths lengths
)
752 ;; With invisible characters, `format' does not get the field width right
753 ;; So we need to make these fields wide by hand.
754 (when (or links emph raise
)
755 (loop for i from
0 upto
(1- maxfields
) do
756 (setq len
(nth i lengths
))
757 (loop for j from
0 upto
(1- (length fields
)) do
758 (setq c
(nthcdr i
(car (nthcdr j fields
))))
759 (if (and (stringp (car c
))
760 (or (text-property-any 0 (length (car c
))
761 'invisible
'org-link
(car c
))
762 (text-property-any 0 (length (car c
))
763 'org-dwidth t
(car c
)))
764 (< (org-string-width (car c
)) len
))
766 (setq space
(make-string (- len
(org-string-width (car c
))) ?\
))
767 (setcar c
(if (nth i typenums
)
768 (concat space
(car c
))
769 (concat (car c
) space
))))))))
771 ;; Compute the formats needed for output of the table
772 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
773 (while (setq l
(pop lengths
))
774 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
775 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
776 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
777 (setq rfmt
(concat rfmt
"\n")
778 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
782 (if l
(apply 'format rfmt
783 (append (pop fields
) emptystrings
))
786 (if (equal (char-before) ?
\n)
787 ;; This hack is for org-indent, to force redisplay of the
788 ;; line prefix of the first line. Apparently the redisplay
789 ;; is tied to the newline, which is, I think, a bug.
790 ;; To force this redisplay, we remove and re-insert the
791 ;; newline, so that the redisplay engine thinks it belongs
792 ;; to the changed text.
794 (backward-delete-char 1)
796 (move-marker org-table-aligned-begin-marker
(point))
798 ;; Replace the old one
799 (delete-region (point) end
)
800 (move-marker end nil
)
801 (move-marker org-table-aligned-end-marker
(point))
802 (when (and orgtbl-mode
(not (org-mode-p)))
803 (goto-char org-table-aligned-begin-marker
)
804 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
805 ;; Try to move to the old location
806 (org-goto-line winstartline
)
807 (setq winstart
(point-at-bol))
808 (org-goto-line linepos
)
809 (set-window-start (selected-window) winstart
'noforce
)
810 (org-table-goto-column colpos
)
811 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
812 (setq org-table-may-need-update nil
)
815 (defun org-table-begin (&optional table-type
)
816 "Find the beginning of the table and return its position.
817 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
819 (if (not (re-search-backward
820 (if table-type org-table-any-border-regexp
821 org-table-border-regexp
)
823 (progn (goto-char (point-min)) (point))
824 (goto-char (match-beginning 0))
825 (beginning-of-line 2)
828 (defun org-table-end (&optional table-type
)
829 "Find the end of the table and return its position.
830 With argument TABLE-TYPE, go to the end of a table.el-type table."
832 (if (not (re-search-forward
833 (if table-type org-table-any-border-regexp
834 org-table-border-regexp
)
836 (goto-char (point-max))
837 (goto-char (match-beginning 0)))
840 (defun org-table-justify-field-maybe (&optional new
)
841 "Justify the current field, text to left, number to right.
842 Optional argument NEW may specify text to replace the current field content."
844 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
845 ((org-at-table-hline-p))
847 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
849 (< (point) org-table-aligned-begin-marker
)
850 (>= (point) org-table-aligned-end-marker
)))
851 ;; This is not the same table, force a full re-align
852 (setq org-table-may-need-update t
))
853 (t ;; realign the current field, based on previous full realign
854 (let* ((pos (point)) s
855 (col (org-table-current-column))
856 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
859 (skip-chars-backward "^|\n")
860 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
862 (setq s
(match-string 1)
864 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
865 e
(not (= (match-beginning 2) (match-end 2))))
866 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
867 l
(if e
"|" (setq org-table-may-need-update t
) ""))
870 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
871 (setq n
(format f new
))
872 (setq n
(concat new
"|") org-table-may-need-update t
)))
873 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
875 (let (org-table-may-need-update)
876 (replace-match n t t
))))
877 (setq org-table-may-need-update t
))
880 (defun org-table-next-field ()
881 "Go to the next field in the current table, creating new lines as needed.
882 Before doing so, re-align the table if necessary."
884 (org-table-maybe-eval-formula)
885 (org-table-maybe-recalculate-line)
886 (if (and org-table-automatic-realign
887 org-table-may-need-update
)
889 (let ((end (org-table-end)))
890 (if (org-at-table-hline-p)
894 (re-search-forward "|" end
)
895 (if (looking-at "[ \t]*$")
896 (re-search-forward "|" end
))
897 (if (and (looking-at "-")
898 org-table-tab-jumps-over-hlines
899 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
900 (goto-char (match-beginning 1)))
903 (beginning-of-line 0)
904 (org-table-insert-row 'below
))
905 (if (looking-at " ") (forward-char 1))))
907 (org-table-insert-row 'below
)))))
909 (defun org-table-previous-field ()
910 "Go to the previous field in the table.
911 Before doing so, re-align the table if necessary."
913 (org-table-justify-field-maybe)
914 (org-table-maybe-recalculate-line)
915 (if (and org-table-automatic-realign
916 org-table-may-need-update
)
918 (if (org-at-table-hline-p)
922 (re-search-backward "|" (org-table-begin))
923 (re-search-backward "|" (org-table-begin)))
924 (error (error "Cannot move to previous table field")))
925 (while (looking-at "|\\(-\\|[ \t]*$\\)")
926 (re-search-backward "|" (org-table-begin)))
927 (if (looking-at "| ?")
928 (goto-char (match-end 0))))
930 (defun org-table-beginning-of-field (&optional n
)
931 "Move to the end of the current table field.
932 If already at or after the end, move to the end of the next table field.
933 With numeric argument N, move N-1 fields forward first."
938 (org-table-previous-field))
939 (if (not (re-search-backward "|" (point-at-bol 0) t
))
940 (error "No more table fields before the current")
941 (goto-char (match-end 0))
942 (and (looking-at " ") (forward-char 1)))
943 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
945 (defun org-table-end-of-field (&optional n
)
946 "Move to the beginning of the current table field.
947 If already at or before the beginning, move to the beginning of the
949 With numeric argument N, move N-1 fields backward first."
954 (org-table-next-field))
955 (when (re-search-forward "|" (point-at-eol 1) t
)
957 (skip-chars-backward " ")
958 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
960 (if (<= (point) pos
) (org-table-end-of-field 2))))
962 (defun org-table-next-row ()
963 "Go to the next row (same column) in the current table.
964 Before doing so, re-align the table if necessary."
966 (org-table-maybe-eval-formula)
967 (org-table-maybe-recalculate-line)
968 (if (or (looking-at "[ \t]*$")
969 (save-excursion (skip-chars-backward " \t") (bolp)))
971 (if (and org-table-automatic-realign
972 org-table-may-need-update
)
974 (let ((col (org-table-current-column)))
975 (beginning-of-line 2)
976 (if (or (not (org-at-table-p))
977 (org-at-table-hline-p))
979 (beginning-of-line 0)
980 (org-table-insert-row 'below
)))
981 (org-table-goto-column col
)
982 (skip-chars-backward "^|\n\r")
983 (if (looking-at " ") (forward-char 1)))))
985 (defun org-table-copy-down (n)
986 "Copy a field down in the current column.
987 If the field at the cursor is empty, copy into it the content of the nearest
988 non-empty field above. With argument N, use the Nth non-empty field.
989 If the current field is not empty, it is copied down to the next row, and
990 the cursor is moved with it. Therefore, repeating this command causes the
991 column to be filled row-by-row.
992 If the variable `org-table-copy-increment' is non-nil and the field is an
993 integer or a timestamp, it will be incremented while copying. In the case of
994 a timestamp, if the cursor is on the year, change the year. If it is on the
995 month or the day, change that. Point will stay on the current date field
996 in order to easily repeat the interval."
998 (let* ((colpos (org-table-current-column))
999 (col (current-column))
1000 (field (org-table-get-field))
1001 (non-empty (string-match "[^ \t]" field
))
1002 (beg (org-table-begin))
1005 (org-table-check-inside-data-field)
1008 (setq txt
(org-trim field
))
1009 (org-table-next-row)
1010 (org-table-blank-field))
1014 (while (progn (beginning-of-line 1)
1015 (re-search-backward org-table-dataline-regexp
1017 (org-table-goto-column colpos t
)
1018 (if (and (looking-at
1019 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1020 (<= (setq n
(1- n
)) 0))
1021 (throw 'exit
(match-string 1))))))))
1024 (if (and org-table-copy-increment
1025 (not (equal orig-n
0))
1026 (string-match "^[0-9]+$" txt
)
1027 (< (string-to-number txt
) 100000000))
1028 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
1030 (org-move-to-column col
)
1031 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1032 (org-timestamp-up-day)
1033 (org-table-maybe-recalculate-line))
1035 (org-move-to-column col
))
1036 (error "No non-empty field found"))))
1038 (defun org-table-check-inside-data-field ()
1039 "Is point inside a table data field?
1040 I.e. not on a hline or before the first or after the last column?
1041 This actually throws an error, so it aborts the current command."
1042 (if (or (not (org-at-table-p))
1043 (= (org-table-current-column) 0)
1044 (org-at-table-hline-p)
1045 (looking-at "[ \t]*$"))
1046 (error "Not in table data field")))
1048 (defvar org-table-clip nil
1049 "Clipboard for table regions.")
1051 (defun org-table-get (line column
)
1052 "Get the field in table line LINE, column COLUMN.
1053 If LINE is larger than the number of data lines in the table, the function
1054 returns nil. However, if COLUMN is too large, we will simply return an
1056 If LINE is nil, use the current line.
1057 If column is nil, use the current column."
1058 (setq column
(or column
(org-table-current-column)))
1060 (and (or (not line
) (org-table-goto-line line
))
1061 (org-trim (org-table-get-field column
)))))
1063 (defun org-table-put (line column value
&optional align
)
1064 "Put VALUE into line LINE, column COLUMN.
1065 When ALIGN is set, also realign the table."
1066 (setq column
(or column
(org-table-current-column)))
1067 (prog1 (save-excursion
1068 (and (or (not line
) (org-table-goto-line line
))
1069 (progn (org-table-goto-column column nil
'force
) t
)
1070 (org-table-get-field column value
)))
1071 (and align
(org-table-align))))
1073 (defun org-table-current-line ()
1074 "Return the index of the current data line."
1075 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1077 (goto-char (org-table-begin))
1078 (while (and (re-search-forward org-table-dataline-regexp end t
)
1080 (< (point-at-eol) pos
))))
1083 (defun org-table-goto-line (N)
1084 "Go to the Nth data line in the current table.
1085 Return t when the line exists, nil if it does not exist."
1086 (goto-char (org-table-begin))
1087 (let ((end (org-table-end)) (cnt 0))
1088 (while (and (re-search-forward org-table-dataline-regexp end t
)
1089 (< (setq cnt
(1+ cnt
)) N
)))
1092 (defun org-table-blank-field ()
1093 "Blank the current table field or active region."
1095 (org-table-check-inside-data-field)
1096 (if (and (interactive-p) (org-region-active-p))
1097 (let (org-table-clip)
1098 (org-table-cut-region (region-beginning) (region-end)))
1099 (skip-chars-backward "^|")
1101 (if (looking-at "|[^|\n]+")
1102 (let* ((pos (match-beginning 0))
1103 (match (match-string 0))
1104 (len (org-string-width match
)))
1105 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1106 (goto-char (+ 2 pos
))
1107 (substring match
1)))))
1109 (defun org-table-get-field (&optional n replace
)
1110 "Return the value of the field in column N of current row.
1111 N defaults to current field.
1112 If REPLACE is a string, replace field with this value. The return value
1113 is always the old value."
1114 (and n
(org-table-goto-column n
))
1115 (skip-chars-backward "^|\n")
1117 (if (looking-at "|[^|\r\n]*")
1118 (let* ((pos (match-beginning 0))
1119 (val (buffer-substring (1+ pos
) (match-end 0))))
1121 (replace-match (concat "|" replace
) t t
))
1122 (goto-char (min (point-at-eol) (+ 2 pos
)))
1124 (forward-char 1) ""))
1126 (defun org-table-field-info (arg)
1127 "Show info about the current field, and highlight any reference at point."
1129 (org-table-get-specials)
1131 (let* ((pos (point))
1132 (col (org-table-current-column))
1133 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1134 (name (car (rassoc (list (org-current-line) col
)
1135 org-table-named-field-locations
)))
1136 (eql (org-table-get-stored-formulas))
1137 (dline (org-table-current-dline))
1138 (ref (format "@%d$%d" dline col
))
1139 (ref1 (org-table-convert-refs-to-an ref
))
1140 (fequation (or (assoc name eql
) (assoc ref eql
)))
1141 (cequation (assoc (int-to-string col
) eql
))
1142 (eqn (or fequation cequation
)))
1145 (org-table-show-reference 'local
)
1147 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1149 (if cname
(concat " or $" cname
) "")
1151 (if name
(concat " or $" name
) "")
1152 ;; FIXME: formula info not correct if special table line
1154 (concat ", formula: "
1155 (org-table-formula-to-user
1157 (if (string-match "^[$@]"(car eqn
)) "" "$")
1158 (car eqn
) "=" (cdr eqn
))))
1161 (defun org-table-current-column ()
1162 "Find out which column we are in."
1164 (if (interactive-p) (org-table-check-inside-data-field))
1166 (let ((cnt 0) (pos (point)))
1167 (beginning-of-line 1)
1168 (while (search-forward "|" pos t
)
1169 (setq cnt
(1+ cnt
)))
1170 (if (interactive-p) (message "In table column %d" cnt
))
1173 (defun org-table-current-dline ()
1174 "Find out what table data line we are in.
1175 Only data lines count for this."
1177 (if (interactive-p) (org-table-check-inside-data-field))
1179 (let ((cnt 0) (pos (point)))
1180 (goto-char (org-table-begin))
1181 (while (<= (point) pos
)
1182 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1183 (beginning-of-line 2))
1184 (if (interactive-p) (message "This is table line %d" cnt
))
1187 (defun org-table-goto-column (n &optional on-delim force
)
1188 "Move the cursor to the Nth column in the current table line.
1189 With optional argument ON-DELIM, stop with point before the left delimiter
1191 If there are less than N fields, just go to after the last delimiter.
1192 However, when FORCE is non-nil, create new columns if necessary."
1194 (beginning-of-line 1)
1196 (while (and (> (setq n
(1- n
)) -
1)
1197 (or (search-forward "|" (point-at-eol) t
)
1199 (progn (end-of-line 1)
1200 (skip-chars-backward "^|")
1203 (when (and force
(not (looking-at ".*|")))
1204 (save-excursion (end-of-line 1) (insert " | ")))
1207 (if (looking-at " ") (forward-char 1)))))
1209 (defun org-table-insert-column ()
1210 "Insert a new column into the table."
1212 (if (not (org-at-table-p))
1213 (error "Not at a table"))
1214 (org-table-find-dataline)
1215 (let* ((col (max 1 (org-table-current-column)))
1216 (beg (org-table-begin))
1217 (end (org-table-end))
1218 ;; Current cursor position
1219 (linepos (org-current-line))
1222 (while (< (point) end
)
1223 (if (org-at-table-hline-p)
1225 (org-table-goto-column col t
)
1227 (beginning-of-line 2))
1228 (move-marker end nil
)
1229 (org-goto-line linepos
)
1230 (org-table-goto-column colpos
)
1232 (org-table-fix-formulas "$" nil
(1- col
) 1)
1233 (org-table-fix-formulas "$LR" nil
(1- col
) 1)))
1235 (defun org-table-find-dataline ()
1236 "Find a data line in the current table, which is needed for column commands."
1237 (if (and (org-at-table-p)
1238 (not (org-at-table-hline-p)))
1240 (let ((col (current-column))
1241 (end (org-table-end)))
1242 (org-move-to-column col
)
1243 (while (and (< (point) end
)
1244 (or (not (= (current-column) col
))
1245 (org-at-table-hline-p)))
1246 (beginning-of-line 2)
1247 (org-move-to-column col
))
1248 (if (and (org-at-table-p)
1249 (not (org-at-table-hline-p)))
1252 "Please position cursor in a data line for column operations")))))
1254 (defun org-table-delete-column ()
1255 "Delete a column from the table."
1257 (if (not (org-at-table-p))
1258 (error "Not at a table"))
1259 (org-table-find-dataline)
1260 (org-table-check-inside-data-field)
1261 (let* ((col (org-table-current-column))
1262 (beg (org-table-begin))
1263 (end (org-table-end))
1264 ;; Current cursor position
1265 (linepos (org-current-line))
1268 (while (< (point) end
)
1269 (if (org-at-table-hline-p)
1271 (org-table-goto-column col t
)
1272 (and (looking-at "|[^|\n]+|")
1273 (replace-match "|")))
1274 (beginning-of-line 2))
1275 (move-marker end nil
)
1276 (org-goto-line linepos
)
1277 (org-table-goto-column colpos
)
1279 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1281 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1284 (defun org-table-move-column-right ()
1285 "Move column to the right."
1287 (org-table-move-column nil
))
1288 (defun org-table-move-column-left ()
1289 "Move column to the left."
1291 (org-table-move-column 'left
))
1293 (defun org-table-move-column (&optional left
)
1294 "Move the current column to the right. With arg LEFT, move to the left."
1296 (if (not (org-at-table-p))
1297 (error "Not at a table"))
1298 (org-table-find-dataline)
1299 (org-table-check-inside-data-field)
1300 (let* ((col (org-table-current-column))
1301 (col1 (if left
(1- col
) col
))
1302 (beg (org-table-begin))
1303 (end (org-table-end))
1304 ;; Current cursor position
1305 (linepos (org-current-line))
1306 (colpos (if left
(1- col
) (1+ col
))))
1307 (if (and left
(= col
1))
1308 (error "Cannot move column further left"))
1309 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1310 (error "Cannot move column further right"))
1312 (while (< (point) end
)
1313 (if (org-at-table-hline-p)
1315 (org-table-goto-column col1 t
)
1316 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1317 (replace-match "|\\2|\\1|")))
1318 (beginning-of-line 2))
1319 (move-marker end nil
)
1320 (org-goto-line linepos
)
1321 (org-table-goto-column colpos
)
1323 (org-table-fix-formulas
1324 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1325 (cons (number-to-string colpos
) (number-to-string col
))))
1326 (org-table-fix-formulas
1327 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1328 (cons (number-to-string colpos
) (number-to-string col
))))))
1330 (defun org-table-move-row-down ()
1331 "Move table row down."
1333 (org-table-move-row nil
))
1334 (defun org-table-move-row-up ()
1335 "Move table row up."
1337 (org-table-move-row 'up
))
1339 (defun org-table-move-row (&optional up
)
1340 "Move the current table line down. With arg UP, move it up."
1342 (let* ((col (current-column))
1344 (hline1p (save-excursion (beginning-of-line 1)
1345 (looking-at org-table-hline-regexp
)))
1346 (dline1 (org-table-current-dline))
1347 (dline2 (+ dline1
(if up -
1 1)))
1350 (beginning-of-line tonew
)
1351 (unless (org-at-table-p)
1353 (error "Cannot move row further"))
1354 (setq hline2p
(looking-at org-table-hline-regexp
))
1356 (beginning-of-line 1)
1358 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1359 (delete-region (point) (1+ (point-at-eol)))
1360 (beginning-of-line tonew
)
1362 (beginning-of-line 0)
1363 (org-move-to-column col
)
1364 (unless (or hline1p hline2p
)
1365 (org-table-fix-formulas
1366 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1367 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1369 (defun org-table-insert-row (&optional arg
)
1370 "Insert a new row above the current line into the table.
1371 With prefix ARG, insert below the current line."
1373 (if (not (org-at-table-p))
1374 (error "Not at a table"))
1375 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1376 (new (org-table-clean-line line
)))
1377 ;; Fix the first field if necessary
1378 (if (string-match "^[ \t]*| *[#$] *|" line
)
1379 (setq new
(replace-match (match-string 0 line
) t t new
)))
1380 (beginning-of-line (if arg
2 1))
1381 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1382 (beginning-of-line 0)
1383 (re-search-forward "| ?" (point-at-eol) t
)
1384 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1386 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1)))
1388 (defun org-table-insert-hline (&optional above
)
1389 "Insert a horizontal-line below the current line into the table.
1390 With prefix ABOVE, insert above the current line."
1392 (if (not (org-at-table-p))
1393 (error "Not at a table"))
1394 (when (eobp) (insert "\n") (backward-char 1))
1395 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1397 (let ((line (org-table-clean-line
1398 (buffer-substring (point-at-bol) (point-at-eol))))
1399 (col (current-column)))
1400 (while (string-match "|\\( +\\)|" line
)
1401 (setq line
(replace-match
1402 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1403 ?-
) "|") t t line
)))
1404 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1405 (beginning-of-line (if above
1 2))
1407 (beginning-of-line (if above
1 -
1))
1408 (org-move-to-column col
)
1409 (and org-table-overlay-coordinates
(org-table-align))))
1411 (defun org-table-hline-and-move (&optional same-column
)
1412 "Insert a hline and move to the row below that line."
1414 (let ((col (org-table-current-column)))
1415 (org-table-maybe-eval-formula)
1416 (org-table-maybe-recalculate-line)
1417 (org-table-insert-hline)
1419 (if (looking-at "\n[ \t]*|-")
1420 (progn (insert "\n|") (org-table-align))
1421 (org-table-next-field))
1422 (if same-column
(org-table-goto-column col
))))
1424 (defun org-table-clean-line (s)
1425 "Convert a table line S into a string with only \"|\" and space.
1426 In particular, this does handle wide and invisible characters."
1427 (if (string-match "^[ \t]*|-" s
)
1428 ;; It's a hline, just map the characters
1429 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1430 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1431 (setq s
(replace-match
1432 (concat "|" (make-string (org-string-width (match-string 1 s
))
1437 (defun org-table-kill-row ()
1438 "Delete the current row or horizontal line from the table."
1440 (if (not (org-at-table-p))
1441 (error "Not at a table"))
1442 (let ((col (current-column))
1443 (dline (org-table-current-dline)))
1444 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1445 (if (not (org-at-table-p)) (beginning-of-line 0))
1446 (org-move-to-column col
)
1447 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1450 (defun org-table-sort-lines (with-case &optional sorting-type
)
1451 "Sort table lines according to the column at point.
1453 The position of point indicates the column to be used for
1454 sorting, and the range of lines is the range between the nearest
1455 horizontal separator lines, or the entire table of no such lines
1456 exist. If point is before the first column, you will be prompted
1457 for the sorting column. If there is an active region, the mark
1458 specifies the first line and the sorting column, while point
1459 should be in the last line to be included into the sorting.
1461 The command then prompts for the sorting type which can be
1462 alphabetically, numerically, or by time (as given in a time stamp
1463 in the field). Sorting in reverse order is also possible.
1465 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1467 If SORTING-TYPE is specified when this function is called from a Lisp
1468 program, no prompting will take place. SORTING-TYPE must be a character,
1469 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1470 should be done in reverse order."
1472 (let* ((thisline (org-current-line))
1473 (thiscol (org-table-current-column))
1474 beg end bcol ecol tend tbeg column lns pos
)
1475 (when (equal thiscol
0)
1479 (read-string "Use column N for sorting: ")))
1481 (org-table-goto-column thiscol
))
1482 (org-table-check-inside-data-field)
1483 (if (org-region-active-p)
1485 (setq beg
(region-beginning) end
(region-end))
1487 (setq column
(org-table-current-column)
1490 (setq end
(point-at-bol 2)))
1491 (setq column
(org-table-current-column)
1493 tbeg
(org-table-begin)
1494 tend
(org-table-end))
1495 (if (re-search-backward org-table-hline-regexp tbeg t
)
1496 (setq beg
(point-at-bol 2))
1498 (setq beg
(point-at-bol 1)))
1500 (if (re-search-forward org-table-hline-regexp tend t
)
1501 (setq end
(point-at-bol 1))
1503 (setq end
(point-at-bol))))
1504 (setq beg
(move-marker (make-marker) beg
)
1505 end
(move-marker (make-marker) end
))
1508 (org-table-goto-column column
)
1509 (skip-chars-backward "^|")
1510 (setq bcol
(current-column))
1511 (org-table-goto-column (1+ column
))
1512 (skip-chars-backward "^|")
1513 (setq ecol
(1- (current-column)))
1514 (org-table-goto-column column
)
1515 (setq lns
(mapcar (lambda(x) (cons
1516 (org-sort-remove-invisible
1518 (org-split-string x
"[ \t]*|[ \t]*")))
1520 (org-split-string (buffer-substring beg end
) "\n")))
1521 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1522 (delete-region beg end
)
1523 (move-marker beg nil
)
1524 (move-marker end nil
)
1525 (insert (mapconcat 'cdr lns
"\n") "\n")
1526 (org-goto-line thisline
)
1527 (org-table-goto-column thiscol
)
1528 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1531 (defun org-table-cut-region (beg end
)
1532 "Copy region in table to the clipboard and blank all relevant fields.
1533 If there is no active region, use just the field at point."
1535 (if (org-region-active-p) (region-beginning) (point))
1536 (if (org-region-active-p) (region-end) (point))))
1537 (org-table-copy-region beg end
'cut
))
1539 (defun org-table-copy-region (beg end
&optional cut
)
1540 "Copy rectangular region in table to clipboard.
1541 A special clipboard is used which can only be accessed
1542 with `org-table-paste-rectangle'."
1544 (if (org-region-active-p) (region-beginning) (point))
1545 (if (org-region-active-p) (region-end) (point))
1546 current-prefix-arg
))
1547 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1549 (rpl (if cut
" " nil
)))
1551 (org-table-check-inside-data-field)
1552 (setq l01
(org-current-line)
1553 c01
(org-table-current-column))
1555 (org-table-check-inside-data-field)
1556 (setq l02
(org-current-line)
1557 c02
(org-table-current-column))
1558 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1559 c1
(min c01 c02
) c2
(max c01 c02
))
1563 (if (> l1 l2
) (throw 'exit t
))
1565 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1566 (setq cols nil ic1 c1 ic2 c2
)
1567 (while (< ic1
(1+ ic2
))
1568 (push (org-table-get-field ic1 rpl
) cols
)
1569 (setq ic1
(1+ ic1
)))
1570 (push (nreverse cols
) region
)
1571 (setq l1
(1+ l1
)))))
1572 (setq org-table-clip
(nreverse region
))
1573 (if cut
(org-table-align))
1576 (defun org-table-paste-rectangle ()
1577 "Paste a rectangular region into a table.
1578 The upper right corner ends up in the current field. All involved fields
1579 will be overwritten. If the rectangle does not fit into the present table,
1580 the table is enlarged as needed. The process ignores horizontal separator
1583 (unless (and org-table-clip
(listp org-table-clip
))
1584 (error "First cut/copy a region to paste!"))
1585 (org-table-check-inside-data-field)
1586 (let* ((clip org-table-clip
)
1587 (line (org-current-line))
1588 (col (org-table-current-column))
1589 (org-enable-table-editor t
)
1590 (org-table-automatic-realign nil
)
1592 (while (setq cols
(pop clip
))
1593 (while (org-at-table-hline-p) (beginning-of-line 2))
1594 (if (not (org-at-table-p))
1595 (progn (end-of-line 0) (org-table-next-field)))
1597 (while (setq field
(pop cols
))
1598 (org-table-goto-column c nil
'force
)
1599 (org-table-get-field nil field
)
1601 (beginning-of-line 2))
1602 (org-goto-line line
)
1603 (org-table-goto-column col
)
1606 (defun org-table-convert ()
1607 "Convert from `org-mode' table to table.el and back.
1608 Obviously, this only works within limits. When an Org-mode table is
1609 converted to table.el, all horizontal separator lines get lost, because
1610 table.el uses these as cell boundaries and has no notion of horizontal lines.
1611 A table.el table can be converted to an Org-mode table only if it does not
1612 do row or column spanning. Multiline cells will become multiple cells.
1613 Beware, Org-mode does not test if the table can be successfully converted - it
1614 blindly applies a recipe that works for simple tables."
1617 (if (org-at-table.el-p
)
1618 ;; convert to Org-mode table
1619 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1620 (end (move-marker (make-marker) (org-table-end t
))))
1621 (table-unrecognize-region beg end
)
1623 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1626 (if (org-at-table-p)
1627 ;; convert to table.el table
1628 (let ((beg (move-marker (make-marker) (org-table-begin)))
1629 (end (move-marker (make-marker) (org-table-end))))
1630 ;; first, get rid of all horizontal lines
1632 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1634 ;; insert a hline before first
1636 (org-table-insert-hline 'above
)
1637 (beginning-of-line -
1)
1638 ;; insert a hline after each line
1639 (while (progn (beginning-of-line 3) (< (point) end
))
1640 (org-table-insert-hline))
1642 (setq end
(move-marker end
(org-table-end)))
1643 ;; replace "+" at beginning and ending of hlines
1644 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1645 (replace-match "\\1+-"))
1647 (while (re-search-forward "-|[ \t]*$" end t
)
1648 (replace-match "-+"))
1651 (defun org-table-wrap-region (arg)
1652 "Wrap several fields in a column like a paragraph.
1653 This is useful if you'd like to spread the contents of a field over several
1654 lines, in order to keep the table compact.
1656 If there is an active region, and both point and mark are in the same column,
1657 the text in the column is wrapped to minimum width for the given number of
1658 lines. Generally, this makes the table more compact. A prefix ARG may be
1659 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1660 formats the selected text to two lines. If the region was longer than two
1661 lines, the remaining lines remain empty. A negative prefix argument reduces
1662 the current number of lines by that amount. The wrapped text is pasted back
1663 into the table. If you formatted it to more lines than it was before, fields
1664 further down in the table get overwritten - so you might need to make space in
1667 If there is no region, the current field is split at the cursor position and
1668 the text fragment to the right of the cursor is prepended to the field one
1671 If there is no region, but you specify a prefix ARG, the current field gets
1672 blank, and the content is appended to the field above."
1674 (org-table-check-inside-data-field)
1675 (if (org-region-active-p)
1676 ;; There is a region: fill as a paragraph
1677 (let* ((beg (region-beginning))
1678 (cline (save-excursion (goto-char beg
) (org-current-line)))
1679 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1681 (org-table-cut-region (region-beginning) (region-end))
1682 (if (> (length (car org-table-clip
)) 1)
1683 (error "Region must be limited to single column"))
1684 (setq nlines
(if arg
1686 (+ (length org-table-clip
) arg
)
1688 (length org-table-clip
)))
1689 (setq org-table-clip
1690 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1692 (org-goto-line cline
)
1693 (org-table-goto-column ccol
)
1694 (org-table-paste-rectangle))
1695 ;; No region, split the current field at point
1696 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1697 (skip-chars-forward "^\r\n|"))
1699 ;; combine with field above
1700 (let ((s (org-table-blank-field))
1701 (col (org-table-current-column)))
1702 (beginning-of-line 0)
1703 (while (org-at-table-hline-p) (beginning-of-line 0))
1704 (org-table-goto-column col
)
1705 (skip-chars-forward "^|")
1706 (skip-chars-backward " ")
1707 (insert " " (org-trim s
))
1710 (if (looking-at "\\([^|]+\\)+|")
1711 (let ((s (match-string 1)))
1712 (replace-match " |")
1713 (goto-char (match-beginning 0))
1714 (org-table-next-row)
1715 (insert (org-trim s
) " ")
1717 (org-table-next-row)))))
1719 (defvar org-field-marker nil
)
1721 (defun org-table-edit-field (arg)
1722 "Edit table field in a different window.
1723 This is mainly useful for fields that contain hidden parts.
1724 When called with a \\[universal-argument] prefix, just make the full field visible so that
1725 it can be edited in place."
1728 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1729 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1730 (remove-text-properties b e
'(org-cwidth t invisible t
1731 display t intangible t
))
1732 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1733 (font-lock-fontify-block)))
1734 (let ((pos (move-marker (make-marker) (point)))
1735 (field (org-table-get-field))
1736 (cw (current-window-configuration))
1738 (org-switch-to-buffer-other-window "*Org tmp*")
1740 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
1741 (let ((org-inhibit-startup t
)) (org-mode))
1742 (goto-char (setq p
(point-max)))
1743 (insert (org-trim field
))
1744 (remove-text-properties p
(point-max)
1745 '(invisible t org-cwidth t display t
1748 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1749 (org-set-local 'org-window-configuration cw
)
1750 (org-set-local 'org-field-marker pos
)
1751 (message "Edit and finish with C-c C-c"))))
1753 (defun org-table-finish-edit-field ()
1754 "Finish editing a table data field.
1755 Remove all newline characters, insert the result into the table, realign
1756 the table and kill the editing buffer."
1757 (let ((pos org-field-marker
)
1758 (cw org-window-configuration
)
1759 (cb (current-buffer))
1761 (goto-char (point-min))
1762 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1763 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1764 (replace-match " "))
1765 (setq text
(org-trim (buffer-string)))
1766 (set-window-configuration cw
)
1768 (select-window (get-buffer-window (marker-buffer pos
)))
1770 (move-marker pos nil
)
1771 (org-table-check-inside-data-field)
1772 (org-table-get-field nil text
)
1774 (message "New field value inserted")))
1776 (defvar org-timecnt
) ; dynamically scoped parameter
1778 (defun org-table-sum (&optional beg end nlast
)
1779 "Sum numbers in region of current table column.
1780 The result will be displayed in the echo area, and will be available
1781 as kill to be inserted with \\[yank].
1783 If there is an active region, it is interpreted as a rectangle and all
1784 numbers in that rectangle will be summed. If there is no active
1785 region and point is located in a table column, sum all numbers in that
1788 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1789 numbers are assumed to be times as well (in decimal hours) and the
1790 numbers are added as such.
1792 If NLAST is a number, only the NLAST fields will actually be summed."
1795 (let (col (org-timecnt 0) diff h m s org-table-clip
)
1797 ((and beg end
)) ; beg and end given explicitly
1798 ((org-region-active-p)
1799 (setq beg
(region-beginning) end
(region-end)))
1801 (setq col
(org-table-current-column))
1802 (goto-char (org-table-begin))
1803 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
1804 (error "No table data"))
1805 (org-table-goto-column col
)
1807 (goto-char (org-table-end))
1808 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
1809 (error "No table data"))
1810 (org-table-goto-column col
)
1811 (setq end
(point))))
1812 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
1813 (items1 (cond ((not nlast
) items
)
1814 ((>= nlast
(length items
)) items
)
1815 (t (setq items
(reverse items
))
1816 (setcdr (nthcdr (1- nlast
) items
) nil
)
1818 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
1820 (res (apply '+ numbers
))
1821 (sres (if (= org-timecnt
0)
1822 (number-to-string res
)
1823 (setq diff
(* 3600 res
)
1824 h
(floor (/ diff
3600)) diff
(mod diff
3600)
1825 m
(floor (/ diff
60)) diff
(mod diff
60)
1827 (format "%d:%02d:%02d" h m s
))))
1831 (substitute-command-keys
1832 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
1833 (length numbers
) sres
))))
1836 (defun org-table-get-number-for-summing (s)
1838 (if (string-match "^ *|? *" s
)
1839 (setq s
(replace-match "" nil nil s
)))
1840 (if (string-match " *|? *$" s
)
1841 (setq s
(replace-match "" nil nil s
)))
1842 (setq n
(string-to-number s
))
1844 ((and (string-match "0" s
)
1845 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
1846 ((string-match "\\`[ \t]+\\'" s
) nil
)
1847 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
1848 (let ((h (string-to-number (or (match-string 1 s
) "0")))
1849 (m (string-to-number (or (match-string 2 s
) "0")))
1850 (s (string-to-number (or (match-string 4 s
) "0"))))
1851 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
1852 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
1856 (defun org-table-current-field-formula (&optional key noerror
)
1857 "Return the formula active for the current field.
1858 Assumes that specials are in place.
1859 If KEY is given, return the key to this formula.
1860 Otherwise return the formula preceded with \"=\" or \":=\"."
1861 (let* ((name (car (rassoc (list (org-current-line)
1862 (org-table-current-column))
1863 org-table-named-field-locations
)))
1864 (col (org-table-current-column))
1865 (scol (int-to-string col
))
1866 (ref (format "@%d$%d" (org-table-current-dline) col
))
1867 (stored-list (org-table-get-stored-formulas noerror
))
1868 (ass (or (assoc name stored-list
)
1869 (assoc ref stored-list
)
1870 (assoc scol stored-list
))))
1873 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
1876 (defun org-table-get-formula (&optional equation named
)
1877 "Read a formula from the minibuffer, offer stored formula as default.
1878 When NAMED is non-nil, look for a named equation."
1879 (let* ((stored-list (org-table-get-stored-formulas))
1880 (name (car (rassoc (list (org-current-line)
1881 (org-table-current-column))
1882 org-table-named-field-locations
)))
1883 (ref (format "@%d$%d" (org-table-current-dline)
1884 (org-table-current-column)))
1885 (refass (assoc ref stored-list
))
1886 (nameass (assoc name stored-list
))
1888 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
1891 (int-to-string (org-table-current-column))))
1892 (dummy (and (or nameass refass
) (not named
)
1893 (not (y-or-n-p "Replace existing field formula with column formula? " ))
1895 (name (or name ref
))
1896 (org-table-may-need-update nil
)
1897 (stored (cdr (assoc scol stored-list
)))
1899 ((and stored equation
(string-match "^ *=? *$" equation
))
1903 (t (org-table-formula-from-user
1905 (org-table-formula-to-user
1906 (format "%s formula %s%s="
1907 (if named
"Field" "Column")
1908 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
1910 (if stored
(org-table-formula-to-user stored
) "")
1911 'org-table-formula-history
1914 (when (not (string-match "\\S-" eq
))
1916 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
1917 (org-table-store-formulas stored-list
)
1918 (error "Formula removed"))
1919 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
1920 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
1921 (if (and name
(not named
))
1922 ;; We set the column equation, delete the named one.
1923 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
1926 (setcdr (assoc scol stored-list
) eq
)
1927 (setq stored-list
(cons (cons scol eq
) stored-list
)))
1928 (if (or mustsave
(not (equal stored eq
)))
1929 (org-table-store-formulas stored-list
))
1932 (defun org-table-store-formulas (alist)
1933 "Store the list of formulas below the current table."
1934 (setq alist
(sort alist
'org-table-formula-less-p
))
1936 (goto-char (org-table-end))
1937 (if (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM:\\(.*\n?\\)")
1939 ;; don't overwrite TBLFM, we might use text properties to store stuff
1940 (goto-char (match-beginning 2))
1941 (delete-region (match-beginning 2) (match-end 0)))
1942 (org-indent-line-function)
1943 (insert "#+TBLFM:"))
1945 (mapconcat (lambda (x)
1947 (if (equal (string-to-char (car x
)) ?
@) "" "$")
1948 (car x
) "=" (cdr x
)))
1952 (defsubst org-table-formula-make-cmp-string
(a)
1953 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a
)
1955 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a
))) "")
1956 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a
))) "")
1957 (if (match-end 5) (concat "@@" (match-string 5 a
))))))
1959 (defun org-table-formula-less-p (a b
)
1960 "Compare two formulas for sorting."
1961 (let ((as (org-table-formula-make-cmp-string (car a
)))
1962 (bs (org-table-formula-make-cmp-string (car b
))))
1963 (and as bs
(string< as bs
))))
1965 (defun org-table-get-stored-formulas (&optional noerror
)
1966 "Return an alist with the stored formulas directly after current table."
1968 (let (scol eq eq-alist strings string seen
)
1970 (goto-char (org-table-end))
1971 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
1972 (setq strings
(org-split-string (match-string 2) " *:: *"))
1973 (while (setq string
(pop strings
))
1974 (when (string-match "\\`\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
1975 (setq scol
(if (match-end 2)
1976 (match-string 2 string
)
1977 (match-string 1 string
))
1978 eq
(match-string 3 string
)
1979 eq-alist
(cons (cons scol eq
) eq-alist
))
1980 (if (member scol seen
)
1983 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
1986 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
1987 (push scol seen
))))))
1988 (nreverse eq-alist
)))
1990 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
1991 "Modify the equations after the table structure has been edited.
1992 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
1993 For all numbers larger than LIMIT, shift them by DELTA."
1995 (goto-char (org-table-end))
1996 (when (looking-at "[ \t]*#\\+TBLFM:")
1997 (let ((re (concat key
"\\([0-9]+\\)"))
2000 (if (or (equal key
"$") (equal key
"$LR"))
2001 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2002 (regexp-quote key
) remove
)
2003 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2006 (while (re-search-forward re2
(point-at-eol) t
)
2007 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2008 (replace-match ""))))
2009 (while (re-search-forward re
(point-at-eol) t
)
2010 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2011 (setq s
(match-string 1) n
(string-to-number s
))
2013 ((setq a
(assoc s replace
))
2014 (replace-match (concat key
(cdr a
)) t t
))
2015 ((and limit
(> n limit
))
2016 (replace-match (concat key
(int-to-string (+ n delta
)))
2019 (defun org-table-get-specials ()
2020 "Get the column names and local parameters for this table."
2022 (let ((beg (org-table-begin)) (end (org-table-end))
2023 names name fields fields1 field cnt
2024 c v l line col types dlines hlines last-dline
)
2025 (setq org-table-column-names nil
2026 org-table-local-parameters nil
2027 org-table-named-field-locations nil
2028 org-table-current-begin-line nil
2029 org-table-current-begin-pos nil
2030 org-table-current-line-types nil
)
2032 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2033 (setq names
(org-split-string (match-string 1) " *| *")
2035 (while (setq name
(pop names
))
2037 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name
)
2038 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2039 (setq org-table-column-names
(nreverse org-table-column-names
))
2040 (setq org-table-column-name-regexp
2041 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2043 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2044 (setq fields
(org-split-string (match-string 1) " *| *"))
2045 (while (setq field
(pop fields
))
2046 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2047 (push (cons (match-string 1 field
) (match-string 2 field
))
2048 org-table-local-parameters
))))
2050 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2051 (setq c
(match-string 1)
2052 fields
(org-split-string (match-string 2) " *| *"))
2054 (beginning-of-line (if (equal c
"_") 2 0))
2055 (setq line
(org-current-line) col
1)
2056 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2057 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2058 (while (and fields1
(setq field
(pop fields
)))
2059 (setq v
(pop fields1
) col
(1+ col
))
2060 (when (and (stringp field
) (stringp v
)
2061 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field
))
2062 (push (cons field v
) org-table-local-parameters
)
2063 (push (list field line col
) org-table-named-field-locations
))))
2064 ;; Analyse the line types
2066 (setq org-table-current-begin-line
(org-current-line)
2067 org-table-current-begin-pos
(point)
2068 l org-table-current-begin-line
)
2069 (while (looking-at "[ \t]*|\\(-\\)?")
2070 (push (if (match-end 1) 'hline
'dline
) types
)
2071 (if (match-end 1) (push l hlines
) (push l dlines
))
2072 (beginning-of-line 2)
2074 (push 'hline types
) ;; add an imaginary extra hline to the end
2075 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2076 last-dline
(car dlines
)
2077 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2078 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2079 (org-goto-line last-dline
)
2080 (let* ((l last-dline
)
2081 (fields (org-split-string
2082 (buffer-substring (point-at-bol) (point-at-eol))
2084 (nfields (length fields
))
2086 (loop for i from
1 to nfields do
2087 (push (list (format "LR%d" i
) l i
) al
)
2088 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2089 (setq org-table-named-field-locations
2090 (append org-table-named-field-locations al
))
2091 (setq org-table-local-parameters
2092 (append org-table-local-parameters al2
))))))
2095 (defun org-table-maybe-eval-formula ()
2096 "Check if the current field starts with \"=\" or \":=\".
2097 If yes, store the formula and apply it."
2098 ;; We already know we are in a table. Get field will only return a formula
2099 ;; when appropriate. It might return a separator line, but no problem.
2100 (when org-table-formula-evaluate-inline
2101 (let* ((field (org-trim (or (org-table-get-field) "")))
2103 (when (string-match "^:?=\\(.*\\)" field
)
2104 (setq named
(equal (string-to-char field
) ?
:)
2105 eq
(match-string 1 field
))
2106 (if (or (fboundp 'calc-eval
)
2107 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2108 (org-table-eval-formula (if named
'(4) nil
)
2109 (org-table-formula-from-user eq
))
2110 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2112 (defvar org-recalc-commands nil
2113 "List of commands triggering the recalculation of a line.
2114 Will be filled automatically during use.")
2116 (defvar org-recalc-marks
2117 '((" " .
"Unmarked: no special line, no automatic recalculation")
2118 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2119 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2120 ("!" .
"Column name definition line. Reference in formula as $name.")
2121 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2122 ("_" .
"Names for values in row below this one.")
2123 ("^" .
"Names for values in row above this one.")))
2125 (defun org-table-rotate-recalc-marks (&optional newchar
)
2126 "Rotate the recalculation mark in the first column.
2127 If in any row, the first field is not consistent with a mark,
2128 insert a new column for the markers.
2129 When there is an active region, change all the lines in the region,
2130 after prompting for the marking character.
2131 After each change, a message will be displayed indicating the meaning
2134 (unless (org-at-table-p) (error "Not at a table"))
2135 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2136 (beg (org-table-begin))
2137 (end (org-table-end))
2138 (l (org-current-line))
2139 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2140 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2144 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2145 (col (org-table-current-column))
2146 (forcenew (car (assoc newchar org-recalc-marks
)))
2149 (message "Change region to what mark? Type # * ! $ or SPC: ")
2150 (setq newchar
(char-to-string (read-char-exclusive))
2151 forcenew
(car (assoc newchar org-recalc-marks
))))
2152 (if (and newchar
(not forcenew
))
2153 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2155 (if l1
(org-goto-line l1
))
2157 (beginning-of-line 1)
2158 (unless (looking-at org-table-dataline-regexp
)
2159 (error "Not at a table data line")))
2161 (org-table-goto-column 1)
2162 (org-table-insert-column)
2163 (org-table-goto-column (1+ col
)))
2164 (setq epos
(point-at-eol))
2166 (beginning-of-line 1)
2167 (org-table-get-field
2168 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2170 (setq new
(or forcenew
2171 (cadr (member (match-string 1) marks
))))
2177 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2178 (and (looking-at org-table-dataline-regexp
)
2179 (org-table-get-field 1 (concat " " new
" "))))
2180 (org-goto-line l1
)))
2181 (if (not (= epos
(point-at-eol))) (org-table-align))
2183 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks
))))))
2185 (defun org-table-maybe-recalculate-line ()
2186 "Recompute the current line if marked for it, and if we haven't just done it."
2188 (and org-table-allow-automatic-line-recalculation
2189 (not (and (memq last-command org-recalc-commands
)
2190 (equal org-last-recalc-line
(org-current-line))))
2191 (save-excursion (beginning-of-line 1)
2192 (looking-at org-table-auto-recalculate-regexp
))
2193 (org-table-recalculate) t
))
2196 (defsubst org-set-calc-mode
(var &optional value
)
2198 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2199 ("R" calc-angle-mode rad
)
2200 ("F" calc-prefer-frac t
)
2201 ("S" calc-symbolic-mode t
)))
2202 value
(nth 2 var
) var
(nth 1 var
)))
2203 (if (memq var modes
)
2204 (setcar (cdr (memq var modes
)) value
)
2205 (cons var
(cons value modes
)))
2208 (defun org-table-eval-formula (&optional arg equation
2209 suppress-align suppress-const
2210 suppress-store suppress-analysis
)
2211 "Replace the table field value at the cursor by the result of a calculation.
2213 This function makes use of Dave Gillespie's Calc package, in my view the
2214 most exciting program ever written for GNU Emacs. So you need to have Calc
2215 installed in order to use this function.
2217 In a table, this command replaces the value in the current field with the
2218 result of a formula. It also installs the formula as the \"current\" column
2219 formula, by storing it in a special line below the table. When called
2220 with a `C-u' prefix, the current field must be a named field, and the
2221 formula is installed as valid in only this specific field.
2223 When called with two `C-u' prefixes, insert the active equation
2224 for the field back into the current field, so that it can be
2225 edited there. This is useful in order to use \\[org-table-show-reference]
2226 to check the referenced fields.
2228 When called, the command first prompts for a formula, which is read in
2229 the minibuffer. Previously entered formulas are available through the
2230 history list, and the last used formula is offered as a default.
2231 These stored formulas are adapted correctly when moving, inserting, or
2232 deleting columns with the corresponding commands.
2234 The formula can be any algebraic expression understood by the Calc package.
2235 For details, see the Org-mode manual.
2237 This function can also be called from Lisp programs and offers
2238 additional arguments: EQUATION can be the formula to apply. If this
2239 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2240 used to speed-up recursive calls by by-passing unnecessary aligns.
2241 SUPPRESS-CONST suppresses the interpretation of constants in the
2242 formula, assuming that this has been done already outside the function.
2243 SUPPRESS-STORE means the formula should not be stored, either because
2244 it is already stored, or because it is a modified equation that should
2245 not overwrite the stored one."
2247 (org-table-check-inside-data-field)
2248 (or suppress-analysis
(org-table-get-specials))
2249 (if (equal arg
'(16))
2250 (let ((eq (org-table-current-field-formula)))
2251 (or eq
(error "No equation active for current field"))
2252 (org-table-get-field nil eq
)
2254 (setq org-table-may-need-update t
))
2256 (ndown (if (integerp arg
) arg
1))
2257 (org-table-automatic-realign nil
)
2258 (case-fold-search nil
)
2260 (formula (if (and equation suppress-store
)
2262 (org-table-get-formula equation
(equal arg
'(4)))))
2263 (n0 (org-table-current-column))
2264 (modes (copy-sequence org-calc-default-modes
))
2265 (numbers nil
) ; was a variable, now fixed default
2267 n form form0 bw fmt x ev orig c lispp literal
)
2268 ;; Parse the format string. Since we have a lot of modes, this is
2269 ;; a lot of work. However, I think calc still uses most of the time.
2270 (if (string-match ";" formula
)
2271 (let ((tmp (org-split-string formula
";")))
2272 (setq formula
(car tmp
)
2273 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2275 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2276 (setq c
(string-to-char (match-string 1 fmt
))
2277 n
(string-to-number (match-string 2 fmt
)))
2279 (setq modes
(org-set-calc-mode 'calc-internal-prec n
))
2280 (setq modes
(org-set-calc-mode
2282 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2283 (?s . sci
) (?e . eng
))))
2285 (setq fmt
(replace-match "" t t fmt
)))
2286 (if (string-match "[NT]" fmt
)
2287 (setq numbers
(equal (match-string 0 fmt
) "N")
2288 fmt
(replace-match "" t t fmt
)))
2289 (if (string-match "L" fmt
)
2291 fmt
(replace-match "" t t fmt
)))
2292 (if (string-match "E" fmt
)
2294 fmt
(replace-match "" t t fmt
)))
2295 (while (string-match "[DRFS]" fmt
)
2296 (setq modes
(org-set-calc-mode (match-string 0 fmt
)))
2297 (setq fmt
(replace-match "" t t fmt
)))
2298 (unless (string-match "\\S-" fmt
)
2300 (if (and (not suppress-const
) org-table-formula-use-constants
)
2301 (setq formula
(org-table-formula-substitute-names formula
)))
2302 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2304 (setq fields
(org-split-string
2306 (buffer-substring (point-at-bol) (point-at-eol)))
2309 (setq fields
(mapcar
2310 (lambda (x) (number-to-string (string-to-number x
)))
2312 (setq ndown
(1- ndown
))
2313 (setq form
(copy-sequence formula
)
2314 lispp
(and (> (length form
) 2)(equal (substring form
0 2) "'(")))
2315 (if (and lispp literal
) (setq lispp
'literal
))
2317 ;; Insert row and column number of formula result field
2318 (while (string-match "[@$]#" form
)
2323 (if (equal (substring form
(match-beginning 0)
2324 (1+ (match-beginning 0)))
2326 (org-table-current-dline)
2327 (org-table-current-column))))
2330 ;; Check for old vertical references
2331 (setq form
(org-table-rewrite-old-row-references form
))
2332 ;; Insert remote references
2333 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2337 (org-table-make-reference
2338 (org-table-get-remote-range
2339 (match-string 1 form
) (match-string 2 form
))
2340 keep-empty numbers lispp
))
2342 ;; Insert complex ranges
2343 (while (and (string-match org-table-range-regexp form
)
2344 (> (length (match-string 0 form
)) 1))
2348 (org-table-make-reference
2349 (org-table-get-range (match-string 0 form
) nil n0
)
2350 keep-empty numbers lispp
))
2352 ;; Insert simple ranges
2353 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2357 (org-table-make-reference
2359 fields
(string-to-number (match-string 1 form
))
2360 (string-to-number (match-string 2 form
)))
2361 keep-empty numbers lispp
))
2364 ;; Insert the references to fields in same row
2365 (while (string-match "\\$\\([0-9]+\\)" form
)
2366 (setq n
(string-to-number (match-string 1 form
))
2367 x
(nth (1- (if (= n
0) n0 n
)) fields
))
2368 (unless x
(error "Invalid field specifier \"%s\""
2369 (match-string 0 form
)))
2370 (setq form
(replace-match
2372 (org-table-make-reference x nil numbers lispp
))
2376 (setq ev
(condition-case nil
2377 (eval (eval (read form
)))
2379 ev
(if (numberp ev
) (number-to-string ev
) ev
))
2380 (or (fboundp 'calc-eval
)
2381 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2382 (setq ev
(calc-eval (cons form modes
)
2383 (if numbers
'num
))))
2385 (when org-table-formula-debug
2386 (with-output-to-temp-buffer "*Substitution History*"
2387 (princ (format "Substitution history of formula
2391 $1-> %s\n" orig formula form0 form
))
2393 (princ (format " %s^\nError: %s"
2394 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2395 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2397 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2398 (setq bw
(get-buffer-window "*Substitution History*"))
2399 (org-fit-window-to-buffer bw
)
2400 (unless (and (interactive-p) (not ndown
))
2401 (unless (let (inhibit-redisplay)
2402 (y-or-n-p "Debugging Formula. Continue to next? "))
2407 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2408 (org-table-justify-field-maybe
2409 (if fmt
(format fmt
(string-to-number ev
)) ev
))
2410 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2411 (call-interactively 'org-return
)
2413 (and down
(org-table-maybe-recalculate-line))
2414 (or suppress-align
(and org-table-may-need-update
2415 (org-table-align))))))
2417 (defun org-table-put-field-property (prop value
)
2419 (put-text-property (progn (skip-chars-backward "^|") (point))
2420 (progn (skip-chars-forward "^|") (point))
2423 (defun org-table-get-range (desc &optional tbeg col highlight
)
2424 "Get a calc vector from a column, according to descriptor DESC.
2425 Optional arguments TBEG and COL can give the beginning of the table and
2426 the current column, to avoid unnecessary parsing.
2427 HIGHLIGHT means just highlight the range."
2428 (if (not (equal (string-to-char desc
) ?
@))
2429 (setq desc
(concat "@" desc
)))
2431 (or tbeg
(setq tbeg
(org-table-begin)))
2432 (or col
(setq col
(org-table-current-column)))
2433 (let ((thisline (org-current-line))
2434 beg end c1 c2 r1 r2 rangep tmp
)
2435 (unless (string-match org-table-range-regexp desc
)
2436 (error "Invalid table range specifier `%s'" desc
))
2437 (setq rangep
(match-end 3)
2438 r1
(and (match-end 1) (match-string 1 desc
))
2439 r2
(and (match-end 4) (match-string 4 desc
))
2440 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2441 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2443 (and c1
(setq c1
(+ (string-to-number c1
)
2444 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2445 (and c2
(setq c2
(+ (string-to-number c2
)
2446 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2447 (if (equal r1
"") (setq r1 nil
))
2448 (if (equal r2
"") (setq r2 nil
))
2449 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2450 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2451 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2452 (if (not r1
) (setq r1 thisline
))
2453 (if (not r2
) (setq r2 thisline
))
2454 (if (not c1
) (setq c1 col
))
2455 (if (not c2
) (setq c2 col
))
2456 (if (or (not rangep
) (and (= r1 r2
) (= c1 c2
)))
2460 (while (not (looking-at org-table-dataline-regexp
))
2461 (beginning-of-line 2))
2462 (prog1 (org-trim (org-table-get-field c1
))
2463 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2464 ;; A range, return a vector
2465 ;; First sort the numbers to get a regular ractangle
2466 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2467 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2469 (while (not (looking-at org-table-dataline-regexp
))
2470 (beginning-of-line 2))
2471 (org-table-goto-column c1
)
2474 (while (not (looking-at org-table-dataline-regexp
))
2475 (beginning-of-line 0))
2476 (org-table-goto-column c2
)
2479 (org-table-highlight-rectangle
2480 beg
(progn (skip-chars-forward "^|\n") (point))))
2481 ;; return string representation of calc vector
2483 (apply 'append
(org-table-copy-region beg end
)))))))
2485 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2486 "Analyze descriptor DESC and retrieve the corresponding line number.
2487 The cursor is currently in line CLINE, the table begins in line BLINE,
2488 and TABLE is a vector with line types."
2489 (if (string-match "^[0-9]+$" desc
)
2490 (aref org-table-dlines
(string-to-number desc
))
2491 (setq cline
(or cline
(org-current-line))
2492 bline
(or bline org-table-current-begin-line
)
2493 table
(or table org-table-current-line-types
))
2495 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2497 (and (not (match-end 3)) (not (match-end 6)))
2498 (and (match-end 3) (match-end 6) (not (match-end 5))))
2499 (error "Invalid row descriptor `%s'" desc
))
2500 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2501 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2502 (odir (and (match-end 5) (match-string 5 desc
)))
2503 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2505 (rel (and (match-end 6)
2506 (or (and (match-end 1) (not (match-end 3)))
2508 (if (and hn
(not hdir
))
2511 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2512 (if (and (not hn
) on
(not odir
))
2513 (error "Should never happen");;(aref org-table-dlines on)
2514 (if (and hn
(> hn
0))
2515 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2516 nil hn cline desc
)))
2518 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2519 rel on cline desc
)))
2522 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2523 "FIXME: Needs more documentation."
2524 (let ((l (length table
)))
2526 (while (and (setq i
(+ i
(if backwards -
1 1)))
2528 (not (eq (aref table i
) type
))
2529 (if (and relative
(eq (aref table i
) 'hline
))
2531 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2532 ((eq org-table-relative-ref-may-cross-hline
'error
)
2533 (error "Row descriptor %s used in line %d crosses hline" desc cline
))
2534 (t (setq i
(- i
(if backwards -
1 1))
2539 (if (or (< i
0) (>= i l
))
2540 (error "Row descriptor %s used in line %d leads outside table"
2544 (defun org-table-rewrite-old-row-references (s)
2545 (if (string-match "&[-+0-9I]" s
)
2546 (error "Formula contains old &row reference, please rewrite using @-syntax")
2549 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2550 "Convert list ELEMENTS to something appropriate to insert into formula.
2551 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2552 NUMBERS indicates that everything should be converted to numbers.
2553 LISPP means to return something appropriate for a Lisp list."
2554 (if (stringp elements
) ; just a single val
2556 (if (eq lispp
'literal
)
2558 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2559 (if (equal elements
"") (setq elements
"0"))
2560 (if numbers
(setq elements
(number-to-string (string-to-number elements
))))
2561 (concat "(" elements
")"))
2565 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2567 (setq elements
(or elements
'("0")))
2571 (if (eq lispp
'literal
)
2573 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2575 (concat "[" (mapconcat
2577 (if numbers
(number-to-string (string-to-number x
)) x
))
2581 (defun org-table-recalculate (&optional all noalign
)
2582 "Recalculate the current table line by applying all stored formulas.
2583 With prefix arg ALL, do this for all lines in the table.
2584 With the prefix argument ALL is `(16)' \
2585 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2586 it is the symbol `iterate', recompute the table until it no longer changes.
2587 If NOALIGN is not nil, do not re-align the table after the computations
2588 are done. This is typically used internally to save time, if it is
2589 known that the table will be realigned a little later anyway."
2591 (or (memq this-command org-recalc-commands
)
2592 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2593 (unless (org-at-table-p) (error "Not at a table"))
2594 (if (or (eq all
'iterate
) (equal all
'(16)))
2596 (org-table-get-specials)
2597 (let* ((eqlist (sort (org-table-get-stored-formulas)
2598 (lambda (a b
) (string< (car a
) (car b
)))))
2599 (inhibit-redisplay (not debug-on-error
))
2600 (line-re org-table-dataline-regexp
)
2601 (thisline (org-current-line))
2602 (thiscol (org-table-current-column))
2603 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name
)
2604 ;; Insert constants in all formulas
2607 (setcdr x
(org-table-formula-substitute-names (cdr x
)))
2610 ;; Split the equation list
2611 (while (setq eq
(pop eqlist
))
2612 (if (<= (string-to-char (car eq
)) ?
9)
2615 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
2618 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
2619 (goto-char (setq beg
(org-table-begin)))
2620 (if (re-search-forward org-table-calculate-mark-regexp end t
)
2621 ;; This is a table with marked lines, compute selected lines
2622 (setq line-re org-table-recalculate-regexp
)
2623 ;; Move forward to the first non-header line
2624 (if (and (re-search-forward org-table-dataline-regexp end t
)
2625 (re-search-forward org-table-hline-regexp end t
)
2626 (re-search-forward org-table-dataline-regexp end t
))
2627 (setq beg
(match-beginning 0))
2628 nil
))) ;; just leave beg where it is
2629 (setq beg
(point-at-bol)
2630 end
(move-marker (make-marker) (1+ (point-at-eol)))))
2632 (and all
(message "Re-applying formulas to full table..."))
2634 ;; First find the named fields, and mark them untouchable
2635 (remove-text-properties beg end
'(org-untouchable t
))
2636 (while (setq eq
(pop eqlname
))
2638 a
(assoc name org-table-named-field-locations
))
2640 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
2643 (aref org-table-dlines
2644 (string-to-number (match-string 1 name
)))
2645 (error (error "Invalid row number in %s"
2647 (string-to-number (match-string 2 name
)))))
2648 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
2649 (message "Re-applying formula to field: %s" name
)
2650 (org-goto-line (nth 1 a
))
2651 (org-table-goto-column (nth 2 a
))
2652 (push (append a
(list (cdr eq
))) eqlname1
)
2653 (org-table-put-field-property :org-untouchable t
)))
2655 ;; Now evaluate the column formulas, but skip fields covered by
2658 (while (re-search-forward line-re end t
)
2659 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2660 ;; Unprotected line, recalculate
2661 (and all
(message "Re-applying formulas to full table...(line %d)"
2662 (setq cnt
(1+ cnt
))))
2663 (setq org-last-recalc-line
(org-current-line))
2665 (while (setq entry
(pop eql
))
2666 (org-goto-line org-last-recalc-line
)
2667 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
2668 (unless (get-text-property (point) :org-untouchable
)
2669 (org-table-eval-formula nil
(cdr entry
)
2670 'noalign
'nocst
'nostore
'noanalysis
)))))
2672 ;; Now evaluate the field formulas
2673 (while (setq eq
(pop eqlname1
))
2674 (message "Re-applying formula to field: %s" (car eq
))
2675 (org-goto-line (nth 1 eq
))
2676 (org-table-goto-column (nth 2 eq
))
2677 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
2678 'nostore
'noanalysis
))
2680 (org-goto-line thisline
)
2681 (org-table-goto-column thiscol
)
2682 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
2683 (or noalign
(and org-table-may-need-update
(org-table-align))
2684 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
2686 ;; back to initial position
2687 (message "Re-applying formulas...done")
2688 (org-goto-line thisline
)
2689 (org-table-goto-column thiscol
)
2690 (or noalign
(and org-table-may-need-update
(org-table-align))
2691 (and all
(message "Re-applying formulas...done"))))))
2693 (defun org-table-iterate (&optional arg
)
2694 "Recalculate the table until it does not change anymore."
2696 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
2698 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2703 (org-table-recalculate 'all
)
2704 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
2705 (if (not (string= lasttbl thistbl
))
2706 (setq lasttbl thistbl
)
2708 (message "Convergence after %d iterations" i
)
2709 (message "Table was already stable"))
2711 (error "No convergence after %d iterations" i
))))
2713 (defun org-table-recalculate-buffer-tables ()
2714 "Recalculate all tables in the current buffer."
2719 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
2721 (defun org-table-iterate-buffer-tables ()
2722 "Iterate all tables in the buffer, to converge inter-table dependencies."
2725 (checksum (md5 (buffer-string)))
2735 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
2736 (if (equal checksum
(setq c1
(md5 (buffer-string))))
2738 (message "Convergence after %d iterations" (- imax i
))
2740 (setq checksum c1
)))
2741 (error "No convergence after %d iterations" imax
))))))
2743 (defun org-table-formula-substitute-names (f)
2744 "Replace $const with values in string F."
2745 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
2746 ;; First, check for column names
2747 (while (setq start
(string-match org-table-column-name-regexp f start
))
2748 (setq start
(1+ start
))
2749 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
2750 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
2751 ;; Parameters and constants
2753 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
2755 (setq start
(match-end 2))
2756 (setq start
(1+ start
))
2757 (if (setq a
(save-match-data
2758 (org-table-get-constant (match-string 1 f
))))
2759 (setq f
(replace-match
2760 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
2761 (if org-table-formula-debug
2762 (put-text-property 0 (length f
) :orig-formula f1 f
))
2765 (defun org-table-get-constant (const)
2766 "Find the value for a parameter or constant in a formula.
2767 Parameters get priority."
2768 (or (cdr (assoc const org-table-local-parameters
))
2769 (cdr (assoc const org-table-formula-constants-local
))
2770 (cdr (assoc const org-table-formula-constants
))
2771 (and (fboundp 'constants-get
) (constants-get const
))
2772 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
2773 (org-entry-get nil
(substring const
5) 'inherit
))
2776 (defvar org-table-fedit-map
2777 (let ((map (make-sparse-keymap)))
2778 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
2779 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
2780 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
2781 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
2782 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
2783 (org-defkey map
"\C-c?" 'org-table-show-reference
)
2784 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
2785 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
2786 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
2787 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
2788 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
2789 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
2790 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
2791 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
2792 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
2793 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
2794 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
2795 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
2796 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
2797 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
2800 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
2802 ["Finish and Install" org-table-fedit-finish t
]
2803 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
2804 ["Abort" org-table-fedit-abort t
]
2806 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
2807 ["Complete Lisp Symbol" lisp-complete-symbol t
]
2809 "Shift Reference at Point"
2810 ["Up" org-table-fedit-ref-up t
]
2811 ["Down" org-table-fedit-ref-down t
]
2812 ["Left" org-table-fedit-ref-left t
]
2813 ["Right" org-table-fedit-ref-right t
]
2815 "Change Test Row for Column Formulas"
2816 ["Up" org-table-fedit-line-up t
]
2817 ["Down" org-table-fedit-line-down t
]
2819 ["Scroll Table Window" org-table-fedit-scroll t
]
2820 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
2821 ["Show Table Grid" org-table-fedit-toggle-coordinates
2822 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
2823 org-table-overlay-coordinates
)]
2825 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
2826 :style toggle
:selected org-table-buffer-is-an
]))
2830 (defun org-table-edit-formulas ()
2831 "Edit the formulas of the current table in a separate buffer."
2833 (when (save-excursion (beginning-of-line 1) (looking-at "[ \t]*#\\+TBLFM"))
2834 (beginning-of-line 0))
2835 (unless (org-at-table-p) (error "Not at a table"))
2836 (org-table-get-specials)
2837 (let ((key (org-table-current-field-formula 'key
'noerror
))
2838 (eql (sort (org-table-get-stored-formulas 'noerror
)
2839 'org-table-formula-less-p
))
2840 (pos (move-marker (make-marker) (point)))
2842 (wc (current-window-configuration))
2843 (sel-win (selected-window))
2844 (titles '((column .
"# Column Formulas\n")
2845 (field .
"# Field Formulas\n")
2846 (named .
"# Named Field Formulas\n")))
2848 (org-switch-to-buffer-other-window "*Edit Formulas*")
2850 ;; Keep global-font-lock-mode from turning on font-lock-mode
2851 (let ((font-lock-global-modes '(not fundamental-mode
)))
2853 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
2854 (org-set-local 'org-pos pos
)
2855 (org-set-local 'org-window-configuration wc
)
2856 (org-set-local 'org-selected-window sel-win
)
2857 (use-local-map org-table-fedit-map
)
2858 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
2859 (easy-menu-add org-table-fedit-menu
)
2860 (setq startline
(org-current-line))
2861 (while (setq entry
(pop eql
))
2863 ((equal (string-to-char (car entry
)) ?
@) 'field
)
2864 ((string-match "^[0-9]" (car entry
)) 'column
)
2866 (when (setq title
(assq type titles
))
2867 (or (bobp) (insert "\n"))
2868 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
2869 (setq titles
(delq title titles
)))
2870 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
2871 (setq s
(concat (if (equal (string-to-char (car entry
)) ?
@) "" "$")
2872 (car entry
) " = " (cdr entry
) "\n"))
2873 (remove-text-properties 0 (length s
) '(face nil
) s
)
2875 (if (eq org-table-use-standard-references t
)
2876 (org-table-fedit-toggle-ref-type))
2877 (org-goto-line startline
)
2878 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
2880 (defun org-table-fedit-post-command ()
2881 (when (not (memq this-command
'(lisp-complete-symbol)))
2882 (let ((win (selected-window)))
2885 (org-table-show-reference)
2887 (select-window win
)))))
2889 (defun org-table-formula-to-user (s)
2890 "Convert a formula from internal to user representation."
2891 (if (eq org-table-use-standard-references t
)
2892 (org-table-convert-refs-to-an s
)
2895 (defun org-table-formula-from-user (s)
2896 "Convert a formula from user to internal representation."
2897 (if org-table-use-standard-references
2898 (org-table-convert-refs-to-rc s
)
2901 (defun org-table-convert-refs-to-rc (s)
2902 "Convert spreadsheet references from AB7 to @7$28.
2903 Works for single references, but also for entire formulas and even the
2906 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^)]*)\\)" s start
)
2909 ;; format match, just advance
2910 (setq start
(match-end 0)))
2911 ((and (> (match-beginning 0) 0)
2912 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
2913 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
2914 ;; 3.e5 or something like this.
2915 (setq start
(match-end 0)))
2916 ((or (> (- (match-end 1) (match-beginning 1)) 2)
2917 ;; (member (match-string 1 s)
2918 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
2920 ;; function name, just advance
2921 (setq start
(match-end 0)))
2923 (setq start
(match-beginning 0)
2925 (if (equal (match-string 2 s
) "&")
2926 (format "$%d" (org-letters-to-number (match-string 1 s
)))
2928 (string-to-number (match-string 2 s
))
2929 (org-letters-to-number (match-string 1 s
))))
2933 (defun org-table-convert-refs-to-an (s)
2934 "Convert spreadsheet references from to @7$28 to AB7.
2935 Works for single references, but also for entire formulas and even the
2937 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
2938 (setq s
(replace-match
2940 (org-number-to-letters
2941 (string-to-number (match-string 2 s
)))
2942 (string-to-number (match-string 1 s
)))
2944 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
2945 (setq s
(replace-match (concat "\\1"
2946 (org-number-to-letters
2947 (string-to-number (match-string 2 s
))) "&")
2951 (defun org-letters-to-number (s)
2952 "Convert a base 26 number represented by letters into an integer.
2953 For example: AB -> 28."
2956 (while (> (length s
) 0)
2957 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
2961 (defun org-number-to-letters (n)
2962 "Convert an integer into a base 26 number represented by letters.
2963 For example: 28 -> AB."
2966 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
2970 (defun org-table-fedit-convert-buffer (function)
2971 "Convert all references in this buffer, using FUNCTION."
2972 (let ((line (org-current-line)))
2973 (goto-char (point-min))
2975 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
2976 (delete-region (point) (point-at-eol))
2977 (or (eobp) (forward-char 1)))
2978 (org-goto-line line
)))
2980 (defun org-table-fedit-toggle-ref-type ()
2981 "Convert all references in the buffer from B3 to @3$2 and back."
2983 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
2984 (org-table-fedit-convert-buffer
2985 (if org-table-buffer-is-an
2986 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
2987 (message "Reference type switched to %s"
2988 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
2990 (defun org-table-fedit-ref-up ()
2991 "Shift the reference at point one row/hline up."
2993 (org-table-fedit-shift-reference 'up
))
2994 (defun org-table-fedit-ref-down ()
2995 "Shift the reference at point one row/hline down."
2997 (org-table-fedit-shift-reference 'down
))
2998 (defun org-table-fedit-ref-left ()
2999 "Shift the reference at point one field to the left."
3001 (org-table-fedit-shift-reference 'left
))
3002 (defun org-table-fedit-ref-right ()
3003 "Shift the reference at point one field to the right."
3005 (org-table-fedit-shift-reference 'right
))
3007 (defun org-table-fedit-shift-reference (dir)
3009 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3010 (if (memq dir
'(left right
))
3011 (org-rematch-and-replace 1 (eq dir
'left
))
3012 (error "Cannot shift reference in this direction")))
3013 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3014 ;; A B3-like reference
3015 (if (memq dir
'(up down
))
3016 (org-rematch-and-replace 2 (eq dir
'up
))
3017 (org-rematch-and-replace 1 (eq dir
'left
))))
3019 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3020 ;; An internal reference
3021 (if (memq dir
'(up down
))
3022 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3023 (org-rematch-and-replace 5 (eq dir
'left
))))))
3025 (defun org-rematch-and-replace (n &optional decr hline
)
3026 "Re-match the group N, and replace it with the shifted reference."
3027 (or (match-end n
) (error "Cannot shift reference in this direction"))
3028 (goto-char (match-beginning n
))
3029 (and (looking-at (regexp-quote (match-string n
)))
3030 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3033 (defun org-table-shift-refpart (ref &optional decr hline
)
3034 "Shift a reference part REF.
3035 If DECR is set, decrease the references row/column, else increase.
3036 If HLINE is set, this may be a hline reference, it certainly is not
3037 a translation reference."
3039 (let* ((sign (string-match "^[-+]" ref
)) n
)
3041 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3043 ((and hline
(string-match "^I+" ref
))
3044 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3045 (setq n
(+ n
(if decr -
1 1)))
3046 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3048 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3050 (concat sign
(make-string n ?I
)))
3052 ((string-match "^[0-9]+" ref
)
3053 (setq n
(string-to-number (concat sign ref
)))
3054 (setq n
(+ n
(if decr -
1 1)))
3056 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3057 (number-to-string (max 1 n
))))
3059 ((string-match "^[a-zA-Z]+" ref
)
3060 (org-number-to-letters
3061 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3063 (t (error "Cannot shift reference"))))))
3065 (defun org-table-fedit-toggle-coordinates ()
3066 "Toggle the display of coordinates in the referenced table."
3068 (let ((pos (marker-position org-pos
)))
3069 (with-current-buffer (marker-buffer org-pos
)
3072 (org-table-toggle-coordinate-overlays)))))
3074 (defun org-table-fedit-finish (&optional arg
)
3075 "Parse the buffer for formula definitions and install them.
3076 With prefix ARG, apply the new formulas to the table."
3078 (org-table-remove-rectangle-highlight)
3079 (if org-table-use-standard-references
3081 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3082 (setq org-table-buffer-is-an nil
)))
3083 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3084 (goto-char (point-min))
3085 (while (re-search-forward
3086 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3088 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3089 form
(match-string 3))
3090 (setq form
(org-trim form
))
3091 (when (not (equal form
""))
3092 (while (string-match "[ \t]*\n[ \t]*" form
)
3093 (setq form
(replace-match " " t t form
)))
3094 (when (assoc var eql
)
3095 (error "Double formulas for %s" var
))
3096 (push (cons var form
) eql
)))
3098 (set-window-configuration org-window-configuration
)
3099 (select-window sel-win
)
3101 (unless (org-at-table-p)
3102 (error "Lost table position - cannot install formulas"))
3103 (org-table-store-formulas eql
)
3104 (move-marker pos nil
)
3105 (kill-buffer "*Edit Formulas*")
3107 (org-table-recalculate 'all
)
3108 (message "New formulas installed - press C-u C-c C-c to apply."))))
3110 (defun org-table-fedit-abort ()
3111 "Abort editing formulas, without installing the changes."
3113 (org-table-remove-rectangle-highlight)
3114 (let ((pos org-pos
) (sel-win org-selected-window
))
3115 (set-window-configuration org-window-configuration
)
3116 (select-window sel-win
)
3118 (move-marker pos nil
)
3119 (message "Formula editing aborted without installing changes")))
3121 (defun org-table-fedit-lisp-indent ()
3122 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3124 (let ((pos (point)) beg end ind
)
3125 (beginning-of-line 1)
3127 ((looking-at "[ \t]")
3129 (call-interactively 'lisp-indent-line
))
3130 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3131 ((not (fboundp 'pp-buffer
))
3132 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3133 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3134 (goto-char (- (match-end 0) 2))
3136 (setq ind
(make-string (current-column) ?\
))
3137 (condition-case nil
(forward-sexp 1)
3139 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3142 (narrow-to-region beg end
)
3143 (if (eq last-command this-command
)
3145 (goto-char (point-min))
3146 (setq this-command nil
)
3147 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3148 (replace-match " ")))
3150 (untabify (point-min) (point-max))
3151 (goto-char (1+ (point-min)))
3152 (while (re-search-forward "^." nil t
)
3153 (beginning-of-line 1)
3155 (goto-char (point-max))
3156 (backward-delete-char 1)))
3160 (defvar org-show-positions nil
)
3162 (defun org-table-show-reference (&optional local
)
3163 "Show the location/value of the $ expression at point."
3165 (org-table-remove-rectangle-highlight)
3167 (let ((pos (if local
(point) org-pos
))
3169 (org-inhibit-highlight-removal t
)
3170 (win (selected-window))
3171 (org-show-positions nil
)
3172 var name e what match dest
)
3173 (if local
(org-table-get-specials))
3175 ((or (org-at-regexp-p org-table-range-regexp2
)
3176 (org-at-regexp-p org-table-translate-regexp
)
3177 (org-at-regexp-p org-table-range-regexp
))
3180 (org-table-convert-refs-to-rc (match-string 0))))
3182 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3183 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3185 (t (error "No reference at point")))
3186 match
(and what
(or match
(match-string 0))))
3187 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3188 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3189 'secondary-selection
))
3190 (org-add-hook 'before-change-functions
3191 'org-table-remove-rectangle-highlight
)
3192 (if (eq what
'name
) (setq var
(substring match
1)))
3193 (when (eq what
'range
)
3194 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3195 (setq match
(org-table-formula-substitute-names match
)))
3199 (re-search-backward "^\\S-" nil t
)
3200 (beginning-of-line 1)
3201 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3204 (org-table-convert-refs-to-rc (match-string 1))))
3205 (org-table-add-rectangle-overlay
3206 (match-beginning 1) (match-end 1) face2
))))
3207 (if (and (markerp pos
) (marker-buffer pos
))
3208 (if (get-buffer-window (marker-buffer pos
))
3209 (select-window (get-buffer-window (marker-buffer pos
)))
3210 (org-switch-to-buffer-other-window (get-buffer-window
3211 (marker-buffer pos
)))))
3213 (org-table-force-dataline)
3215 (setq name
(substring dest
1))
3217 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3218 (setq e
(assoc name org-table-named-field-locations
))
3219 (org-goto-line (nth 1 e
))
3220 (org-table-goto-column (nth 2 e
)))
3221 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3222 (let ((l (string-to-number (match-string 1 dest
)))
3223 (c (string-to-number (match-string 2 dest
))))
3224 (org-goto-line (aref org-table-dlines l
))
3225 (org-table-goto-column c
)))
3226 (t (org-table-goto-column (string-to-number name
))))
3227 (move-marker pos
(point))
3228 (org-table-highlight-rectangle nil nil face2
))
3230 ((equal dest match
))
3235 (org-table-get-range match nil nil
'highlight
))
3237 ((setq e
(assoc var org-table-named-field-locations
))
3238 (org-goto-line (nth 1 e
))
3239 (org-table-goto-column (nth 2 e
))
3240 (org-table-highlight-rectangle (point) (point))
3241 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3242 ((setq e
(assoc var org-table-column-names
))
3243 (org-table-goto-column (string-to-number (cdr e
)))
3244 (org-table-highlight-rectangle (point) (point))
3245 (goto-char (org-table-begin))
3246 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3249 (goto-char (match-beginning 1))
3250 (org-table-highlight-rectangle)
3251 (message "Named column (column %s)" (cdr e
)))
3252 (error "Column name not found")))
3255 (org-table-goto-column (string-to-number (substring match
1)))
3256 (org-table-highlight-rectangle (point) (point))
3257 (message "Column %s" (substring match
1)))
3258 ((setq e
(assoc var org-table-local-parameters
))
3259 (goto-char (org-table-begin))
3260 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3262 (goto-char (match-beginning 1))
3263 (org-table-highlight-rectangle)
3264 (message "Local parameter."))
3265 (error "Parameter not found")))
3268 ((not var
) (error "No reference at point"))
3269 ((setq e
(assoc var org-table-formula-constants-local
))
3270 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3272 ((setq e
(assoc var org-table-formula-constants
))
3273 (message "Constant: $%s=%s in `org-table-formula-constants'."
3275 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3276 (message "Constant: $%s=%s, from `constants.el'%s."
3277 var e
(format " (%s units)" constants-unit-system
)))
3278 (t (error "Undefined name $%s" var
)))))
3280 (when (and org-show-positions
3281 (not (memq this-command
'(org-table-fedit-scroll
3282 org-table-fedit-scroll-down
))))
3283 (push pos org-show-positions
)
3284 (push org-table-current-begin-pos org-show-positions
)
3285 (let ((min (apply 'min org-show-positions
))
3286 (max (apply 'max org-show-positions
)))
3287 (goto-char min
) (recenter 0)
3289 (or (pos-visible-in-window-p max
) (recenter -
1))))
3290 (select-window win
))))
3292 (defun org-table-force-dataline ()
3293 "Make sure the cursor is in a dataline in a table."
3294 (unless (save-excursion
3295 (beginning-of-line 1)
3296 (looking-at org-table-dataline-regexp
))
3297 (let* ((re org-table-dataline-regexp
)
3298 (p1 (save-excursion (re-search-forward re nil
'move
)))
3299 (p2 (save-excursion (re-search-backward re nil
'move
))))
3301 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3303 ((or p1 p2
) (goto-char (or p1 p2
)))
3304 (t (error "No table dataline around here"))))))
3306 (defun org-table-fedit-line-up ()
3307 "Move cursor one line up in the window showing the table."
3309 (org-table-fedit-move 'previous-line
))
3311 (defun org-table-fedit-line-down ()
3312 "Move cursor one line down in the window showing the table."
3314 (org-table-fedit-move 'next-line
))
3316 (defun org-table-fedit-move (command)
3317 "Move the cursor in the window showing the table.
3318 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3319 (let ((org-table-allow-automatic-line-recalculation nil
)
3320 (pos org-pos
) (win (selected-window)) p
)
3321 (select-window (get-buffer-window (marker-buffer org-pos
)))
3323 (call-interactively command
)
3324 (while (and (org-at-table-p)
3325 (org-at-table-hline-p))
3326 (call-interactively command
))
3327 (or (org-at-table-p) (goto-char p
))
3328 (move-marker pos
(point))
3329 (select-window win
)))
3331 (defun org-table-fedit-scroll (N)
3333 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3334 (scroll-other-window N
)))
3336 (defun org-table-fedit-scroll-down (N)
3338 (org-table-fedit-scroll (- N
)))
3340 (defvar org-table-rectangle-overlays nil
)
3342 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3343 "Add a new overlay."
3344 (let ((ov (make-overlay beg end
)))
3345 (overlay-put ov
'face
(or face
'secondary-selection
))
3346 (push ov org-table-rectangle-overlays
)))
3348 (defun org-table-highlight-rectangle (&optional beg end face
)
3349 "Highlight rectangular region in a table."
3350 (setq beg
(or beg
(point)) end
(or end
(point)))
3351 (let ((b (min beg end
))
3354 (and (boundp 'org-show-positions
)
3355 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3356 (goto-char (min beg end
))
3357 (setq l1
(org-current-line)
3358 c1
(org-table-current-column))
3359 (goto-char (max beg end
))
3360 (setq l2
(org-current-line)
3361 c2
(org-table-current-column))
3362 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3364 (beginning-of-line 1)
3365 (loop for line from l1 to l2 do
3366 (when (looking-at org-table-dataline-regexp
)
3367 (org-table-goto-column c1
)
3368 (skip-chars-backward "^|\n") (setq beg
(point))
3369 (org-table-goto-column c2
)
3370 (skip-chars-forward "^|\n") (setq end
(point))
3371 (org-table-add-rectangle-overlay beg end face
))
3372 (beginning-of-line 2))
3374 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3376 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3377 "Remove the rectangle overlays."
3378 (unless org-inhibit-highlight-removal
3379 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3380 (mapc 'delete-overlay org-table-rectangle-overlays
)
3381 (setq org-table-rectangle-overlays nil
)))
3383 (defvar org-table-coordinate-overlays nil
3384 "Collects the coordinate grid overlays, so that they can be removed.")
3385 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3387 (defun org-table-overlay-coordinates ()
3388 "Add overlays to the table at point, to show row/column coordinates."
3390 (mapc 'delete-overlay org-table-coordinate-overlays
)
3391 (setq org-table-coordinate-overlays nil
)
3393 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3394 (goto-char (org-table-begin))
3395 (while (org-at-table-p)
3396 (setq eol
(point-at-eol))
3397 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
3398 (push ov org-table-coordinate-overlays
)
3399 (setq hline
(looking-at org-table-hline-regexp
))
3400 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3401 (format "%4d" (setq id
(1+ id
)))))
3402 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3405 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3406 (setq beg
(1+ (match-beginning 0))
3408 s1
(concat "$" (int-to-string ic
))
3409 s2
(org-number-to-letters ic
)
3410 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3411 (setq ov
(make-overlay beg
(+ beg
(length str
))))
3412 (push ov org-table-coordinate-overlays
)
3413 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3414 (beginning-of-line 2)))))
3416 (defun org-table-toggle-coordinate-overlays ()
3417 "Toggle the display of Row/Column numbers in tables."
3419 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3420 (message "Row/Column number display turned %s"
3421 (if org-table-overlay-coordinates
"on" "off"))
3422 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3424 (unless org-table-overlay-coordinates
3425 (mapc 'delete-overlay org-table-coordinate-overlays
)
3426 (setq org-table-coordinate-overlays nil
)))
3428 (defun org-table-toggle-formula-debugger ()
3429 "Toggle the formula debugger in tables."
3431 (setq org-table-formula-debug
(not org-table-formula-debug
))
3432 (message "Formula debugging has been turned %s"
3433 (if org-table-formula-debug
"on" "off")))
3435 ;;; The orgtbl minor mode
3437 ;; Define a minor mode which can be used in other modes in order to
3438 ;; integrate the org-mode table editor.
3440 ;; This is really a hack, because the org-mode table editor uses several
3441 ;; keys which normally belong to the major mode, for example the TAB and
3442 ;; RET keys. Here is how it works: The minor mode defines all the keys
3443 ;; necessary to operate the table editor, but wraps the commands into a
3444 ;; function which tests if the cursor is currently inside a table. If that
3445 ;; is the case, the table editor command is executed. However, when any of
3446 ;; those keys is used outside a table, the function uses `key-binding' to
3447 ;; look up if the key has an associated command in another currently active
3448 ;; keymap (minor modes, major mode, global), and executes that command.
3449 ;; There might be problems if any of the keys used by the table editor is
3450 ;; otherwise used as a prefix key.
3452 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3453 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3454 ;; addresses this by checking explicitly for both bindings.
3456 ;; The optimized version (see variable `orgtbl-optimized') takes over
3457 ;; all keys which are bound to `self-insert-command' in the *global map*.
3458 ;; Some modes bind other commands to simple characters, for example
3459 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3460 ;; active, this binding is ignored inside tables and replaced with a
3461 ;; modified self-insert.
3464 (defvar orgtbl-mode-map
(make-keymap)
3465 "Keymap for `orgtbl-mode'.")
3468 (defun turn-on-orgtbl ()
3469 "Unconditionally turn on `orgtbl-mode'."
3472 (defvar org-old-auto-fill-inhibit-regexp nil
3473 "Local variable used by `orgtbl-mode'.")
3475 (defconst orgtbl-line-start-regexp
3476 "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\|TBLNAME\\):\\)"
3477 "Matches a line belonging to an orgtbl.")
3479 (defconst orgtbl-extra-font-lock-keywords
3480 (list (list (concat "^" orgtbl-line-start-regexp
".*")
3481 0 (quote 'org-table
) 'prepend
))
3482 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
3484 ;; Install it as a minor mode.
3485 (put 'orgtbl-mode
:included t
)
3486 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
3489 (define-minor-mode orgtbl-mode
3490 "The `org-mode' table editor as a minor mode for use in other modes."
3491 :lighter
" OrgTbl" :keymap orgtbl-mode-map
3492 (org-load-modules-maybe)
3495 ;; Exit without error, in case some hook functions calls this
3496 ;; by accident in org-mode.
3497 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
3499 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
3500 ;; Make sure we are first in minor-mode-map-alist
3501 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
3502 ;; FIXME: maybe it should use emulation-mode-map-alists?
3503 (and c
(setq minor-mode-map-alist
3504 (cons c
(delq c minor-mode-map-alist
)))))
3505 (org-set-local (quote org-table-may-need-update
) t
)
3506 (org-add-hook 'before-change-functions
'org-before-change-function
3508 (org-set-local 'org-old-auto-fill-inhibit-regexp
3509 auto-fill-inhibit-regexp
)
3510 (org-set-local 'auto-fill-inhibit-regexp
3511 (if auto-fill-inhibit-regexp
3512 (concat orgtbl-line-start-regexp
"\\|"
3513 auto-fill-inhibit-regexp
)
3514 orgtbl-line-start-regexp
))
3515 (add-to-invisibility-spec '(org-cwidth))
3516 (when (fboundp 'font-lock-add-keywords
)
3517 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
3518 (org-restart-font-lock))
3519 (easy-menu-add orgtbl-mode-menu
))
3521 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
3522 (org-table-cleanup-narrow-column-properties)
3523 (org-remove-from-invisibility-spec '(org-cwidth))
3524 (remove-hook 'before-change-functions
'org-before-change-function t
)
3525 (when (fboundp 'font-lock-remove-keywords
)
3526 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
3527 (org-restart-font-lock))
3528 (easy-menu-remove orgtbl-mode-menu
)
3529 (force-mode-line-update 'all
))))
3531 (defun org-table-cleanup-narrow-column-properties ()
3532 "Remove all properties related to narrow-column invisibility."
3534 (while (setq s
(text-property-any s
(point-max)
3535 'display org-narrow-column-arrow
))
3536 (remove-text-properties s
(1+ s
) '(display t
)))
3538 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
3539 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
3541 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
3542 (remove-text-properties s
(1+ s
) '(invisible t
)))))
3544 (defun orgtbl-make-binding (fun n
&rest keys
)
3545 "Create a function for binding in the table minor mode.
3546 FUN is the command to call inside a table. N is used to create a unique
3547 command name. KEYS are keys that should be checked in for a command
3548 to execute outside of tables."
3551 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
3553 (concat "In tables, run `" (symbol-name fun
) "'.\n"
3554 "Outside of tables, run the binding of `"
3555 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
3560 (list 'call-interactively
(list 'quote fun
))
3561 (list 'let
'(orgtbl-mode)
3562 (list 'call-interactively
3565 (list 'key-binding k
))
3567 '('orgtbl-error
))))))))
3569 (defun orgtbl-error ()
3570 "Error when there is no default binding for a table key."
3572 (error "This key has no function outside tables"))
3574 (defun orgtbl-setup ()
3575 "Setup orgtbl keymaps."
3578 '(([(meta shift left
)] org-table-delete-column
)
3579 ([(meta left
)] org-table-move-column-left
)
3580 ([(meta right
)] org-table-move-column-right
)
3581 ([(meta shift right
)] org-table-insert-column
)
3582 ([(meta shift up
)] org-table-kill-row
)
3583 ([(meta shift down
)] org-table-insert-row
)
3584 ([(meta up
)] org-table-move-row-up
)
3585 ([(meta down
)] org-table-move-row-down
)
3586 ("\C-c\C-w" org-table-cut-region
)
3587 ("\C-c\M-w" org-table-copy-region
)
3588 ("\C-c\C-y" org-table-paste-rectangle
)
3589 ("\C-c-" org-table-insert-hline
)
3590 ("\C-c}" org-table-toggle-coordinate-overlays
)
3591 ("\C-c{" org-table-toggle-formula-debugger
)
3592 ("\C-m" org-table-next-row
)
3593 ([(shift return
)] org-table-copy-down
)
3594 ("\C-c?" org-table-field-info
)
3595 ("\C-c " org-table-blank-field
)
3596 ("\C-c+" org-table-sum
)
3597 ("\C-c=" org-table-eval-formula
)
3598 ("\C-c'" org-table-edit-formulas
)
3599 ("\C-c`" org-table-edit-field
)
3600 ("\C-c*" org-table-recalculate
)
3601 ("\C-c^" org-table-sort-lines
)
3602 ("\M-a" org-table-beginning-of-field
)
3603 ("\M-e" org-table-end-of-field
)
3604 ([(control ?
#)] org-table-rotate-recalc-marks
)))
3606 (while (setq elt
(pop bindings
))
3607 (setq nfunc
(1+ nfunc
))
3608 (setq key
(org-key (car elt
))
3610 cmd
(orgtbl-make-binding fun nfunc key
))
3611 (org-defkey orgtbl-mode-map key cmd
))
3613 ;; Special treatment needed for TAB and RET
3614 (org-defkey orgtbl-mode-map
[(return)]
3615 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
3616 (org-defkey orgtbl-mode-map
"\C-m"
3617 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
3619 (org-defkey orgtbl-mode-map
[(tab)]
3620 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
3621 (org-defkey orgtbl-mode-map
"\C-i"
3622 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
3624 (org-defkey orgtbl-mode-map
[(shift tab
)]
3625 (orgtbl-make-binding 'org-table-previous-field
104
3626 [(shift tab
)] [(tab)] "\C-i"))
3629 (unless (featurep 'xemacs
)
3630 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
3631 (orgtbl-make-binding 'org-table-previous-field
107
3632 [S-iso-lefttab
] [backtab] [(shift tab)]
3635 (org-defkey orgtbl-mode-map [backtab]
3636 (orgtbl-make-binding 'org-table-previous-field
108
3637 [backtab] [S-iso-lefttab] [(shift tab)]
3640 (org-defkey orgtbl-mode-map "\M-\C-m"
3641 (orgtbl-make-binding 'org-table-wrap-region 105
3642 "\M-\C-m" [(meta return)]))
3643 (org-defkey orgtbl-mode-map [(meta return)]
3644 (orgtbl-make-binding 'org-table-wrap-region 106
3645 [(meta return)] "\M-\C-m"))
3647 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
3648 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
3650 (when orgtbl-optimized
3651 ;; If the user wants maximum table support, we need to hijack
3652 ;; some standard editing functions
3653 (org-remap orgtbl-mode-map
3654 'self-insert-command 'orgtbl-self-insert-command
3655 'delete-char 'org-delete-char
3656 'delete-backward-char 'org-delete-backward-char)
3657 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
3658 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
3660 ["Create or convert" org-table-create-or-convert-from-region
3661 :active (not (org-at-table-p)) :keys "C-c |" ]
3663 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
3664 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
3665 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
3666 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
3668 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
3669 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
3670 ["Copy Field from Above"
3671 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
3674 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
3675 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
3676 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
3677 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
3679 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
3680 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
3681 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
3682 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
3683 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
3685 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
3687 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
3688 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
3689 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
3690 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
3693 ["Insert table template" orgtbl-insert-radio-table
3694 (assq major-mode orgtbl-radio-table-templates)]
3695 ["Comment/uncomment table" orgtbl-toggle-comment t])
3697 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
3698 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
3699 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
3700 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
3701 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
3702 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
3703 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
3704 ["Sum Column/Rectangle" org-table-sum
3705 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
3706 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
3708 org-table-toggle-formula-debugger :active (org-at-table-p)
3710 :style toggle :selected org-table-formula-debug]
3711 ["Show Col/Row Numbers"
3712 org-table-toggle-coordinate-overlays :active (org-at-table-p)
3714 :style toggle :selected org-table-overlay-coordinates]
3718 (defun orgtbl-ctrl-c-ctrl-c (arg)
3719 "If the cursor is inside a table, realign the table.
3720 If it is a table to be sent away to a receiver, do it.
3721 With prefix arg, also recompute table."
3723 (let ((pos (point)) action)
3725 (beginning-of-line 1)
3726 (setq action (cond ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
3727 ((looking-at "[ \t]*|") pos)
3728 ((looking-at "[ \t]*#\\+TBLFM:") 'recalc))))
3732 (org-table-maybe-eval-formula)
3734 (call-interactively 'org-table-recalculate)
3735 (org-table-maybe-recalculate-line))
3736 (call-interactively 'org-table-align)
3737 (when (orgtbl-send-table 'maybe)
3738 (run-hooks 'orgtbl-after-send-table-hook)))
3739 ((eq action 'recalc)
3741 (beginning-of-line 1)
3742 (skip-chars-backward " \r\n\t")
3743 (if (org-at-table-p)
3744 (org-call-with-arg 'org-table-recalculate t))))
3745 (t (let (orgtbl-mode)
3746 (call-interactively (key-binding "\C-c\C-c")))))))
3748 (defun orgtbl-create-or-convert-from-region (arg)
3749 "Create table or convert region to table, if no conflicting binding.
3750 This installs the table binding `C-c |', but only if there is no
3751 conflicting binding to this key outside orgtbl-mode."
3753 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
3755 (call-interactively cmd)
3756 (call-interactively 'org-table-create-or-convert-from-region))))
3758 (defun orgtbl-tab (arg)
3759 "Justification and field motion for `orgtbl-mode'."
3761 (if arg (org-table-edit-field t)
3762 (org-table-justify-field-maybe)
3763 (org-table-next-field)))
3765 (defun orgtbl-ret ()
3766 "Justification and field motion for `orgtbl-mode'."
3770 (org-table-justify-field-maybe)
3771 (org-table-next-row)))
3773 (defun orgtbl-self-insert-command (N)
3774 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
3775 If the cursor is in a table looking at whitespace, the whitespace is
3776 overwritten, and the table is not marked as requiring realignment."
3778 (if (and (org-at-table-p)
3780 (and org-table-auto-blank-field
3781 (member last-command
3782 '(orgtbl-hijacker-command-100
3783 orgtbl-hijacker-command-101
3784 orgtbl-hijacker-command-102
3785 orgtbl-hijacker-command-103
3786 orgtbl-hijacker-command-104
3787 orgtbl-hijacker-command-105
3789 (org-table-blank-field))
3792 (looking-at "[^|\n]* +|"))
3793 (let (org-table-may-need-update)
3794 (goto-char (1- (match-end 0)))
3795 (delete-backward-char 1)
3796 (goto-char (match-beginning 0))
3797 (self-insert-command N))
3798 (setq org-table-may-need-update t)
3801 (cmd (or (key-binding
3802 (or (and (listp function-key-map)
3803 (setq a (assoc last-input-event function-key-map))
3805 (vector last-input-event)))
3806 'self-insert-command)))
3807 (call-interactively cmd)
3808 (if (and org-self-insert-cluster-for-undo
3809 (eq cmd 'self-insert-command))
3810 (if (not (eq last-command 'orgtbl-self-insert-command))
3811 (setq org-self-insert-command-undo-counter 1)
3812 (if (>= org-self-insert-command-undo-counter 20)
3813 (setq org-self-insert-command-undo-counter 1)
3814 (and (> org-self-insert-command-undo-counter 0)
3816 (not (cadr buffer-undo-list)) ; remove nil entry
3817 (setcdr buffer-undo-list (cddr buffer-undo-list)))
3818 (setq org-self-insert-command-undo-counter
3819 (1+ org-self-insert-command-undo-counter))))))))
3821 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
3822 "Regular expression matching exponentials as produced by calc.")
3824 (defun orgtbl-export (table target)
3826 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
3827 (lines (org-split-string table "[ \t]*\n[ \t]*"))
3828 org-table-last-alignment org-table-last-column-widths
3830 (if (not (fboundp func))
3831 (error "Cannot export orgtbl table to %s" target))
3832 (setq lines (org-table-clean-before-export lines))
3836 (if (string-match org-table-hline-regexp x)
3838 (org-split-string (org-trim x) "\\s-*|\\s-*")))
3840 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
3842 (loop for i from (1- maxcol) downto 0 do
3843 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
3844 (setq column (delq nil column))
3845 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
3846 (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))
3847 (funcall func table nil)))
3849 (defun orgtbl-gather-send-defs ()
3850 "Gather a plist of :name, :transform, :params for each destination before
3853 (goto-char (org-table-begin))
3855 (beginning-of-line 0)
3856 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
3857 (let ((name (org-no-properties (match-string 1)))
3858 (transform (intern (match-string 2)))
3859 (params (if (match-end 3)
3860 (read (concat "(" (match-string 3) ")")))))
3861 (push (list :name name :transform transform :params params)
3863 (beginning-of-line 0)))
3866 (defun orgtbl-send-replace-tbl (name txt)
3867 "Find and replace table NAME with TXT."
3869 (goto-char (point-min))
3870 (unless (re-search-forward
3871 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
3872 (error "Don't know where to insert translated table"))
3873 (goto-char (match-beginning 0))
3874 (beginning-of-line 2)
3876 (let ((beg (point)))
3877 (unless (re-search-forward
3878 (concat "END RECEIVE ORGTBL +" name) nil t)
3879 (error "Cannot find end of insertion region"))
3880 (beginning-of-line 1)
3881 (delete-region beg (point))))
3885 (defun org-table-to-lisp (&optional txt)
3886 "Convert the table at point to a Lisp structure.
3887 The structure will be a list. Each item is either the symbol `hline'
3888 for a horizontal separator line, or a list of field values as strings.
3889 The table is taken from the parameter TXT, or from the buffer at point."
3891 (unless (org-at-table-p)
3892 (error "No table at point")))
3894 (buffer-substring-no-properties (org-table-begin)
3896 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
3900 (if (string-match org-table-hline-regexp x)
3902 (org-split-string (org-trim x) "\\s-*|\\s-*")))
3905 (defun orgtbl-send-table (&optional maybe)
3906 "Send a transformed version of this table to the receiver position.
3907 With argument MAYBE, fail quietly if no transformation is defined for
3911 (unless (org-at-table-p) (error "Not at a table"))
3912 ;; when non-interactive, we assume align has just happened.
3913 (when (interactive-p) (org-table-align))
3914 (let ((dests (orgtbl-gather-send-defs))
3915 (txt (buffer-substring-no-properties (org-table-begin)
3918 (unless dests (if maybe (throw 'exit nil)
3919 (error "Don't know how to transform this table")))
3920 (dolist (dest dests)
3921 (let* ((name (plist-get dest :name))
3922 (transform (plist-get dest :transform))
3923 (params (plist-get dest :params))
3924 (skip (plist-get params :skip))
3925 (skipcols (plist-get params :skipcols))
3927 (lines (org-table-clean-before-export
3929 (org-split-string txt "[ \t]*\n[ \t]*"))))
3930 (i0 (if org-table-clean-did-remove-column 2 1))
3933 (if (string-match org-table-hline-regexp x)
3935 (org-remove-by-index
3936 (org-split-string (org-trim x) "\\s-*|\\s-*")
3939 (fun (if (= i0 2) 'cdr 'identity))
3940 (org-table-last-alignment
3941 (org-remove-by-index (funcall fun org-table-last-alignment)
3943 (org-table-last-column-widths
3944 (org-remove-by-index (funcall fun org-table-last-column-widths)
3946 (txt (if (fboundp transform)
3947 (funcall transform table params)
3948 (error "No such transformation function %s" transform))))
3949 (orgtbl-send-replace-tbl name txt))
3950 (setq ntbl (1+ ntbl)))
3951 (message "Table converted and installed at %d receiver location%s"
3952 ntbl (if (> ntbl 1) "s" ""))
3957 (defun org-remove-by-index (list indices &optional i0)
3958 "Remove the elements in LIST with indices in INDICES.
3959 First element has index 0, or I0 if given."
3962 (if (integerp indices) (setq indices (list indices)))
3963 (setq i0 (1- (or i0 0)))
3964 (delq :rm (mapcar (lambda (x)
3966 (if (memq i0 indices) :rm x))
3969 (defun orgtbl-toggle-comment ()
3970 "Comment or uncomment the orgtbl at point."
3972 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
3973 (re2 (concat "^" orgtbl-line-start-regexp))
3974 (commented (save-excursion (beginning-of-line 1)
3975 (cond ((looking-at re1) t)
3976 ((looking-at re2) nil)
3977 (t (error "Not at an org table")))))
3978 (re (if commented re1 re2))
3981 (beginning-of-line 1)
3982 (while (looking-at re) (beginning-of-line 0))
3983 (beginning-of-line 2)
3985 (while (looking-at re) (beginning-of-line 2))
3987 (comment-region beg end (if commented '(4) nil))))
3989 (defun orgtbl-insert-radio-table ()
3990 "Insert a radio table template appropriate for this major mode."
3992 (let* ((e (assq major-mode orgtbl-radio-table-templates))
3995 (unless e (error "No radio table setup defined for %s" major-mode))
3996 (setq name (read-string "Table name: "))
3997 (while (string-match "%n" txt)
3998 (setq txt (replace-match name t t txt)))
3999 (or (bolp) (insert "\n"))
4004 ;; Dynamically bound input and output for table formatting.
4005 (defvar *orgtbl-table* nil
4006 "Carries the current table through formatting routines.")
4007 (defvar *orgtbl-rtn* nil
4008 "Formatting routines push the output lines here.")
4009 ;; Formatting parameters for the current table section.
4010 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4011 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4012 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4013 (defvar *orgtbl-fmt* nil "Format for each entry.")
4014 (defvar *orgtbl-efmt* nil "Format for numbers.")
4015 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4016 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4017 (defvar *orgtbl-lstart* nil "Text starting a row.")
4018 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4019 (defvar *orgtbl-lend* nil "Text ending a row.")
4020 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4022 (defsubst orgtbl-get-fmt (fmt i)
4023 "Retrieve the format from FMT corresponding to the Ith column."
4024 (if (and (not (functionp fmt)) (consp fmt))
4028 (defsubst orgtbl-apply-fmt (fmt &rest args)
4029 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4030 (cond ((functionp fmt) (apply fmt args))
4031 (fmt (apply 'format fmt args))
4035 (defsubst orgtbl-eval-str (str)
4036 "If STR is a function, evaluate it with no arguments."
4041 (defun orgtbl-format-line (line)
4042 "Format LINE as a table row."
4043 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4049 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4050 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4051 (orgtbl-apply-fmt efmt (match-string 1 f)
4054 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4055 *orgtbl-default-fmt*)
4058 (push (if *orgtbl-lfmt*
4059 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4060 (concat (orgtbl-eval-str *orgtbl-lstart*)
4061 (mapconcat 'identity line *orgtbl-sep*)
4062 (orgtbl-eval-str *orgtbl-lend*)))
4065 (defun orgtbl-format-section (section-stopper)
4066 "Format lines until the first occurrence of SECTION-STOPPER."
4069 (while (not (eq (car *orgtbl-table*) section-stopper))
4070 (if prevline (orgtbl-format-line prevline))
4071 (setq prevline (pop *orgtbl-table*)))
4072 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4073 (*orgtbl-lend* *orgtbl-llend*)
4074 (*orgtbl-lfmt* *orgtbl-llfmt*))
4075 (orgtbl-format-line prevline))))))
4077 (defun orgtbl-to-generic (table params)
4078 "Convert the orgtbl-mode TABLE to some other format.
4079 This generic routine can be used for many standard cases.
4080 TABLE is a list, each entry either the symbol `hline' for a horizontal
4081 separator line, or a list of fields for that line.
4082 PARAMS is a property list of parameters that can influence the conversion.
4083 For the generic converter, some parameters are obligatory: You need to
4084 specify either :lfmt, or all of (:lstart :lend :sep).
4086 Valid parameters are
4088 :splice When set to t, return only table body lines, don't wrap
4089 them into :tstart and :tend. Default is nil. When :splice
4090 is non-nil, this also means that the exporter should not look
4091 for and interpret header and footer sections.
4093 :hline String to be inserted on horizontal separation lines.
4094 May be nil to ignore hlines.
4096 :sep Separator between two fields
4097 :remove-nil-lines Do not include lines that evaluate to nil.
4100 Each in the following group may be either a string or a function
4101 of no arguments returning a string:
4102 :tstart String to start the table. Ignored when :splice is t.
4103 :tend String to end the table. Ignored when :splice is t.
4104 :lstart String to start a new table line.
4105 :llstart String to start the last table line, defaults to :lstart.
4106 :lend String to end a table line
4107 :llend String to end the last table line, defaults to :lend.
4109 Each in the following group may be a string, a function of one
4110 argument (the field or line) returning a string, or a plist
4111 mapping columns to either of the above:
4112 :lfmt Format for entire line, with enough %s to capture all fields.
4113 If this is present, :lstart, :lend, and :sep are ignored.
4114 :llfmt Format for the entire last line, defaults to :lfmt.
4115 :fmt A format to be used to wrap the field, should contain
4116 %s for the original field value. For example, to wrap
4117 everything in dollars, you could use :fmt \"$%s$\".
4118 This may also be a property list with column numbers and
4119 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4121 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4122 Same as above, specific for the header lines in the table.
4123 All lines before the first hline are treated as header.
4124 If any of these is not present, the data line value is used.
4126 This may be either a string or a function of two arguments:
4127 :efmt Use this format to print numbers with exponentials.
4128 The format should have %s twice for inserting mantissa
4129 and exponent, for example \"%s\\\\times10^{%s}\". This
4130 may also be a property list with column numbers and
4131 formats. :fmt will still be applied after :efmt.
4133 In addition to this, the parameters :skip and :skipcols are always handled
4134 directly by `orgtbl-send-table'. See manual."
4137 (let* ((splicep (plist-get params :splice))
4138 (hline (plist-get params :hline))
4139 (remove-nil-linesp (plist-get params :remove-nil-lines))
4140 (remove-newlines (plist-get params :remove-newlines))
4141 (*orgtbl-hline* hline)
4142 (*orgtbl-table* table)
4143 (*orgtbl-sep* (plist-get params :sep))
4144 (*orgtbl-efmt* (plist-get params :efmt))
4145 (*orgtbl-lstart* (plist-get params :lstart))
4146 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4147 (*orgtbl-lend* (plist-get params :lend))
4148 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4149 (*orgtbl-lfmt* (plist-get params :lfmt))
4150 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4151 (*orgtbl-fmt* (plist-get params :fmt))
4156 (when (plist-member params :tstart)
4157 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4158 (if tstart (push tstart *orgtbl-rtn*)))))
4160 ;; Do we have a heading section? If so, format it and handle the
4162 (if (and (not splicep)
4163 (or (consp (car *orgtbl-table*))
4164 (consp (nth 1 *orgtbl-table*)))
4165 (memq 'hline (cdr *orgtbl-table*)))
4167 (when (eq 'hline (car *orgtbl-table*))
4168 ;; there is a hline before the first data line
4169 (and hline (push hline *orgtbl-rtn*))
4170 (pop *orgtbl-table*))
4171 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4173 (*orgtbl-llstart* (or (plist-get params :hllstart)
4175 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4176 (*orgtbl-llend* (or (plist-get params :hllend)
4177 (plist-get params :hlend) *orgtbl-llend*))
4178 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4179 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4180 (plist-get params :hlfmt) *orgtbl-llfmt*))
4181 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4182 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4183 (orgtbl-format-section 'hline))
4184 (if hline (push hline *orgtbl-rtn*))
4185 (pop *orgtbl-table*)))
4187 ;; Now format the main section.
4188 (orgtbl-format-section nil)
4191 (when (plist-member params :tend)
4192 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4193 (if tend (push tend *orgtbl-rtn*)))))
4195 (mapconcat (if remove-newlines
4197 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4199 (nreverse (if remove-nil-linesp
4200 (remq nil *orgtbl-rtn*)
4201 *orgtbl-rtn*)) "\n")))
4203 (defun orgtbl-to-tsv (table params)
4204 "Convert the orgtbl-mode table to TAB separated material."
4205 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4206 (defun orgtbl-to-csv (table params)
4207 "Convert the orgtbl-mode table to CSV material.
4208 This does take care of the proper quoting of fields with comma or quotes."
4209 (orgtbl-to-generic table (org-combine-plists
4210 '(:sep "," :fmt org-quote-csv-field)
4213 (defun orgtbl-to-latex (table params)
4214 "Convert the orgtbl-mode TABLE to LaTeX.
4215 TABLE is a list, each entry either the symbol `hline' for a horizontal
4216 separator line, or a list of fields for that line.
4217 PARAMS is a property list of parameters that can influence the conversion.
4218 Supports all parameters from `orgtbl-to-generic'. Most important for
4221 :splice When set to t, return only table body lines, don't wrap
4222 them into a tabular environment. Default is nil.
4224 :fmt A format to be used to wrap the field, should contain %s for the
4225 original field value. For example, to wrap everything in dollars,
4226 use :fmt \"$%s$\". This may also be a property list with column
4227 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4228 The format may also be a function that formats its one argument.
4230 :efmt Format for transforming numbers with exponentials. The format
4231 should have %s twice for inserting mantissa and exponent, for
4232 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4233 This may also be a property list with column numbers and formats.
4234 The format may also be a function that formats its two arguments.
4236 :llend If you find too much space below the last line of a table,
4237 pass a value of \"\" for :llend to suppress the final \\\\.
4239 The general parameters :skip and :skipcols have already been applied when
4240 this function is called."
4241 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4242 org-table-last-alignment ""))
4245 :tstart (concat "\\begin{tabular}{" alignment "}")
4246 :tend "\\end{tabular}"
4247 :lstart "" :lend " \\\\" :sep " & "
4248 :efmt "%s\\,(%s)" :hline "\\hline")))
4249 (orgtbl-to-generic table (org-combine-plists params2 params))))
4251 (defun orgtbl-to-html (table params)
4252 "Convert the orgtbl-mode TABLE to HTML.
4253 TABLE is a list, each entry either the symbol `hline' for a horizontal
4254 separator line, or a list of fields for that line.
4255 PARAMS is a property list of parameters that can influence the conversion.
4256 Currently this function recognizes the following parameters:
4258 :splice When set to t, return only table body lines, don't wrap
4259 them into a <table> environment. Default is nil.
4261 The general parameters :skip and :skipcols have already been applied when
4262 this function is called. The function does *not* use `orgtbl-to-generic',
4263 so you cannot specify parameters for it."
4264 (let* ((splicep (plist-get params :splice))
4265 (html-table-tag org-export-html-table-tag)
4267 ;; Just call the formatter we already have
4268 ;; We need to make text lines for it, so put the fields back together.
4269 (setq html (org-format-org-table-html
4274 (concat "| " (mapconcat 'org-html-expand x " | ") " |")))
4277 (if (string-match "\n+\\'" html)
4278 (setq html (replace-match "" t t html)))
4281 (defun orgtbl-to-texinfo (table params)
4282 "Convert the orgtbl-mode TABLE to TeXInfo.
4283 TABLE is a list, each entry either the symbol `hline' for a horizontal
4284 separator line, or a list of fields for that line.
4285 PARAMS is a property list of parameters that can influence the conversion.
4286 Supports all parameters from `orgtbl-to-generic'. Most important for
4289 :splice nil/t When set to t, return only table body lines, don't wrap
4290 them into a multitable environment. Default is nil.
4292 :fmt fmt A format to be used to wrap the field, should contain
4293 %s for the original field value. For example, to wrap
4294 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4295 This may also be a property list with column numbers and
4296 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4297 Each format also may be a function that formats its one
4300 :cf \"f1 f2..\" The column fractions for the table. By default these
4301 are computed automatically from the width of the columns
4304 The general parameters :skip and :skipcols have already been applied when
4305 this function is called."
4306 (let* ((total (float (apply '+ org-table-last-column-widths)))
4307 (colfrac (or (plist-get params :cf)
4309 (lambda (x) (format "%.3f" (/ (float x) total)))
4310 org-table-last-column-widths " ")))
4313 :tstart (concat "@multitable @columnfractions " colfrac)
4314 :tend "@end multitable"
4315 :lstart "@item " :lend "" :sep " @tab "
4316 :hlstart "@headitem ")))
4317 (orgtbl-to-generic table (org-combine-plists params2 params))))
4319 (defun orgtbl-to-orgtbl (table params)
4320 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4321 Useful when slicing one table into many. The :hline, :sep,
4322 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4323 and :tend suppress strings without splicing; they can be set to
4324 provide ORGTBL directives for the generated table."
4328 :tstart nil :tend nil
4333 (params (org-combine-plists params2 params)))
4334 (orgtbl-to-generic table params)))
4336 (defun org-table-get-remote-range (name-or-id form)
4337 "Get a field value or a list of values in a range from table at ID.
4339 NAME-OR-ID may be the name of a table in the current file as set by
4340 a \"#+TBLNAME:\" directive. The first table following this line
4341 will then be used. Alternatively, it may be an ID referring to
4342 any entry, also in a different file. In this case, the first table
4343 in that entry will be referenced.
4344 FORM is a field or range descriptor like \"@2$3\" or or \"B3\" or
4345 \"@I$2..@II$2\". All the references must be absolute, not relative.
4347 The return value is either a single string for a single field, or a
4348 list of the fields in the rectangle ."
4351 org-table-column-names org-table-column-name-regexp
4352 org-table-local-parameters org-table-named-field-locations
4353 org-table-current-line-types org-table-current-begin-line
4354 org-table-current-begin-pos org-table-dlines
4355 org-table-hlines org-table-last-alignment
4356 org-table-last-column-widths org-table-last-alignment
4357 org-table-last-column-widths tbeg
4359 (setq form (org-table-convert-refs-to-rc form))
4364 (goto-char (point-min))
4365 (if (re-search-forward
4366 (concat "^[ \t]*#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4368 (setq buffer (current-buffer) loc (match-beginning 0))
4369 (setq id-loc (org-id-find name-or-id 'marker))
4370 (unless (and id-loc (markerp id-loc))
4371 (error "Can't find remote table \"%s\"" name-or-id))
4372 (setq buffer (marker-buffer id-loc)
4373 loc (marker-position id-loc))
4374 (move-marker id-loc nil)))
4375 (with-current-buffer buffer
4381 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4382 (not (match-beginning 1)))
4383 (error "Cannot find a table at NAME or ID %s" name-or-id))
4384 (setq tbeg (point-at-bol))
4385 (org-table-get-specials)
4386 (setq form (org-table-formula-substitute-names form))
4387 (if (and (string-match org-table-range-regexp form)
4388 (> (length (match-string 0 form)) 1))
4390 (org-table-get-range (match-string 0 form) tbeg 1))
4393 (provide 'org-table)
4396 ;;; org-table.el ends here