Add documentation for org-crypt.el
[org-mode.git] / lisp / org-table.el
blob30c4ddd0aac41400b827f2d417dfdc53cd1e492e
1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 7.5
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; This file contains the table editor and spreadsheet for Org-mode.
31 ;; Watch out: Here we are talking about two different kind of tables.
32 ;; Most of the code is for the tables created with the Org-mode table editor.
33 ;; Sometimes, we talk about tables created and edited with the table.el
34 ;; Emacs package. We call the former org-type tables, and the latter
35 ;; table.el-type tables.
37 ;;; Code:
39 (eval-when-compile
40 (require 'cl))
41 (require 'org)
43 (declare-function org-table-clean-before-export "org-exp"
44 (lines &optional maybe-quoted))
45 (declare-function org-format-org-table-html "org-html" (lines &optional splice))
46 (defvar orgtbl-mode) ; defined below
47 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
48 (defvar org-export-html-table-tag) ; defined in org-exp.el
49 (defvar constants-unit-system)
51 (defvar orgtbl-after-send-table-hook nil
52 "Hook for functions attaching to `C-c C-c', if the table is sent.
53 This can be used to add additional functionality after the table is sent
54 to the receiver position, othewise, if table is not sent, the functions
55 are not run.")
57 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
58 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
59 In the optimized version, the table editor takes over all simple keys that
60 normally just insert a character. In tables, the characters are inserted
61 in a way to minimize disturbing the table structure (i.e. in overwrite mode
62 for empty fields). Outside tables, the correct binding of the keys is
63 restored.
65 The default for this option is t if the optimized version is also used in
66 Org-mode. See the variable `org-enable-table-editor' for details. Changing
67 this variable requires a restart of Emacs to become effective."
68 :group 'org-table
69 :type 'boolean)
71 (defcustom orgtbl-radio-table-templates
72 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
73 % END RECEIVE ORGTBL %n
74 \\begin{comment}
75 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
76 | | |
77 \\end{comment}\n")
78 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
79 @c END RECEIVE ORGTBL %n
80 @ignore
81 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
82 | | |
83 @end ignore\n")
84 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
85 <!-- END RECEIVE ORGTBL %n -->
86 <!--
87 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
88 | | |
89 -->\n"))
90 "Templates for radio tables in different major modes.
91 All occurrences of %n in a template will be replaced with the name of the
92 table, obtained by prompting the user."
93 :group 'org-table
94 :type '(repeat
95 (list (symbol :tag "Major mode")
96 (string :tag "Format"))))
98 (defgroup org-table-settings nil
99 "Settings for tables in Org-mode."
100 :tag "Org Table Settings"
101 :group 'org-table)
103 (defcustom org-table-default-size "5x2"
104 "The default size for newly created tables, Columns x Rows."
105 :group 'org-table-settings
106 :type 'string)
108 (defcustom org-table-number-regexp
109 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
110 "Regular expression for recognizing numbers in table columns.
111 If a table column contains mostly numbers, it will be aligned to the
112 right. If not, it will be aligned to the left.
114 The default value of this option is a regular expression which allows
115 anything which looks remotely like a number as used in scientific
116 context. For example, all of the following will be considered a
117 number:
118 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
120 Other options offered by the customize interface are more restrictive."
121 :group 'org-table-settings
122 :type '(choice
123 (const :tag "Positive Integers"
124 "^[0-9]+$")
125 (const :tag "Integers"
126 "^[-+]?[0-9]+$")
127 (const :tag "Floating Point Numbers"
128 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
129 (const :tag "Floating Point Number or Integer"
130 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
131 (const :tag "Exponential, Floating point, Integer"
132 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
133 (const :tag "Very General Number-Like, including hex"
134 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
135 (string :tag "Regexp:")))
137 (defcustom org-table-number-fraction 0.5
138 "Fraction of numbers in a column required to make the column align right.
139 In a column all non-white fields are considered. If at least this
140 fraction of fields is matched by `org-table-number-fraction',
141 alignment to the right border applies."
142 :group 'org-table-settings
143 :type 'number)
145 (defgroup org-table-editing nil
146 "Behavior of tables during editing in Org-mode."
147 :tag "Org Table Editing"
148 :group 'org-table)
150 (defcustom org-table-automatic-realign t
151 "Non-nil means automatically re-align table when pressing TAB or RETURN.
152 When nil, aligning is only done with \\[org-table-align], or after column
153 removal/insertion."
154 :group 'org-table-editing
155 :type 'boolean)
157 (defcustom org-table-auto-blank-field t
158 "Non-nil means automatically blank table field when starting to type into it.
159 This only happens when typing immediately after a field motion
160 command (TAB, S-TAB or RET).
161 Only relevant when `org-enable-table-editor' is equal to `optimized'."
162 :group 'org-table-editing
163 :type 'boolean)
165 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
166 "Non-nil means automatically exit the follow mode.
167 When nil, the follow mode will stay on and be active in any table
168 the cursor enters. Since the table follow filed mode messes with the
169 window configuration, it is not recommended to set this variable to nil,
170 except maybe locally in a special file that has mostly tables with long
171 fields."
172 :group 'org-table
173 :type 'boolean)
175 (defcustom org-table-fix-formulas-confirm nil
176 "Whether the user should confirm when Org fixes formulas."
177 :group 'org-table-editing
178 :type '(choice
179 (const :tag "with yes-or-no" yes-or-no-p)
180 (const :tag "with y-or-n" y-or-n-p)
181 (const :tag "no confirmation" nil)))
182 (put 'org-table-fix-formulas-confirm
183 'safe-local-variable
184 '(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
186 (defcustom org-table-tab-jumps-over-hlines t
187 "Non-nil means tab in the last column of a table with jump over a hline.
188 If a horizontal separator line is following the current line,
189 `org-table-next-field' can either create a new row before that line, or jump
190 over the line. When this option is nil, a new line will be created before
191 this line."
192 :group 'org-table-editing
193 :type 'boolean)
195 (defgroup org-table-calculation nil
196 "Options concerning tables in Org-mode."
197 :tag "Org Table Calculation"
198 :group 'org-table)
200 (defcustom org-table-use-standard-references 'from
201 "Should org-mode work with table references like B3 instead of @3$2?
202 Possible values are:
203 nil never use them
204 from accept as input, do not present for editing
205 t accept as input and present for editing"
206 :group 'org-table-calculation
207 :type '(choice
208 (const :tag "Never, don't even check user input for them" nil)
209 (const :tag "Always, both as user input, and when editing" t)
210 (const :tag "Convert user input, don't offer during editing" from)))
212 (defcustom org-table-copy-increment t
213 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
214 :group 'org-table-calculation
215 :type 'boolean)
217 (defcustom org-calc-default-modes
218 '(calc-internal-prec 12
219 calc-float-format (float 8)
220 calc-angle-mode deg
221 calc-prefer-frac nil
222 calc-symbolic-mode nil
223 calc-date-format (YYYY "-" MM "-" DD " " Www (" " hh ":" mm))
224 calc-display-working-message t
226 "List with Calc mode settings for use in `calc-eval' for table formulas.
227 The list must contain alternating symbols (Calc modes variables and values).
228 Don't remove any of the default settings, just change the values. Org-mode
229 relies on the variables to be present in the list."
230 :group 'org-table-calculation
231 :type 'plist)
233 (defcustom org-table-formula-evaluate-inline t
234 "Non-nil means TAB and RET evaluate a formula in current table field.
235 If the current field starts with an equal sign, it is assumed to be a formula
236 which should be evaluated as described in the manual and in the documentation
237 string of the command `org-table-eval-formula'. This feature requires the
238 Emacs calc package.
239 When this variable is nil, formula calculation is only available through
240 the command \\[org-table-eval-formula]."
241 :group 'org-table-calculation
242 :type 'boolean)
244 (defcustom org-table-formula-use-constants t
245 "Non-nil means interpret constants in formulas in tables.
246 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
247 by the value given in `org-table-formula-constants', or by a value obtained
248 from the `constants.el' package."
249 :group 'org-table-calculation
250 :type 'boolean)
252 (defcustom org-table-formula-constants nil
253 "Alist with constant names and values, for use in table formulas.
254 The car of each element is a name of a constant, without the `$' before it.
255 The cdr is the value as a string. For example, if you'd like to use the
256 speed of light in a formula, you would configure
258 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
260 and then use it in an equation like `$1*$c'.
262 Constants can also be defined on a per-file basis using a line like
264 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
265 :group 'org-table-calculation
266 :type '(repeat
267 (cons (string :tag "name")
268 (string :tag "value"))))
270 (defcustom org-table-allow-automatic-line-recalculation t
271 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
272 Automatically means when TAB or RET or C-c C-c are pressed in the line."
273 :group 'org-table-calculation
274 :type 'boolean)
276 (defcustom org-table-error-on-row-ref-crossing-hline t
277 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
278 :group 'org-table
279 :type 'boolean)
281 (defcustom org-table-relative-ref-may-cross-hline t
282 "Non-nil means relative formula references may cross hlines.
283 Here are the allowed values:
285 nil Relative references may not cross hlines. They will reference the
286 field next to the hline instead. Coming from below, the reference
287 will be to the field below the hline. Coming from above, it will be
288 to the field above.
289 t Relative references may cross hlines.
290 error An attempt to cross a hline will throw an error.
292 It is probably good to never set this variable to nil, for the sake of
293 portability of tables."
294 :group 'org-table-calculation
295 :type '(choice
296 (const :tag "Allow to cross" t)
297 (const :tag "Stick to hline" nil)
298 (const :tag "Error on attempt to cross" error)))
300 (defgroup org-table-import-export nil
301 "Options concerning table import and export in Org-mode."
302 :tag "Org Table Import Export"
303 :group 'org-table)
305 (defcustom org-table-export-default-format "orgtbl-to-tsv"
306 "Default export parameters for `org-table-export'.
307 These can be overridden for a specific table by setting the
308 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
309 radio tables for the different export transformations and
310 available parameters."
311 :group 'org-table-import-export
312 :type 'string)
314 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
315 "Detects a table line marked for automatic recalculation.")
316 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
317 "Detects a table line marked for automatic recalculation.")
318 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
319 "Detects a table line marked for automatic recalculation.")
320 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
321 "Searching from within a table (any type) this finds the first line outside the table.")
322 (defvar org-table-last-highlighted-reference nil)
323 (defvar org-table-formula-history nil)
325 (defvar org-table-column-names nil
326 "Alist with column names, derived from the `!' line.")
327 (defvar org-table-column-name-regexp nil
328 "Regular expression matching the current column names.")
329 (defvar org-table-local-parameters nil
330 "Alist with parameter names, derived from the `$' line.")
331 (defvar org-table-named-field-locations nil
332 "Alist with locations of named fields.")
334 (defvar org-table-current-line-types nil
335 "Table row types, non-nil only for the duration of a command.")
336 (defvar org-table-current-begin-line nil
337 "Table begin line, non-nil only for the duration of a command.")
338 (defvar org-table-current-begin-pos nil
339 "Table begin position, non-nil only for the duration of a command.")
340 (defvar org-table-current-ncol nil
341 "Number of columns in table, non-nil only for the duration of a command.")
342 (defvar org-table-dlines nil
343 "Vector of data line line numbers in the current table.")
344 (defvar org-table-hlines nil
345 "Vector of hline line numbers in the current table.")
347 (defconst org-table-range-regexp
348 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
349 ;; 1 2 3 4 5
350 "Regular expression for matching ranges in formulas.")
352 (defconst org-table-range-regexp2
353 (concat
354 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
355 "\\.\\."
356 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
357 "Match a range for reference display.")
359 (defun org-table-colgroup-line-p (line)
360 "Is this a table line colgroup information?"
361 (save-match-data
362 (and (string-match "[<>]\\|&[lg]t;" line)
363 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
364 line)
365 (not (delq
367 (mapcar
368 (lambda (s)
369 (not (member s '("" "<" ">" "<>" "&lt;" "&gt;" "&lt;&gt;"))))
370 (org-split-string (match-string 1 line) "[ \t]*|[ \t]*")))))))
372 (defun org-table-cookie-line-p (line)
373 "Is this a table line with only alignment/width cookies?"
374 (save-match-data
375 (and (string-match "[<>]\\|&[lg]t;" line)
376 (or (string-match
377 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line)
378 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line))
379 (not (delq nil (mapcar
380 (lambda (s)
381 (not (or (equal s "")
382 (string-match
383 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s)
384 (string-match
385 "\\`&lt;\\([lrc]?[0-9]+\\|[lrc]\\)&gt;\\'"
386 s))))
387 (org-split-string (match-string 1 line)
388 "[ \t]*|[ \t]*")))))))
390 (defconst org-table-translate-regexp
391 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
392 "Match a reference that needs translation, for reference display.")
394 (defun org-table-create-with-table.el ()
395 "Use the table.el package to insert a new table.
396 If there is already a table at point, convert between Org-mode tables
397 and table.el tables."
398 (interactive)
399 (require 'table)
400 (cond
401 ((org-at-table.el-p)
402 (if (y-or-n-p "Convert table to Org-mode table? ")
403 (org-table-convert)))
404 ((org-at-table-p)
405 (when (y-or-n-p "Convert table to table.el table? ")
406 (org-table-align)
407 (org-table-convert)))
408 (t (call-interactively 'table-insert))))
410 (defun org-table-create-or-convert-from-region (arg)
411 "Convert region to table, or create an empty table.
412 If there is an active region, convert it to a table, using the function
413 `org-table-convert-region'. See the documentation of that function
414 to learn how the prefix argument is interpreted to determine the field
415 separator.
416 If there is no such region, create an empty table with `org-table-create'."
417 (interactive "P")
418 (if (org-region-active-p)
419 (org-table-convert-region (region-beginning) (region-end) arg)
420 (org-table-create arg)))
422 (defun org-table-create (&optional size)
423 "Query for a size and insert a table skeleton.
424 SIZE is a string Columns x Rows like for example \"3x2\"."
425 (interactive "P")
426 (unless size
427 (setq size (read-string
428 (concat "Table size Columns x Rows [e.g. "
429 org-table-default-size "]: ")
430 "" nil org-table-default-size)))
432 (let* ((pos (point))
433 (indent (make-string (current-column) ?\ ))
434 (split (org-split-string size " *x *"))
435 (rows (string-to-number (nth 1 split)))
436 (columns (string-to-number (car split)))
437 (line (concat (apply 'concat indent "|" (make-list columns " |"))
438 "\n")))
439 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
440 (point-at-bol) (point)))
441 (beginning-of-line 1)
442 (newline))
443 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
444 (dotimes (i rows) (insert line))
445 (goto-char pos)
446 (if (> rows 1)
447 ;; Insert a hline after the first row.
448 (progn
449 (end-of-line 1)
450 (insert "\n|-")
451 (goto-char pos)))
452 (org-table-align)))
454 (defun org-table-convert-region (beg0 end0 &optional separator)
455 "Convert region to a table.
456 The region goes from BEG0 to END0, but these borders will be moved
457 slightly, to make sure a beginning of line in the first line is included.
459 SEPARATOR specifies the field separator in the lines. It can have the
460 following values:
462 '(4) Use the comma as a field separator
463 '(16) Use a TAB as field separator
464 integer When a number, use that many spaces as field separator
465 nil When nil, the command tries to be smart and figure out the
466 separator in the following way:
467 - when each line contains a TAB, assume TAB-separated material
468 - when each line contains a comma, assume CSV material
469 - else, assume one or more SPACE characters as separator."
470 (interactive "rP")
471 (let* ((beg (min beg0 end0))
472 (end (max beg0 end0))
474 (goto-char beg)
475 (beginning-of-line 1)
476 (setq beg (move-marker (make-marker) (point)))
477 (goto-char end)
478 (if (bolp) (backward-char 1) (end-of-line 1))
479 (setq end (move-marker (make-marker) (point)))
480 ;; Get the right field separator
481 (unless separator
482 (goto-char beg)
483 (setq separator
484 (cond
485 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
486 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
487 (t 1))))
488 (goto-char beg)
489 (if (equal separator '(4))
490 (while (< (point) end)
491 ;; parse the csv stuff
492 (cond
493 ((looking-at "^") (insert "| "))
494 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
495 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
496 (replace-match "\\1")
497 (if (looking-at "\"") (insert "\"")))
498 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
499 ((looking-at "[ \t]*,") (replace-match " | "))
500 (t (beginning-of-line 2))))
501 (setq re (cond
502 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
503 ((equal separator '(16)) "^\\|\t")
504 ((integerp separator)
505 (if (< separator 1)
506 (error "Number of spaces in separator must be >= 1")
507 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
508 (t (error "This should not happen"))))
509 (while (re-search-forward re end t)
510 (replace-match "| " t t)))
511 (goto-char beg)
512 (org-table-align)))
514 (defun org-table-import (file arg)
515 "Import FILE as a table.
516 The file is assumed to be tab-separated. Such files can be produced by most
517 spreadsheet and database applications. If no tabs (at least one per line)
518 are found, lines will be split on whitespace into fields."
519 (interactive "f\nP")
520 (or (bolp) (newline))
521 (let ((beg (point))
522 (pm (point-max)))
523 (insert-file-contents file)
524 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
527 (defvar org-table-last-alignment)
528 (defvar org-table-last-column-widths)
529 (defun org-table-export (&optional file format)
530 "Export table to a file, with configurable format.
531 Such a file can be imported into a spreadsheet program like Excel.
532 FILE can be the output file name. If not given, it will be taken from
533 a TABLE_EXPORT_FILE property in the current entry or higher up in the
534 hierarchy, or the user will be prompted for a file name.
535 FORMAT can be an export format, of the same kind as it used when
536 `orgtbl-mode' sends a table in a different format. The default format can
537 be found in the variable `org-table-export-default-format', but the function
538 first checks if there is an export format specified in a TABLE_EXPORT_FORMAT
539 property, locally or anywhere up in the hierarchy."
540 (interactive)
541 (unless (org-at-table-p)
542 (error "No table at point"))
543 (require 'org-exp)
544 (org-table-align) ;; make sure we have everything we need
545 (let* ((beg (org-table-begin))
546 (end (org-table-end))
547 (txt (buffer-substring-no-properties beg end))
548 (file (or file (org-entry-get beg "TABLE_EXPORT_FILE" t)))
549 (format (or format
550 (org-entry-get beg "TABLE_EXPORT_FORMAT" t)))
551 buf deffmt-readable)
552 (unless file
553 (setq file (read-file-name "Export table to: "))
554 (unless (or (not (file-exists-p file))
555 (y-or-n-p (format "Overwrite file %s? " file)))
556 (error "Abort")))
557 (if (file-directory-p file)
558 (error "This is a directory path, not a file"))
559 (if (and (buffer-file-name)
560 (equal (file-truename file)
561 (file-truename (buffer-file-name))))
562 (error "Please specify a file name that is different from current"))
563 (unless format
564 (setq deffmt-readable org-table-export-default-format)
565 (while (string-match "\t" deffmt-readable)
566 (setq deffmt-readable (replace-match "\\t" t t deffmt-readable)))
567 (while (string-match "\n" deffmt-readable)
568 (setq deffmt-readable (replace-match "\\n" t t deffmt-readable)))
569 (setq format (org-completing-read
570 "Format: "
571 '("orgtbl-to-tsv" "orgtbl-to-csv"
572 "orgtbl-to-latex" "orgtbl-to-html"
573 "orgtbl-to-generic" "orgtbl-to-texinfo"
574 "orgtbl-to-orgtbl") nil nil
575 deffmt-readable)))
576 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format)
577 (let* ((transform (intern (match-string 1 format)))
578 (params (if (match-end 2)
579 (read (concat "(" (match-string 2 format) ")"))))
580 (skip (plist-get params :skip))
581 (skipcols (plist-get params :skipcols))
582 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
583 (lines (org-table-clean-before-export lines))
584 (i0 (if org-table-clean-did-remove-column 2 1))
585 (table (mapcar
586 (lambda (x)
587 (if (string-match org-table-hline-regexp x)
588 'hline
589 (org-remove-by-index
590 (org-split-string (org-trim x) "\\s-*|\\s-*")
591 skipcols i0)))
592 lines))
593 (fun (if (= i0 2) 'cdr 'identity))
594 (org-table-last-alignment
595 (org-remove-by-index (funcall fun org-table-last-alignment)
596 skipcols i0))
597 (org-table-last-column-widths
598 (org-remove-by-index (funcall fun org-table-last-column-widths)
599 skipcols i0)))
601 (unless (fboundp transform)
602 (error "No such transformation function %s" transform))
603 (setq txt (funcall transform table params))
605 (with-current-buffer (find-file-noselect file)
606 (setq buf (current-buffer))
607 (erase-buffer)
608 (fundamental-mode)
609 (insert txt "\n")
610 (save-buffer))
611 (kill-buffer buf)
612 (message "Export done."))
613 (error "TABLE_EXPORT_FORMAT invalid"))))
615 (defvar org-table-aligned-begin-marker (make-marker)
616 "Marker at the beginning of the table last aligned.
617 Used to check if cursor still is in that table, to minimize realignment.")
618 (defvar org-table-aligned-end-marker (make-marker)
619 "Marker at the end of the table last aligned.
620 Used to check if cursor still is in that table, to minimize realignment.")
621 (defvar org-table-last-alignment nil
622 "List of flags for flushright alignment, from the last re-alignment.
623 This is being used to correctly align a single field after TAB or RET.")
624 (defvar org-table-last-column-widths nil
625 "List of max width of fields in each column.
626 This is being used to correctly align a single field after TAB or RET.")
627 (defvar org-table-formula-debug nil
628 "Non-nil means debug table formulas.
629 When nil, simply write \"#ERROR\" in corrupted fields.")
630 (make-variable-buffer-local 'org-table-formula-debug)
631 (defvar org-table-overlay-coordinates nil
632 "Overlay coordinates after each align of a table.")
633 (make-variable-buffer-local 'org-table-overlay-coordinates)
635 (defvar org-last-recalc-line nil)
636 (defvar org-table-do-narrow t) ; for dynamic scoping
637 (defconst org-narrow-column-arrow "=>"
638 "Used as display property in narrowed table columns.")
640 (defun org-table-align ()
641 "Align the table at point by aligning all vertical bars."
642 (interactive)
643 (let* (
644 ;; Limits of table
645 (beg (org-table-begin))
646 (end (org-table-end))
647 ;; Current cursor position
648 (linepos (org-current-line))
649 (colpos (org-table-current-column))
650 (winstart (window-start))
651 (winstartline (org-current-line (min winstart (1- (point-max)))))
652 lines (new "") lengths l typenums ty fields maxfields i
653 column
654 (indent "") cnt frac
655 rfmt hfmt
656 (spaces '(1 . 1))
657 (sp1 (car spaces))
658 (sp2 (cdr spaces))
659 (rfmt1 (concat
660 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
661 (hfmt1 (concat
662 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
663 emptystrings links dates emph raise narrow
664 falign falign1 fmax f1 len c e space)
665 (untabify beg end)
666 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
667 ;; Check if we have links or dates
668 (goto-char beg)
669 (setq links (re-search-forward org-bracket-link-regexp end t))
670 (goto-char beg)
671 (setq emph (and org-hide-emphasis-markers
672 (re-search-forward org-emph-re end t)))
673 (goto-char beg)
674 (setq raise (and org-use-sub-superscripts
675 (re-search-forward org-match-substring-regexp end t)))
676 (goto-char beg)
677 (setq dates (and org-display-custom-times
678 (re-search-forward org-ts-regexp-both end t)))
679 ;; Make sure the link properties are right
680 (when links (goto-char beg) (while (org-activate-bracket-links end)))
681 ;; Make sure the date properties are right
682 (when dates (goto-char beg) (while (org-activate-dates end)))
683 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
684 (when raise (goto-char beg) (while (org-raise-scripts end)))
686 ;; Check if we are narrowing any columns
687 (goto-char beg)
688 (setq narrow (and org-table-do-narrow
689 org-format-transports-properties-p
690 (re-search-forward "<[lrc]?[0-9]+>" end t)))
691 (goto-char beg)
692 (setq falign (re-search-forward "<[lrc][0-9]*>" end t))
693 (goto-char beg)
694 ;; Get the rows
695 (setq lines (org-split-string
696 (buffer-substring beg end) "\n"))
697 ;; Store the indentation of the first line
698 (if (string-match "^ *" (car lines))
699 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
700 ;; Mark the hlines by setting the corresponding element to nil
701 ;; At the same time, we remove trailing space.
702 (setq lines (mapcar (lambda (l)
703 (if (string-match "^ *|-" l)
705 (if (string-match "[ \t]+$" l)
706 (substring l 0 (match-beginning 0))
707 l)))
708 lines))
709 ;; Get the data fields by splitting the lines.
710 (setq fields (mapcar
711 (lambda (l)
712 (org-split-string l " *| *"))
713 (delq nil (copy-sequence lines))))
714 ;; How many fields in the longest line?
715 (condition-case nil
716 (setq maxfields (apply 'max (mapcar 'length fields)))
717 (error
718 (kill-region beg end)
719 (org-table-create org-table-default-size)
720 (error "Empty table - created default table")))
721 ;; A list of empty strings to fill any short rows on output
722 (setq emptystrings (make-list maxfields ""))
723 ;; Check for special formatting.
724 (setq i -1)
725 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
726 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
727 ;; Check if there is an explicit width specified
728 (setq fmax nil)
729 (when (or narrow falign)
730 (setq c column fmax nil falign1 nil)
731 (while c
732 (setq e (pop c))
733 (when (and (stringp e) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e))
734 (if (match-end 1) (setq falign1 (match-string 1 e)))
735 (if (and org-table-do-narrow (match-end 2))
736 (setq fmax (string-to-number (match-string 2 e)) c nil))))
737 ;; Find fields that are wider than fmax, and shorten them
738 (when fmax
739 (loop for xx in column do
740 (when (and (stringp xx)
741 (> (org-string-width xx) fmax))
742 (org-add-props xx nil
743 'help-echo
744 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
745 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
746 (unless (> f1 1)
747 (error "Cannot narrow field starting with wide link \"%s\""
748 (match-string 0 xx)))
749 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
750 (add-text-properties (- f1 2) f1
751 (list 'display org-narrow-column-arrow)
752 xx)))))
753 ;; Get the maximum width for each column
754 (push (apply 'max (or fmax 1) 1 (mapcar 'org-string-width column))
755 lengths)
756 ;; Get the fraction of numbers, to decide about alignment of the column
757 (if falign1
758 (push (equal (downcase falign1) "r") typenums)
759 (setq cnt 0 frac 0.0)
760 (loop for x in column do
761 (if (equal x "")
763 (setq frac ( / (+ (* frac cnt)
764 (if (string-match org-table-number-regexp x) 1 0))
765 (setq cnt (1+ cnt))))))
766 (push (>= frac org-table-number-fraction) typenums)))
767 (setq lengths (nreverse lengths) typenums (nreverse typenums))
769 ;; Store the alignment of this table, for later editing of single fields
770 (setq org-table-last-alignment typenums
771 org-table-last-column-widths lengths)
773 ;; With invisible characters, `format' does not get the field width right
774 ;; So we need to make these fields wide by hand.
775 (when (or links emph raise)
776 (loop for i from 0 upto (1- maxfields) do
777 (setq len (nth i lengths))
778 (loop for j from 0 upto (1- (length fields)) do
779 (setq c (nthcdr i (car (nthcdr j fields))))
780 (if (and (stringp (car c))
781 (or (text-property-any 0 (length (car c))
782 'invisible 'org-link (car c))
783 (text-property-any 0 (length (car c))
784 'org-dwidth t (car c)))
785 (< (org-string-width (car c)) len))
786 (progn
787 (setq space (make-string (- len (org-string-width (car c))) ?\ ))
788 (setcar c (if (nth i typenums)
789 (concat space (car c))
790 (concat (car c) space))))))))
792 ;; Compute the formats needed for output of the table
793 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
794 (while (setq l (pop lengths))
795 (setq ty (if (pop typenums) "" "-")) ; number types flushright
796 (setq rfmt (concat rfmt (format rfmt1 ty l))
797 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
798 (setq rfmt (concat rfmt "\n")
799 hfmt (concat (substring hfmt 0 -1) "|\n"))
801 (setq new (mapconcat
802 (lambda (l)
803 (if l (apply 'format rfmt
804 (append (pop fields) emptystrings))
805 hfmt))
806 lines ""))
807 (if (equal (char-before) ?\n)
808 ;; This hack is for org-indent, to force redisplay of the
809 ;; line prefix of the first line. Apparently the redisplay
810 ;; is tied to the newline, which is, I think, a bug.
811 ;; To force this redisplay, we remove and re-insert the
812 ;; newline, so that the redisplay engine thinks it belongs
813 ;; to the changed text.
814 (progn
815 (backward-delete-char 1)
816 (insert "\n")))
817 (move-marker org-table-aligned-begin-marker (point))
818 (insert new)
819 ;; Replace the old one
820 (delete-region (point) end)
821 (move-marker end nil)
822 (move-marker org-table-aligned-end-marker (point))
823 (when (and orgtbl-mode (not (org-mode-p)))
824 (goto-char org-table-aligned-begin-marker)
825 (while (org-hide-wide-columns org-table-aligned-end-marker)))
826 ;; Try to move to the old location
827 (org-goto-line winstartline)
828 (setq winstart (point-at-bol))
829 (org-goto-line linepos)
830 (set-window-start (selected-window) winstart 'noforce)
831 (org-table-goto-column colpos)
832 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
833 (setq org-table-may-need-update nil)
836 (defun org-table-begin (&optional table-type)
837 "Find the beginning of the table and return its position.
838 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
839 (save-excursion
840 (if (not (re-search-backward
841 (if table-type org-table-any-border-regexp
842 org-table-border-regexp)
843 nil t))
844 (progn (goto-char (point-min)) (point))
845 (goto-char (match-beginning 0))
846 (beginning-of-line 2)
847 (point))))
849 (defun org-table-end (&optional table-type)
850 "Find the end of the table and return its position.
851 With argument TABLE-TYPE, go to the end of a table.el-type table."
852 (save-excursion
853 (if (not (re-search-forward
854 (if table-type org-table-any-border-regexp
855 org-table-border-regexp)
856 nil t))
857 (goto-char (point-max))
858 (goto-char (match-beginning 0)))
859 (point-marker)))
861 (defun org-table-justify-field-maybe (&optional new)
862 "Justify the current field, text to left, number to right.
863 Optional argument NEW may specify text to replace the current field content."
864 (cond
865 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
866 ((org-at-table-hline-p))
867 ((and (not new)
868 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
869 (current-buffer)))
870 (< (point) org-table-aligned-begin-marker)
871 (>= (point) org-table-aligned-end-marker)))
872 ;; This is not the same table, force a full re-align
873 (setq org-table-may-need-update t))
874 (t ;; realign the current field, based on previous full realign
875 (let* ((pos (point)) s
876 (col (org-table-current-column))
877 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
878 l f n o e)
879 (when (> col 0)
880 (skip-chars-backward "^|\n")
881 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
882 (progn
883 (setq s (match-string 1)
884 o (match-string 0)
885 l (max 1 (- (match-end 0) (match-beginning 0) 3))
886 e (not (= (match-beginning 2) (match-end 2))))
887 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
888 l (if e "|" (setq org-table-may-need-update t) ""))
889 n (format f s))
890 (if new
891 (if (<= (length new) l) ;; FIXME: length -> str-width?
892 (setq n (format f new))
893 (setq n (concat new "|") org-table-may-need-update t)))
894 (if (equal (string-to-char n) ?-) (setq n (concat " " n)))
895 (or (equal n o)
896 (let (org-table-may-need-update)
897 (replace-match n t t))))
898 (setq org-table-may-need-update t))
899 (goto-char pos))))))
901 (defun org-table-next-field ()
902 "Go to the next field in the current table, creating new lines as needed.
903 Before doing so, re-align the table if necessary."
904 (interactive)
905 (org-table-maybe-eval-formula)
906 (org-table-maybe-recalculate-line)
907 (if (and org-table-automatic-realign
908 org-table-may-need-update)
909 (org-table-align))
910 (let ((end (org-table-end)))
911 (if (org-at-table-hline-p)
912 (end-of-line 1))
913 (condition-case nil
914 (progn
915 (re-search-forward "|" end)
916 (if (looking-at "[ \t]*$")
917 (re-search-forward "|" end))
918 (if (and (looking-at "-")
919 org-table-tab-jumps-over-hlines
920 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
921 (goto-char (match-beginning 1)))
922 (if (looking-at "-")
923 (progn
924 (beginning-of-line 0)
925 (org-table-insert-row 'below))
926 (if (looking-at " ") (forward-char 1))))
927 (error
928 (org-table-insert-row 'below)))))
930 (defun org-table-previous-field ()
931 "Go to the previous field in the table.
932 Before doing so, re-align the table if necessary."
933 (interactive)
934 (org-table-justify-field-maybe)
935 (org-table-maybe-recalculate-line)
936 (if (and org-table-automatic-realign
937 org-table-may-need-update)
938 (org-table-align))
939 (if (org-at-table-hline-p)
940 (end-of-line 1))
941 (condition-case nil
942 (progn
943 (re-search-backward "|" (org-table-begin))
944 (re-search-backward "|" (org-table-begin)))
945 (error (error "Cannot move to previous table field")))
946 (while (looking-at "|\\(-\\|[ \t]*$\\)")
947 (re-search-backward "|" (org-table-begin)))
948 (if (looking-at "| ?")
949 (goto-char (match-end 0))))
951 (defun org-table-beginning-of-field (&optional n)
952 "Move to the end of the current table field.
953 If already at or after the end, move to the end of the next table field.
954 With numeric argument N, move N-1 fields forward first."
955 (interactive "p")
956 (let ((pos (point)))
957 (while (> n 1)
958 (setq n (1- n))
959 (org-table-previous-field))
960 (if (not (re-search-backward "|" (point-at-bol 0) t))
961 (error "No more table fields before the current")
962 (goto-char (match-end 0))
963 (and (looking-at " ") (forward-char 1)))
964 (if (>= (point) pos) (org-table-beginning-of-field 2))))
966 (defun org-table-end-of-field (&optional n)
967 "Move to the beginning of the current table field.
968 If already at or before the beginning, move to the beginning of the
969 previous field.
970 With numeric argument N, move N-1 fields backward first."
971 (interactive "p")
972 (let ((pos (point)))
973 (while (> n 1)
974 (setq n (1- n))
975 (org-table-next-field))
976 (when (re-search-forward "|" (point-at-eol 1) t)
977 (backward-char 1)
978 (skip-chars-backward " ")
979 (if (and (equal (char-before (point)) ?|) (looking-at " "))
980 (forward-char 1)))
981 (if (<= (point) pos) (org-table-end-of-field 2))))
983 (defun org-table-next-row ()
984 "Go to the next row (same column) in the current table.
985 Before doing so, re-align the table if necessary."
986 (interactive)
987 (org-table-maybe-eval-formula)
988 (org-table-maybe-recalculate-line)
989 (if (or (looking-at "[ \t]*$")
990 (save-excursion (skip-chars-backward " \t") (bolp)))
991 (newline)
992 (if (and org-table-automatic-realign
993 org-table-may-need-update)
994 (org-table-align))
995 (let ((col (org-table-current-column)))
996 (beginning-of-line 2)
997 (if (or (not (org-at-table-p))
998 (org-at-table-hline-p))
999 (progn
1000 (beginning-of-line 0)
1001 (org-table-insert-row 'below)))
1002 (org-table-goto-column col)
1003 (skip-chars-backward "^|\n\r")
1004 (if (looking-at " ") (forward-char 1)))))
1006 (defun org-table-copy-down (n)
1007 "Copy a field down in the current column.
1008 If the field at the cursor is empty, copy into it the content of
1009 the nearest non-empty field above. With argument N, use the Nth
1010 non-empty field. If the current field is not empty, it is copied
1011 down to the next row, and the cursor is moved with it.
1012 Therefore, repeating this command causes the column to be filled
1013 row-by-row.
1014 If the variable `org-table-copy-increment' is non-nil and the
1015 field is an integer or a timestamp, it will be incremented while
1016 copying. In the case of a timestamp, increment by one day."
1017 (interactive "p")
1018 (let* ((colpos (org-table-current-column))
1019 (col (current-column))
1020 (field (org-table-get-field))
1021 (non-empty (string-match "[^ \t]" field))
1022 (beg (org-table-begin))
1023 (orig-n n)
1024 txt)
1025 (org-table-check-inside-data-field)
1026 (if non-empty
1027 (progn
1028 (setq txt (org-trim field))
1029 (org-table-next-row)
1030 (org-table-blank-field))
1031 (save-excursion
1032 (setq txt
1033 (catch 'exit
1034 (while (progn (beginning-of-line 1)
1035 (re-search-backward org-table-dataline-regexp
1036 beg t))
1037 (org-table-goto-column colpos t)
1038 (if (and (looking-at
1039 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1040 (<= (setq n (1- n)) 0))
1041 (throw 'exit (match-string 1))))))))
1042 (if txt
1043 (progn
1044 (if (and org-table-copy-increment
1045 (not (equal orig-n 0))
1046 (string-match "^[0-9]+$" txt)
1047 (< (string-to-number txt) 100000000))
1048 (setq txt (format "%d" (+ (string-to-number txt) 1))))
1049 (insert txt)
1050 (org-move-to-column col)
1051 (if (and org-table-copy-increment (org-at-timestamp-p t))
1052 (org-timestamp-up-day)
1053 (org-table-maybe-recalculate-line))
1054 (org-table-align)
1055 (org-move-to-column col))
1056 (error "No non-empty field found"))))
1058 (defun org-table-check-inside-data-field (&optional noerror)
1059 "Is point inside a table data field?
1060 I.e. not on a hline or before the first or after the last column?
1061 This actually throws an error, so it aborts the current command."
1062 (if (or (not (org-at-table-p))
1063 (= (org-table-current-column) 0)
1064 (org-at-table-hline-p)
1065 (looking-at "[ \t]*$"))
1066 (if noerror
1068 (error "Not in table data field"))
1071 (defvar org-table-clip nil
1072 "Clipboard for table regions.")
1074 (defun org-table-get (line column)
1075 "Get the field in table line LINE, column COLUMN.
1076 If LINE is larger than the number of data lines in the table, the function
1077 returns nil. However, if COLUMN is too large, we will simply return an
1078 empty string.
1079 If LINE is nil, use the current line.
1080 If column is nil, use the current column."
1081 (setq column (or column (org-table-current-column)))
1082 (save-excursion
1083 (and (or (not line) (org-table-goto-line line))
1084 (org-trim (org-table-get-field column)))))
1086 (defun org-table-put (line column value &optional align)
1087 "Put VALUE into line LINE, column COLUMN.
1088 When ALIGN is set, also realign the table."
1089 (setq column (or column (org-table-current-column)))
1090 (prog1 (save-excursion
1091 (and (or (not line) (org-table-goto-line line))
1092 (progn (org-table-goto-column column nil 'force) t)
1093 (org-table-get-field column value)))
1094 (and align (org-table-align))))
1096 (defun org-table-current-line ()
1097 "Return the index of the current data line."
1098 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1099 (save-excursion
1100 (goto-char (org-table-begin))
1101 (while (and (re-search-forward org-table-dataline-regexp end t)
1102 (setq cnt (1+ cnt))
1103 (< (point-at-eol) pos))))
1104 cnt))
1106 (defun org-table-goto-line (N)
1107 "Go to the Nth data line in the current table.
1108 Return t when the line exists, nil if it does not exist."
1109 (goto-char (org-table-begin))
1110 (let ((end (org-table-end)) (cnt 0))
1111 (while (and (re-search-forward org-table-dataline-regexp end t)
1112 (< (setq cnt (1+ cnt)) N)))
1113 (= cnt N)))
1115 (defun org-table-blank-field ()
1116 "Blank the current table field or active region."
1117 (interactive)
1118 (org-table-check-inside-data-field)
1119 (if (and (interactive-p) (org-region-active-p))
1120 (let (org-table-clip)
1121 (org-table-cut-region (region-beginning) (region-end)))
1122 (skip-chars-backward "^|")
1123 (backward-char 1)
1124 (if (looking-at "|[^|\n]+")
1125 (let* ((pos (match-beginning 0))
1126 (match (match-string 0))
1127 (len (org-string-width match)))
1128 (replace-match (concat "|" (make-string (1- len) ?\ )))
1129 (goto-char (+ 2 pos))
1130 (substring match 1)))))
1132 (defun org-table-get-field (&optional n replace)
1133 "Return the value of the field in column N of current row.
1134 N defaults to current field.
1135 If REPLACE is a string, replace field with this value. The return value
1136 is always the old value."
1137 (and n (org-table-goto-column n))
1138 (skip-chars-backward "^|\n")
1139 (backward-char 1)
1140 (if (looking-at "|[^|\r\n]*")
1141 (let* ((pos (match-beginning 0))
1142 (val (buffer-substring (1+ pos) (match-end 0))))
1143 (if replace
1144 (replace-match (concat "|" (if (equal replace "") " " replace))
1145 t t))
1146 (goto-char (min (point-at-eol) (+ 2 pos)))
1147 val)
1148 (forward-char 1) ""))
1150 (defun org-table-field-info (arg)
1151 "Show info about the current field, and highlight any reference at point."
1152 (interactive "P")
1153 (org-table-get-specials)
1154 (save-excursion
1155 (let* ((pos (point))
1156 (col (org-table-current-column))
1157 (cname (car (rassoc (int-to-string col) org-table-column-names)))
1158 (name (car (rassoc (list (org-current-line) col)
1159 org-table-named-field-locations)))
1160 (eql (org-table-expand-lhs-ranges
1161 (mapcar
1162 (lambda (e)
1163 (cons (org-table-formula-handle-first/last-rc
1164 (car e)) (cdr e)))
1165 (org-table-get-stored-formulas))))
1166 (dline (org-table-current-dline))
1167 (ref (format "@%d$%d" dline col))
1168 (ref1 (org-table-convert-refs-to-an ref))
1169 (fequation (or (assoc name eql) (assoc ref eql)))
1170 (cequation (assoc (int-to-string col) eql))
1171 (eqn (or fequation cequation)))
1172 (if (and eqn (get-text-property 0 :orig-eqn (car eqn)))
1173 (setq eqn (get-text-property 0 :orig-eqn (car eqn))))
1174 (goto-char pos)
1175 (condition-case nil
1176 (org-table-show-reference 'local)
1177 (error nil))
1178 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1179 dline col
1180 (if cname (concat " or $" cname) "")
1181 dline col ref1
1182 (if name (concat " or $" name) "")
1183 ;; FIXME: formula info not correct if special table line
1184 (if eqn
1185 (concat ", formula: "
1186 (org-table-formula-to-user
1187 (concat
1188 (if (string-match "^[$@]"(car eqn)) "" "$")
1189 (car eqn) "=" (cdr eqn))))
1190 "")))))
1192 (defun org-table-current-column ()
1193 "Find out which column we are in."
1194 (interactive)
1195 (if (interactive-p) (org-table-check-inside-data-field))
1196 (save-excursion
1197 (let ((cnt 0) (pos (point)))
1198 (beginning-of-line 1)
1199 (while (search-forward "|" pos t)
1200 (setq cnt (1+ cnt)))
1201 (if (interactive-p) (message "In table column %d" cnt))
1202 cnt)))
1204 (defun org-table-current-dline ()
1205 "Find out what table data line we are in.
1206 Only data lines count for this."
1207 (interactive)
1208 (if (interactive-p) (org-table-check-inside-data-field))
1209 (save-excursion
1210 (let ((cnt 0) (pos (point)))
1211 (goto-char (org-table-begin))
1212 (while (<= (point) pos)
1213 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
1214 (beginning-of-line 2))
1215 (if (interactive-p) (message "This is table line %d" cnt))
1216 cnt)))
1218 (defun org-table-goto-column (n &optional on-delim force)
1219 "Move the cursor to the Nth column in the current table line.
1220 With optional argument ON-DELIM, stop with point before the left delimiter
1221 of the field.
1222 If there are less than N fields, just go to after the last delimiter.
1223 However, when FORCE is non-nil, create new columns if necessary."
1224 (interactive "p")
1225 (beginning-of-line 1)
1226 (when (> n 0)
1227 (while (and (> (setq n (1- n)) -1)
1228 (or (search-forward "|" (point-at-eol) t)
1229 (and force
1230 (progn (end-of-line 1)
1231 (skip-chars-backward "^|")
1232 (insert " | ")
1233 t)))))
1234 (when (and force (not (looking-at ".*|")))
1235 (save-excursion (end-of-line 1) (insert " | ")))
1236 (if on-delim
1237 (backward-char 1)
1238 (if (looking-at " ") (forward-char 1)))))
1240 (defun org-table-insert-column ()
1241 "Insert a new column into the table."
1242 (interactive)
1243 (if (not (org-at-table-p))
1244 (error "Not at a table"))
1245 (org-table-find-dataline)
1246 (let* ((col (max 1 (org-table-current-column)))
1247 (beg (org-table-begin))
1248 (end (org-table-end))
1249 ;; Current cursor position
1250 (linepos (org-current-line))
1251 (colpos col))
1252 (goto-char beg)
1253 (while (< (point) end)
1254 (if (org-at-table-hline-p)
1256 (org-table-goto-column col t)
1257 (insert "| "))
1258 (beginning-of-line 2))
1259 (move-marker end nil)
1260 (org-goto-line linepos)
1261 (org-table-goto-column colpos)
1262 (org-table-align)
1263 (when (or (not org-table-fix-formulas-confirm)
1264 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1265 (org-table-fix-formulas "$" nil (1- col) 1)
1266 (org-table-fix-formulas "$LR" nil (1- col) 1))))
1268 (defun org-table-find-dataline ()
1269 "Find a data line in the current table, which is needed for column commands."
1270 (if (and (org-at-table-p)
1271 (not (org-at-table-hline-p)))
1273 (let ((col (current-column))
1274 (end (org-table-end)))
1275 (org-move-to-column col)
1276 (while (and (< (point) end)
1277 (or (not (= (current-column) col))
1278 (org-at-table-hline-p)))
1279 (beginning-of-line 2)
1280 (org-move-to-column col))
1281 (if (and (org-at-table-p)
1282 (not (org-at-table-hline-p)))
1284 (error
1285 "Please position cursor in a data line for column operations")))))
1287 (defun org-table-line-to-dline (line &optional above)
1288 "Turn a buffer line number into a data line number.
1289 If there is no data line in this line, return nil.
1290 If there is no matchin dline (most likely te refrence was a hline), the
1291 first dline below it is used. When ABOVE is non-nil, the one above is used."
1292 (catch 'exit
1293 (let ((ll (length org-table-dlines))
1295 (if above
1296 (progn
1297 (setq i (1- ll))
1298 (while (> i 0)
1299 (if (<= (aref org-table-dlines i) line)
1300 (throw 'exit i))
1301 (setq i (1- i))))
1302 (setq i 1)
1303 (while (< i ll)
1304 (if (>= (aref org-table-dlines i) line)
1305 (throw 'exit i))
1306 (setq i (1+ i)))))
1307 nil))
1309 (defun org-table-delete-column ()
1310 "Delete a column from the table."
1311 (interactive)
1312 (if (not (org-at-table-p))
1313 (error "Not at a table"))
1314 (org-table-find-dataline)
1315 (org-table-check-inside-data-field)
1316 (let* ((col (org-table-current-column))
1317 (beg (org-table-begin))
1318 (end (org-table-end))
1319 ;; Current cursor position
1320 (linepos (org-current-line))
1321 (colpos col))
1322 (goto-char beg)
1323 (while (< (point) end)
1324 (if (org-at-table-hline-p)
1326 (org-table-goto-column col t)
1327 (and (looking-at "|[^|\n]+|")
1328 (replace-match "|")))
1329 (beginning-of-line 2))
1330 (move-marker end nil)
1331 (org-goto-line linepos)
1332 (org-table-goto-column colpos)
1333 (org-table-align)
1334 (when (or (not org-table-fix-formulas-confirm)
1335 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1336 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
1337 col -1 col)
1338 (org-table-fix-formulas "$LR" (list (cons (number-to-string col) "INVALID"))
1339 col -1 col))))
1341 (defun org-table-move-column-right ()
1342 "Move column to the right."
1343 (interactive)
1344 (org-table-move-column nil))
1345 (defun org-table-move-column-left ()
1346 "Move column to the left."
1347 (interactive)
1348 (org-table-move-column 'left))
1350 (defun org-table-move-column (&optional left)
1351 "Move the current column to the right. With arg LEFT, move to the left."
1352 (interactive "P")
1353 (if (not (org-at-table-p))
1354 (error "Not at a table"))
1355 (org-table-find-dataline)
1356 (org-table-check-inside-data-field)
1357 (let* ((col (org-table-current-column))
1358 (col1 (if left (1- col) col))
1359 (beg (org-table-begin))
1360 (end (org-table-end))
1361 ;; Current cursor position
1362 (linepos (org-current-line))
1363 (colpos (if left (1- col) (1+ col))))
1364 (if (and left (= col 1))
1365 (error "Cannot move column further left"))
1366 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
1367 (error "Cannot move column further right"))
1368 (goto-char beg)
1369 (while (< (point) end)
1370 (if (org-at-table-hline-p)
1372 (org-table-goto-column col1 t)
1373 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1374 (replace-match "|\\2|\\1|")))
1375 (beginning-of-line 2))
1376 (move-marker end nil)
1377 (org-goto-line linepos)
1378 (org-table-goto-column colpos)
1379 (org-table-align)
1380 (when (or (not org-table-fix-formulas-confirm)
1381 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1382 (org-table-fix-formulas
1383 "$" (list (cons (number-to-string col) (number-to-string colpos))
1384 (cons (number-to-string colpos) (number-to-string col))))
1385 (org-table-fix-formulas
1386 "$LR" (list (cons (number-to-string col) (number-to-string colpos))
1387 (cons (number-to-string colpos) (number-to-string col)))))))
1389 (defun org-table-move-row-down ()
1390 "Move table row down."
1391 (interactive)
1392 (org-table-move-row nil))
1393 (defun org-table-move-row-up ()
1394 "Move table row up."
1395 (interactive)
1396 (org-table-move-row 'up))
1398 (defun org-table-move-row (&optional up)
1399 "Move the current table line down. With arg UP, move it up."
1400 (interactive "P")
1401 (let* ((col (current-column))
1402 (pos (point))
1403 (hline1p (save-excursion (beginning-of-line 1)
1404 (looking-at org-table-hline-regexp)))
1405 (dline1 (org-table-current-dline))
1406 (dline2 (+ dline1 (if up -1 1)))
1407 (tonew (if up 0 2))
1408 txt hline2p)
1409 (beginning-of-line tonew)
1410 (unless (org-at-table-p)
1411 (goto-char pos)
1412 (error "Cannot move row further"))
1413 (setq hline2p (looking-at org-table-hline-regexp))
1414 (goto-char pos)
1415 (beginning-of-line 1)
1416 (setq pos (point))
1417 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
1418 (delete-region (point) (1+ (point-at-eol)))
1419 (beginning-of-line tonew)
1420 (insert txt)
1421 (beginning-of-line 0)
1422 (org-move-to-column col)
1423 (unless (or hline1p hline2p
1424 (not (or (not org-table-fix-formulas-confirm)
1425 (funcall org-table-fix-formulas-confirm
1426 "Fix formulas? "))))
1427 (org-table-fix-formulas
1428 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
1429 (cons (number-to-string dline2) (number-to-string dline1)))))))
1431 (defun org-table-insert-row (&optional arg)
1432 "Insert a new row above the current line into the table.
1433 With prefix ARG, insert below the current line."
1434 (interactive "P")
1435 (if (not (org-at-table-p))
1436 (error "Not at a table"))
1437 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1438 (new (org-table-clean-line line)))
1439 ;; Fix the first field if necessary
1440 (if (string-match "^[ \t]*| *[#$] *|" line)
1441 (setq new (replace-match (match-string 0 line) t t new)))
1442 (beginning-of-line (if arg 2 1))
1443 (let (org-table-may-need-update) (insert-before-markers new "\n"))
1444 (beginning-of-line 0)
1445 (re-search-forward "| ?" (point-at-eol) t)
1446 (and (or org-table-may-need-update org-table-overlay-coordinates)
1447 (org-table-align))
1448 (when (or (not org-table-fix-formulas-confirm)
1449 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1450 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1))))
1452 (defun org-table-insert-hline (&optional above)
1453 "Insert a horizontal-line below the current line into the table.
1454 With prefix ABOVE, insert above the current line."
1455 (interactive "P")
1456 (if (not (org-at-table-p))
1457 (error "Not at a table"))
1458 (when (eobp) (insert "\n") (backward-char 1))
1459 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1460 (org-table-align))
1461 (let ((line (org-table-clean-line
1462 (buffer-substring (point-at-bol) (point-at-eol))))
1463 (col (current-column)))
1464 (while (string-match "|\\( +\\)|" line)
1465 (setq line (replace-match
1466 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1467 ?-) "|") t t line)))
1468 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
1469 (beginning-of-line (if above 1 2))
1470 (insert line "\n")
1471 (beginning-of-line (if above 1 -1))
1472 (org-move-to-column col)
1473 (and org-table-overlay-coordinates (org-table-align))))
1475 (defun org-table-hline-and-move (&optional same-column)
1476 "Insert a hline and move to the row below that line."
1477 (interactive "P")
1478 (let ((col (org-table-current-column)))
1479 (org-table-maybe-eval-formula)
1480 (org-table-maybe-recalculate-line)
1481 (org-table-insert-hline)
1482 (end-of-line 2)
1483 (if (looking-at "\n[ \t]*|-")
1484 (progn (insert "\n|") (org-table-align))
1485 (org-table-next-field))
1486 (if same-column (org-table-goto-column col))))
1488 (defun org-table-clean-line (s)
1489 "Convert a table line S into a string with only \"|\" and space.
1490 In particular, this does handle wide and invisible characters."
1491 (if (string-match "^[ \t]*|-" s)
1492 ;; It's a hline, just map the characters
1493 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
1494 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
1495 (setq s (replace-match
1496 (concat "|" (make-string (org-string-width (match-string 1 s))
1497 ?\ ) "|")
1498 t t s)))
1501 (defun org-table-kill-row ()
1502 "Delete the current row or horizontal line from the table."
1503 (interactive)
1504 (if (not (org-at-table-p))
1505 (error "Not at a table"))
1506 (let ((col (current-column))
1507 (dline (org-table-current-dline)))
1508 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1509 (if (not (org-at-table-p)) (beginning-of-line 0))
1510 (org-move-to-column col)
1511 (when (or (not org-table-fix-formulas-confirm)
1512 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1513 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
1514 dline -1 dline))))
1516 (defun org-table-sort-lines (with-case &optional sorting-type)
1517 "Sort table lines according to the column at point.
1519 The position of point indicates the column to be used for
1520 sorting, and the range of lines is the range between the nearest
1521 horizontal separator lines, or the entire table of no such lines
1522 exist. If point is before the first column, you will be prompted
1523 for the sorting column. If there is an active region, the mark
1524 specifies the first line and the sorting column, while point
1525 should be in the last line to be included into the sorting.
1527 The command then prompts for the sorting type which can be
1528 alphabetically, numerically, or by time (as given in a time stamp
1529 in the field). Sorting in reverse order is also possible.
1531 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1533 If SORTING-TYPE is specified when this function is called from a Lisp
1534 program, no prompting will take place. SORTING-TYPE must be a character,
1535 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1536 should be done in reverse order."
1537 (interactive "P")
1538 (let* ((thisline (org-current-line))
1539 (thiscol (org-table-current-column))
1540 beg end bcol ecol tend tbeg column lns pos)
1541 (when (equal thiscol 0)
1542 (if (interactive-p)
1543 (setq thiscol
1544 (string-to-number
1545 (read-string "Use column N for sorting: ")))
1546 (setq thiscol 1))
1547 (org-table-goto-column thiscol))
1548 (org-table-check-inside-data-field)
1549 (if (org-region-active-p)
1550 (progn
1551 (setq beg (region-beginning) end (region-end))
1552 (goto-char beg)
1553 (setq column (org-table-current-column)
1554 beg (point-at-bol))
1555 (goto-char end)
1556 (setq end (point-at-bol 2)))
1557 (setq column (org-table-current-column)
1558 pos (point)
1559 tbeg (org-table-begin)
1560 tend (org-table-end))
1561 (if (re-search-backward org-table-hline-regexp tbeg t)
1562 (setq beg (point-at-bol 2))
1563 (goto-char tbeg)
1564 (setq beg (point-at-bol 1)))
1565 (goto-char pos)
1566 (if (re-search-forward org-table-hline-regexp tend t)
1567 (setq end (point-at-bol 1))
1568 (goto-char tend)
1569 (setq end (point-at-bol))))
1570 (setq beg (move-marker (make-marker) beg)
1571 end (move-marker (make-marker) end))
1572 (untabify beg end)
1573 (goto-char beg)
1574 (org-table-goto-column column)
1575 (skip-chars-backward "^|")
1576 (setq bcol (current-column))
1577 (org-table-goto-column (1+ column))
1578 (skip-chars-backward "^|")
1579 (setq ecol (1- (current-column)))
1580 (org-table-goto-column column)
1581 (setq lns (mapcar (lambda(x) (cons
1582 (org-sort-remove-invisible
1583 (nth (1- column)
1584 (org-split-string x "[ \t]*|[ \t]*")))
1586 (org-split-string (buffer-substring beg end) "\n")))
1587 (setq lns (org-do-sort lns "Table" with-case sorting-type))
1588 (delete-region beg end)
1589 (move-marker beg nil)
1590 (move-marker end nil)
1591 (insert (mapconcat 'cdr lns "\n") "\n")
1592 (org-goto-line thisline)
1593 (org-table-goto-column thiscol)
1594 (message "%d lines sorted, based on column %d" (length lns) column)))
1597 (defun org-table-cut-region (beg end)
1598 "Copy region in table to the clipboard and blank all relevant fields.
1599 If there is no active region, use just the field at point."
1600 (interactive (list
1601 (if (org-region-active-p) (region-beginning) (point))
1602 (if (org-region-active-p) (region-end) (point))))
1603 (org-table-copy-region beg end 'cut))
1605 (defun org-table-copy-region (beg end &optional cut)
1606 "Copy rectangular region in table to clipboard.
1607 A special clipboard is used which can only be accessed
1608 with `org-table-paste-rectangle'."
1609 (interactive (list
1610 (if (org-region-active-p) (region-beginning) (point))
1611 (if (org-region-active-p) (region-end) (point))
1612 current-prefix-arg))
1613 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1614 region cols
1615 (rpl (if cut " " nil)))
1616 (goto-char beg)
1617 (org-table-check-inside-data-field)
1618 (setq l01 (org-current-line)
1619 c01 (org-table-current-column))
1620 (goto-char end)
1621 (org-table-check-inside-data-field)
1622 (setq l02 (org-current-line)
1623 c02 (org-table-current-column))
1624 (setq l1 (min l01 l02) l2 (max l01 l02)
1625 c1 (min c01 c02) c2 (max c01 c02))
1626 (catch 'exit
1627 (while t
1628 (catch 'nextline
1629 (if (> l1 l2) (throw 'exit t))
1630 (org-goto-line l1)
1631 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
1632 (setq cols nil ic1 c1 ic2 c2)
1633 (while (< ic1 (1+ ic2))
1634 (push (org-table-get-field ic1 rpl) cols)
1635 (setq ic1 (1+ ic1)))
1636 (push (nreverse cols) region)
1637 (setq l1 (1+ l1)))))
1638 (setq org-table-clip (nreverse region))
1639 (if cut (org-table-align))
1640 org-table-clip))
1642 (defun org-table-paste-rectangle ()
1643 "Paste a rectangular region into a table.
1644 The upper right corner ends up in the current field. All involved fields
1645 will be overwritten. If the rectangle does not fit into the present table,
1646 the table is enlarged as needed. The process ignores horizontal separator
1647 lines."
1648 (interactive)
1649 (unless (and org-table-clip (listp org-table-clip))
1650 (error "First cut/copy a region to paste!"))
1651 (org-table-check-inside-data-field)
1652 (let* ((clip org-table-clip)
1653 (line (org-current-line))
1654 (col (org-table-current-column))
1655 (org-enable-table-editor t)
1656 (org-table-automatic-realign nil)
1657 c cols field)
1658 (while (setq cols (pop clip))
1659 (while (org-at-table-hline-p) (beginning-of-line 2))
1660 (if (not (org-at-table-p))
1661 (progn (end-of-line 0) (org-table-next-field)))
1662 (setq c col)
1663 (while (setq field (pop cols))
1664 (org-table-goto-column c nil 'force)
1665 (org-table-get-field nil field)
1666 (setq c (1+ c)))
1667 (beginning-of-line 2))
1668 (org-goto-line line)
1669 (org-table-goto-column col)
1670 (org-table-align)))
1672 (defun org-table-convert ()
1673 "Convert from `org-mode' table to table.el and back.
1674 Obviously, this only works within limits. When an Org-mode table is
1675 converted to table.el, all horizontal separator lines get lost, because
1676 table.el uses these as cell boundaries and has no notion of horizontal lines.
1677 A table.el table can be converted to an Org-mode table only if it does not
1678 do row or column spanning. Multiline cells will become multiple cells.
1679 Beware, Org-mode does not test if the table can be successfully converted - it
1680 blindly applies a recipe that works for simple tables."
1681 (interactive)
1682 (require 'table)
1683 (if (org-at-table.el-p)
1684 ;; convert to Org-mode table
1685 (let ((beg (move-marker (make-marker) (org-table-begin t)))
1686 (end (move-marker (make-marker) (org-table-end t))))
1687 (table-unrecognize-region beg end)
1688 (goto-char beg)
1689 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
1690 (replace-match ""))
1691 (goto-char beg))
1692 (if (org-at-table-p)
1693 ;; convert to table.el table
1694 (let ((beg (move-marker (make-marker) (org-table-begin)))
1695 (end (move-marker (make-marker) (org-table-end))))
1696 ;; first, get rid of all horizontal lines
1697 (goto-char beg)
1698 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
1699 (replace-match ""))
1700 ;; insert a hline before first
1701 (goto-char beg)
1702 (org-table-insert-hline 'above)
1703 (beginning-of-line -1)
1704 ;; insert a hline after each line
1705 (while (progn (beginning-of-line 3) (< (point) end))
1706 (org-table-insert-hline))
1707 (goto-char beg)
1708 (setq end (move-marker end (org-table-end)))
1709 ;; replace "+" at beginning and ending of hlines
1710 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
1711 (replace-match "\\1+-"))
1712 (goto-char beg)
1713 (while (re-search-forward "-|[ \t]*$" end t)
1714 (replace-match "-+"))
1715 (goto-char beg)))))
1717 (defun org-table-wrap-region (arg)
1718 "Wrap several fields in a column like a paragraph.
1719 This is useful if you'd like to spread the contents of a field over several
1720 lines, in order to keep the table compact.
1722 If there is an active region, and both point and mark are in the same column,
1723 the text in the column is wrapped to minimum width for the given number of
1724 lines. Generally, this makes the table more compact. A prefix ARG may be
1725 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1726 formats the selected text to two lines. If the region was longer than two
1727 lines, the remaining lines remain empty. A negative prefix argument reduces
1728 the current number of lines by that amount. The wrapped text is pasted back
1729 into the table. If you formatted it to more lines than it was before, fields
1730 further down in the table get overwritten - so you might need to make space in
1731 the table first.
1733 If there is no region, the current field is split at the cursor position and
1734 the text fragment to the right of the cursor is prepended to the field one
1735 line down.
1737 If there is no region, but you specify a prefix ARG, the current field gets
1738 blank, and the content is appended to the field above."
1739 (interactive "P")
1740 (org-table-check-inside-data-field)
1741 (if (org-region-active-p)
1742 ;; There is a region: fill as a paragraph
1743 (let* ((beg (region-beginning))
1744 (cline (save-excursion (goto-char beg) (org-current-line)))
1745 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
1746 nlines)
1747 (org-table-cut-region (region-beginning) (region-end))
1748 (if (> (length (car org-table-clip)) 1)
1749 (error "Region must be limited to single column"))
1750 (setq nlines (if arg
1751 (if (< arg 1)
1752 (+ (length org-table-clip) arg)
1753 arg)
1754 (length org-table-clip)))
1755 (setq org-table-clip
1756 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
1757 nil nlines)))
1758 (org-goto-line cline)
1759 (org-table-goto-column ccol)
1760 (org-table-paste-rectangle))
1761 ;; No region, split the current field at point
1762 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
1763 (skip-chars-forward "^\r\n|"))
1764 (if arg
1765 ;; combine with field above
1766 (let ((s (org-table-blank-field))
1767 (col (org-table-current-column)))
1768 (beginning-of-line 0)
1769 (while (org-at-table-hline-p) (beginning-of-line 0))
1770 (org-table-goto-column col)
1771 (skip-chars-forward "^|")
1772 (skip-chars-backward " ")
1773 (insert " " (org-trim s))
1774 (org-table-align))
1775 ;; split field
1776 (if (looking-at "\\([^|]+\\)+|")
1777 (let ((s (match-string 1)))
1778 (replace-match " |")
1779 (goto-char (match-beginning 0))
1780 (org-table-next-row)
1781 (insert (org-trim s) " ")
1782 (org-table-align))
1783 (org-table-next-row)))))
1785 (defvar org-field-marker nil)
1787 (defun org-table-edit-field (arg)
1788 "Edit table field in a different window.
1789 This is mainly useful for fields that contain hidden parts.
1790 When called with a \\[universal-argument] prefix, just make the full field visible so that
1791 it can be edited in place."
1792 (interactive "P")
1793 (cond
1794 ((equal arg '(16))
1795 (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
1796 (arg
1797 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1798 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1799 (remove-text-properties b e '(org-cwidth t invisible t
1800 display t intangible t))
1801 (if (and (boundp 'font-lock-mode) font-lock-mode)
1802 (font-lock-fontify-block))))
1804 (let ((pos (move-marker (make-marker) (point)))
1805 (field (org-table-get-field))
1806 (cw (current-window-configuration))
1808 (goto-char pos)
1809 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
1810 (when (and (local-variable-p 'org-field-marker)
1811 (markerp org-field-marker))
1812 (move-marker org-field-marker nil))
1813 (erase-buffer)
1814 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
1815 (let ((org-inhibit-startup t)) (org-mode))
1816 (auto-fill-mode -1)
1817 (setq truncate-lines nil)
1818 (setq word-wrap t)
1819 (goto-char (setq p (point-max)))
1820 (insert (org-trim field))
1821 (remove-text-properties p (point-max)
1822 '(invisible t org-cwidth t display t
1823 intangible t))
1824 (goto-char p)
1825 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
1826 (org-set-local 'org-window-configuration cw)
1827 (org-set-local 'org-field-marker pos)
1828 (message "Edit and finish with C-c C-c")))))
1830 (defun org-table-finish-edit-field ()
1831 "Finish editing a table data field.
1832 Remove all newline characters, insert the result into the table, realign
1833 the table and kill the editing buffer."
1834 (let ((pos org-field-marker)
1835 (cw org-window-configuration)
1836 (cb (current-buffer))
1837 text)
1838 (goto-char (point-min))
1839 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
1840 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
1841 (replace-match " "))
1842 (setq text (org-trim (buffer-string)))
1843 (set-window-configuration cw)
1844 (kill-buffer cb)
1845 (select-window (get-buffer-window (marker-buffer pos)))
1846 (goto-char pos)
1847 (move-marker pos nil)
1848 (org-table-check-inside-data-field)
1849 (org-table-get-field nil text)
1850 (org-table-align)
1851 (message "New field value inserted")))
1853 (define-minor-mode org-table-follow-field-mode
1854 "Minor mode to make the table field editor window follow the cursor.
1855 When this mode is active, the field editor window will always show the
1856 current field. The mode exits automatically when the cursor leaves the
1857 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
1858 nil " TblFollow" nil
1859 (if org-table-follow-field-mode
1860 (org-add-hook 'post-command-hook 'org-table-follow-fields-with-editor
1861 'append 'local)
1862 (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
1863 (let* ((buf (get-buffer "*Org Table Edit Field*"))
1864 (win (and buf (get-buffer-window buf))))
1865 (when win (delete-window win))
1866 (when buf
1867 (with-current-buffer buf
1868 (move-marker org-field-marker nil))
1869 (kill-buffer buf)))))
1871 (defun org-table-follow-fields-with-editor ()
1872 (if (and org-table-exit-follow-field-mode-when-leaving-table
1873 (not (org-at-table-p)))
1874 ;; We have left the table, exit the follow mode
1875 (org-table-follow-field-mode -1)
1876 (when (org-table-check-inside-data-field 'noerror)
1877 (let ((win (selected-window)))
1878 (org-table-edit-field nil)
1879 (org-fit-window-to-buffer)
1880 (select-window win)))))
1882 (defvar org-timecnt) ; dynamically scoped parameter
1884 (defun org-table-sum (&optional beg end nlast)
1885 "Sum numbers in region of current table column.
1886 The result will be displayed in the echo area, and will be available
1887 as kill to be inserted with \\[yank].
1889 If there is an active region, it is interpreted as a rectangle and all
1890 numbers in that rectangle will be summed. If there is no active
1891 region and point is located in a table column, sum all numbers in that
1892 column.
1894 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1895 numbers are assumed to be times as well (in decimal hours) and the
1896 numbers are added as such.
1898 If NLAST is a number, only the NLAST fields will actually be summed."
1899 (interactive)
1900 (save-excursion
1901 (let (col (org-timecnt 0) diff h m s org-table-clip)
1902 (cond
1903 ((and beg end)) ; beg and end given explicitly
1904 ((org-region-active-p)
1905 (setq beg (region-beginning) end (region-end)))
1907 (setq col (org-table-current-column))
1908 (goto-char (org-table-begin))
1909 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
1910 (error "No table data"))
1911 (org-table-goto-column col)
1912 (setq beg (point))
1913 (goto-char (org-table-end))
1914 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
1915 (error "No table data"))
1916 (org-table-goto-column col)
1917 (setq end (point))))
1918 (let* ((items (apply 'append (org-table-copy-region beg end)))
1919 (items1 (cond ((not nlast) items)
1920 ((>= nlast (length items)) items)
1921 (t (setq items (reverse items))
1922 (setcdr (nthcdr (1- nlast) items) nil)
1923 (nreverse items))))
1924 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
1925 items1)))
1926 (res (apply '+ numbers))
1927 (sres (if (= org-timecnt 0)
1928 (number-to-string res)
1929 (setq diff (* 3600 res)
1930 h (floor (/ diff 3600)) diff (mod diff 3600)
1931 m (floor (/ diff 60)) diff (mod diff 60)
1932 s diff)
1933 (format "%d:%02d:%02d" h m s))))
1934 (kill-new sres)
1935 (if (interactive-p)
1936 (message "%s"
1937 (substitute-command-keys
1938 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
1939 (length numbers) sres))))
1940 sres))))
1942 (defun org-table-get-number-for-summing (s)
1943 (let (n)
1944 (if (string-match "^ *|? *" s)
1945 (setq s (replace-match "" nil nil s)))
1946 (if (string-match " *|? *$" s)
1947 (setq s (replace-match "" nil nil s)))
1948 (setq n (string-to-number s))
1949 (cond
1950 ((and (string-match "0" s)
1951 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
1952 ((string-match "\\`[ \t]+\\'" s) nil)
1953 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
1954 (let ((h (string-to-number (or (match-string 1 s) "0")))
1955 (m (string-to-number (or (match-string 2 s) "0")))
1956 (s (string-to-number (or (match-string 4 s) "0"))))
1957 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
1958 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
1959 ((equal n 0) nil)
1960 (t n))))
1962 (defun org-table-current-field-formula (&optional key noerror)
1963 "Return the formula active for the current field.
1964 Assumes that specials are in place.
1965 If KEY is given, return the key to this formula.
1966 Otherwise return the formula preceded with \"=\" or \":=\"."
1967 (let* ((name (car (rassoc (list (org-current-line)
1968 (org-table-current-column))
1969 org-table-named-field-locations)))
1970 (col (org-table-current-column))
1971 (scol (int-to-string col))
1972 (ref (format "@%d$%d" (org-table-current-dline) col))
1973 (stored-list (org-table-get-stored-formulas noerror))
1974 (ass (or (assoc name stored-list)
1975 (assoc ref stored-list)
1976 (assoc scol stored-list))))
1977 (if key
1978 (car ass)
1979 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
1980 (cdr ass))))))
1982 (defun org-table-get-formula (&optional equation named)
1983 "Read a formula from the minibuffer, offer stored formula as default.
1984 When NAMED is non-nil, look for a named equation."
1985 (let* ((stored-list (org-table-get-stored-formulas))
1986 (name (car (rassoc (list (org-current-line)
1987 (org-table-current-column))
1988 org-table-named-field-locations)))
1989 (ref (format "@%d$%d" (org-table-current-dline)
1990 (org-table-current-column)))
1991 (refass (assoc ref stored-list))
1992 (nameass (assoc name stored-list))
1993 (scol (if named
1994 (if (and name (not (string-match "^LR[0-9]+$" name)))
1995 name
1996 ref)
1997 (int-to-string (org-table-current-column))))
1998 (dummy (and (or nameass refass) (not named)
1999 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2000 (error "Abort")))
2001 (name (or name ref))
2002 (org-table-may-need-update nil)
2003 (stored (cdr (assoc scol stored-list)))
2004 (eq (cond
2005 ((and stored equation (string-match "^ *=? *$" equation))
2006 stored)
2007 ((stringp equation)
2008 equation)
2009 (t (org-table-formula-from-user
2010 (read-string
2011 (org-table-formula-to-user
2012 (format "%s formula %s%s="
2013 (if named "Field" "Column")
2014 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
2015 scol))
2016 (if stored (org-table-formula-to-user stored) "")
2017 'org-table-formula-history
2018 )))))
2019 mustsave)
2020 (when (not (string-match "\\S-" eq))
2021 ;; remove formula
2022 (setq stored-list (delq (assoc scol stored-list) stored-list))
2023 (org-table-store-formulas stored-list)
2024 (error "Formula removed"))
2025 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
2026 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
2027 (if (and name (not named))
2028 ;; We set the column equation, delete the named one.
2029 (setq stored-list (delq (assoc name stored-list) stored-list)
2030 mustsave t))
2031 (if stored
2032 (setcdr (assoc scol stored-list) eq)
2033 (setq stored-list (cons (cons scol eq) stored-list)))
2034 (if (or mustsave (not (equal stored eq)))
2035 (org-table-store-formulas stored-list))
2036 eq))
2038 (defun org-table-store-formulas (alist)
2039 "Store the list of formulas below the current table."
2040 (setq alist (sort alist 'org-table-formula-less-p))
2041 (save-excursion
2042 (goto-char (org-table-end))
2043 (if (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM:\\(.*\n?\\)")
2044 (progn
2045 ;; don't overwrite TBLFM, we might use text properties to store stuff
2046 (goto-char (match-beginning 2))
2047 (delete-region (match-beginning 2) (match-end 0)))
2048 (org-indent-line-function)
2049 (insert "#+TBLFM:"))
2050 (insert " "
2051 (mapconcat (lambda (x)
2052 (concat
2053 (if (equal (string-to-char (car x)) ?@) "" "$")
2054 (car x) "=" (cdr x)))
2055 alist "::")
2056 "\n")))
2058 (defsubst org-table-formula-make-cmp-string (a)
2059 (when (string-match "\\`$[<>]" a)
2060 (let ((arrow (string-to-char (substring a 1))))
2061 ;; Fake a high number to make sure this is sorted at the end.
2062 (setq a (org-table-formula-handle-first/last-rc a))
2063 (setq a (format "$%d" (+ 10000
2064 (if (= arrow ?<) -1000 0)
2065 (string-to-number (substring a 1)))))))
2066 (when (string-match
2067 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2069 (concat
2070 (if (match-end 2)
2071 (format "@%05d" (string-to-number (match-string 2 a))) "")
2072 (if (match-end 4)
2073 (format "$%05d" (string-to-number (match-string 4 a))) "")
2074 (if (match-end 5)
2075 (concat "@@" (match-string 5 a))))))
2077 (defun org-table-formula-less-p (a b)
2078 "Compare two formulas for sorting."
2079 (let ((as (org-table-formula-make-cmp-string (car a)))
2080 (bs (org-table-formula-make-cmp-string (car b))))
2081 (and as bs (string< as bs))))
2083 (defun org-table-get-stored-formulas (&optional noerror)
2084 "Return an alist with the stored formulas directly after current table."
2085 (interactive)
2086 (let (scol eq eq-alist strings string seen)
2087 (save-excursion
2088 (goto-char (org-table-end))
2089 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
2090 (setq strings (org-split-string (org-match-string-no-properties 2)
2091 " *:: *"))
2092 (while (setq string (pop strings))
2093 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string)
2094 (setq scol (if (match-end 2)
2095 (match-string 2 string)
2096 (match-string 1 string))
2097 scol (if (member (string-to-char scol) '(?< ?>))
2098 (concat "$" scol) scol)
2099 eq (match-string 3 string)
2100 eq-alist (cons (cons scol eq) eq-alist))
2101 (if (member scol seen)
2102 (if noerror
2103 (progn
2104 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
2105 (ding)
2106 (sit-for 2))
2107 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
2108 (push scol seen))))))
2109 (nreverse eq-alist)))
2111 (defun org-table-fix-formulas (key replace &optional limit delta remove)
2112 "Modify the equations after the table structure has been edited.
2113 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2114 For all numbers larger than LIMIT, shift them by DELTA."
2115 (save-excursion
2116 (goto-char (org-table-end))
2117 (when (looking-at "[ \t]*#\\+TBLFM:")
2118 (let ((re (concat key "\\([0-9]+\\)"))
2119 (re2
2120 (when remove
2121 (if (or (equal key "$") (equal key "$LR"))
2122 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2123 (regexp-quote key) remove)
2124 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
2125 s n a)
2126 (when remove
2127 (while (re-search-forward re2 (point-at-eol) t)
2128 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2129 (replace-match ""))))
2130 (while (re-search-forward re (point-at-eol) t)
2131 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2132 (setq s (match-string 1) n (string-to-number s))
2133 (cond
2134 ((setq a (assoc s replace))
2135 (replace-match (concat key (cdr a)) t t))
2136 ((and limit (> n limit))
2137 (replace-match (concat key (int-to-string (+ n delta)))
2138 t t)))))))))
2140 (defun org-table-get-specials ()
2141 "Get the column names and local parameters for this table."
2142 (save-excursion
2143 (let ((beg (org-table-begin)) (end (org-table-end))
2144 names name fields fields1 field cnt
2145 c v l line col types dlines hlines last-dline)
2146 (setq org-table-column-names nil
2147 org-table-local-parameters nil
2148 org-table-named-field-locations nil
2149 org-table-current-begin-line nil
2150 org-table-current-begin-pos nil
2151 org-table-current-line-types nil
2152 org-table-current-ncol 0)
2153 (goto-char beg)
2154 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
2155 (setq names (org-split-string (match-string 1) " *| *")
2156 cnt 1)
2157 (while (setq name (pop names))
2158 (setq cnt (1+ cnt))
2159 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
2160 (push (cons name (int-to-string cnt)) org-table-column-names))))
2161 (setq org-table-column-names (nreverse org-table-column-names))
2162 (setq org-table-column-name-regexp
2163 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
2164 (goto-char beg)
2165 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
2166 (setq fields (org-split-string (match-string 1) " *| *"))
2167 (while (setq field (pop fields))
2168 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
2169 (push (cons (match-string 1 field) (match-string 2 field))
2170 org-table-local-parameters))))
2171 (goto-char beg)
2172 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
2173 (setq c (match-string 1)
2174 fields (org-split-string (match-string 2) " *| *"))
2175 (save-excursion
2176 (beginning-of-line (if (equal c "_") 2 0))
2177 (setq line (org-current-line) col 1)
2178 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2179 (setq fields1 (org-split-string (match-string 1) " *| *"))))
2180 (while (and fields1 (setq field (pop fields)))
2181 (setq v (pop fields1) col (1+ col))
2182 (when (and (stringp field) (stringp v)
2183 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
2184 (push (cons field v) org-table-local-parameters)
2185 (push (list field line col) org-table-named-field-locations))))
2186 ;; Analyse the line types
2187 (goto-char beg)
2188 (setq org-table-current-begin-line (org-current-line)
2189 org-table-current-begin-pos (point)
2190 l org-table-current-begin-line)
2191 (while (looking-at "[ \t]*|\\(-\\)?")
2192 (push (if (match-end 1) 'hline 'dline) types)
2193 (if (match-end 1) (push l hlines) (push l dlines))
2194 (beginning-of-line 2)
2195 (setq l (1+ l)))
2196 (push 'hline types) ;; add an imaginary extra hline to the end
2197 (setq org-table-current-line-types (apply 'vector (nreverse types))
2198 last-dline (car dlines)
2199 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
2200 org-table-hlines (apply 'vector (cons nil (nreverse hlines))))
2201 (org-goto-line last-dline)
2202 (let* ((l last-dline)
2203 (fields (org-split-string
2204 (buffer-substring (point-at-bol) (point-at-eol))
2205 "[ \t]*|[ \t]*"))
2206 (nfields (length fields))
2207 al al2)
2208 (setq org-table-current-ncol nfields)
2209 (loop for i from 1 to nfields do
2210 (push (list (format "LR%d" i) l i) al)
2211 (push (cons (format "LR%d" i) (nth (1- i) fields)) al2))
2212 (setq org-table-named-field-locations
2213 (append org-table-named-field-locations al))
2214 (setq org-table-local-parameters
2215 (append org-table-local-parameters al2))))))
2217 (defun org-table-maybe-eval-formula ()
2218 "Check if the current field starts with \"=\" or \":=\".
2219 If yes, store the formula and apply it."
2220 ;; We already know we are in a table. Get field will only return a formula
2221 ;; when appropriate. It might return a separator line, but no problem.
2222 (when org-table-formula-evaluate-inline
2223 (let* ((field (org-trim (or (org-table-get-field) "")))
2224 named eq)
2225 (when (string-match "^:?=\\(.*\\)" field)
2226 (setq named (equal (string-to-char field) ?:)
2227 eq (match-string 1 field))
2228 (if (or (fboundp 'calc-eval)
2229 (equal (substring eq 0 (min 2 (length eq))) "'("))
2230 (org-table-eval-formula (if named '(4) nil)
2231 (org-table-formula-from-user eq))
2232 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2234 (defvar org-recalc-commands nil
2235 "List of commands triggering the recalculation of a line.
2236 Will be filled automatically during use.")
2238 (defvar org-recalc-marks
2239 '((" " . "Unmarked: no special line, no automatic recalculation")
2240 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2241 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
2242 ("!" . "Column name definition line. Reference in formula as $name.")
2243 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
2244 ("_" . "Names for values in row below this one.")
2245 ("^" . "Names for values in row above this one.")))
2247 (defun org-table-rotate-recalc-marks (&optional newchar)
2248 "Rotate the recalculation mark in the first column.
2249 If in any row, the first field is not consistent with a mark,
2250 insert a new column for the markers.
2251 When there is an active region, change all the lines in the region,
2252 after prompting for the marking character.
2253 After each change, a message will be displayed indicating the meaning
2254 of the new mark."
2255 (interactive)
2256 (unless (org-at-table-p) (error "Not at a table"))
2257 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
2258 (beg (org-table-begin))
2259 (end (org-table-end))
2260 (l (org-current-line))
2261 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2262 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2263 (have-col
2264 (save-excursion
2265 (goto-char beg)
2266 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
2267 (col (org-table-current-column))
2268 (forcenew (car (assoc newchar org-recalc-marks)))
2269 epos new)
2270 (when l1
2271 (message "Change region to what mark? Type # * ! $ or SPC: ")
2272 (setq newchar (char-to-string (read-char-exclusive))
2273 forcenew (car (assoc newchar org-recalc-marks))))
2274 (if (and newchar (not forcenew))
2275 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2276 newchar))
2277 (if l1 (org-goto-line l1))
2278 (save-excursion
2279 (beginning-of-line 1)
2280 (unless (looking-at org-table-dataline-regexp)
2281 (error "Not at a table data line")))
2282 (unless have-col
2283 (org-table-goto-column 1)
2284 (org-table-insert-column)
2285 (org-table-goto-column (1+ col)))
2286 (setq epos (point-at-eol))
2287 (save-excursion
2288 (beginning-of-line 1)
2289 (org-table-get-field
2290 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2291 (concat " "
2292 (setq new (or forcenew
2293 (cadr (member (match-string 1) marks))))
2294 " ")
2295 " # ")))
2296 (if (and l1 l2)
2297 (progn
2298 (org-goto-line l1)
2299 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
2300 (and (looking-at org-table-dataline-regexp)
2301 (org-table-get-field 1 (concat " " new " "))))
2302 (org-goto-line l1)))
2303 (if (not (= epos (point-at-eol))) (org-table-align))
2304 (org-goto-line l)
2305 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
2307 (defun org-table-maybe-recalculate-line ()
2308 "Recompute the current line if marked for it, and if we haven't just done it."
2309 (interactive)
2310 (and org-table-allow-automatic-line-recalculation
2311 (not (and (memq last-command org-recalc-commands)
2312 (equal org-last-recalc-line (org-current-line))))
2313 (save-excursion (beginning-of-line 1)
2314 (looking-at org-table-auto-recalculate-regexp))
2315 (org-table-recalculate) t))
2317 (defvar modes)
2318 (defsubst org-set-calc-mode (var &optional value)
2319 (if (stringp var)
2320 (setq var (assoc var '(("D" calc-angle-mode deg)
2321 ("R" calc-angle-mode rad)
2322 ("F" calc-prefer-frac t)
2323 ("S" calc-symbolic-mode t)))
2324 value (nth 2 var) var (nth 1 var)))
2325 (if (memq var modes)
2326 (setcar (cdr (memq var modes)) value)
2327 (cons var (cons value modes)))
2328 modes)
2330 (defun org-table-eval-formula (&optional arg equation
2331 suppress-align suppress-const
2332 suppress-store suppress-analysis)
2333 "Replace the table field value at the cursor by the result of a calculation.
2335 This function makes use of Dave Gillespie's Calc package, in my view the
2336 most exciting program ever written for GNU Emacs. So you need to have Calc
2337 installed in order to use this function.
2339 In a table, this command replaces the value in the current field with the
2340 result of a formula. It also installs the formula as the \"current\" column
2341 formula, by storing it in a special line below the table. When called
2342 with a `C-u' prefix, the current field must be a named field, and the
2343 formula is installed as valid in only this specific field.
2345 When called with two `C-u' prefixes, insert the active equation
2346 for the field back into the current field, so that it can be
2347 edited there. This is useful in order to use \\[org-table-show-reference]
2348 to check the referenced fields.
2350 When called, the command first prompts for a formula, which is read in
2351 the minibuffer. Previously entered formulas are available through the
2352 history list, and the last used formula is offered as a default.
2353 These stored formulas are adapted correctly when moving, inserting, or
2354 deleting columns with the corresponding commands.
2356 The formula can be any algebraic expression understood by the Calc package.
2357 For details, see the Org-mode manual.
2359 This function can also be called from Lisp programs and offers
2360 additional arguments: EQUATION can be the formula to apply. If this
2361 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2362 used to speed-up recursive calls by by-passing unnecessary aligns.
2363 SUPPRESS-CONST suppresses the interpretation of constants in the
2364 formula, assuming that this has been done already outside the function.
2365 SUPPRESS-STORE means the formula should not be stored, either because
2366 it is already stored, or because it is a modified equation that should
2367 not overwrite the stored one."
2368 (interactive "P")
2369 (org-table-check-inside-data-field)
2370 (or suppress-analysis (org-table-get-specials))
2371 (if (equal arg '(16))
2372 (let ((eq (org-table-current-field-formula)))
2373 (or eq (error "No equation active for current field"))
2374 (org-table-get-field nil eq)
2375 (org-table-align)
2376 (setq org-table-may-need-update t))
2377 (let* (fields
2378 (ndown (if (integerp arg) arg 1))
2379 (org-table-automatic-realign nil)
2380 (case-fold-search nil)
2381 (down (> ndown 1))
2382 (formula (if (and equation suppress-store)
2383 equation
2384 (org-table-get-formula equation (equal arg '(4)))))
2385 (n0 (org-table-current-column))
2386 (modes (copy-sequence org-calc-default-modes))
2387 (numbers nil) ; was a variable, now fixed default
2388 (keep-empty nil)
2389 n form form0 bw fmt x ev orig c lispp literal)
2390 ;; Parse the format string. Since we have a lot of modes, this is
2391 ;; a lot of work. However, I think calc still uses most of the time.
2392 (if (string-match ";" formula)
2393 (let ((tmp (org-split-string formula ";")))
2394 (setq formula (car tmp)
2395 fmt (concat (cdr (assoc "%" org-table-local-parameters))
2396 (nth 1 tmp)))
2397 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
2398 (setq c (string-to-char (match-string 1 fmt))
2399 n (string-to-number (match-string 2 fmt)))
2400 (if (= c ?p)
2401 (setq modes (org-set-calc-mode 'calc-internal-prec n))
2402 (setq modes (org-set-calc-mode
2403 'calc-float-format
2404 (list (cdr (assoc c '((?n . float) (?f . fix)
2405 (?s . sci) (?e . eng))))
2406 n))))
2407 (setq fmt (replace-match "" t t fmt)))
2408 (if (string-match "[NT]" fmt)
2409 (setq numbers (equal (match-string 0 fmt) "N")
2410 fmt (replace-match "" t t fmt)))
2411 (if (string-match "L" fmt)
2412 (setq literal t
2413 fmt (replace-match "" t t fmt)))
2414 (if (string-match "E" fmt)
2415 (setq keep-empty t
2416 fmt (replace-match "" t t fmt)))
2417 (while (string-match "[DRFS]" fmt)
2418 (setq modes (org-set-calc-mode (match-string 0 fmt)))
2419 (setq fmt (replace-match "" t t fmt)))
2420 (unless (string-match "\\S-" fmt)
2421 (setq fmt nil))))
2422 (if (and (not suppress-const) org-table-formula-use-constants)
2423 (setq formula (org-table-formula-substitute-names formula)))
2424 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
2425 (while (> ndown 0)
2426 (setq fields (org-split-string
2427 (org-no-properties
2428 (buffer-substring (point-at-bol) (point-at-eol)))
2429 " *| *"))
2430 (if (eq numbers t)
2431 (setq fields (mapcar
2432 (lambda (x) (number-to-string (string-to-number x)))
2433 fields)))
2434 (setq ndown (1- ndown))
2435 (setq form (copy-sequence formula)
2436 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
2437 (if (and lispp literal) (setq lispp 'literal))
2439 ;; Insert row and column number of formula result field
2440 (while (string-match "[@$]#" form)
2441 (setq form
2442 (replace-match
2443 (format "%d"
2444 (save-match-data
2445 (if (equal (substring form (match-beginning 0)
2446 (1+ (match-beginning 0)))
2447 "@")
2448 (org-table-current-dline)
2449 (org-table-current-column))))
2450 t t form)))
2452 ;; Check for old vertical references
2453 (setq form (org-table-rewrite-old-row-references form))
2454 ;; Insert remote references
2455 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
2456 (setq form
2457 (replace-match
2458 (save-match-data
2459 (org-table-make-reference
2460 (org-table-get-remote-range
2461 (match-string 1 form) (match-string 2 form))
2462 keep-empty numbers lispp))
2463 t t form)))
2464 ;; Insert complex ranges
2465 (while (and (string-match org-table-range-regexp form)
2466 (> (length (match-string 0 form)) 1))
2467 (setq form
2468 (replace-match
2469 (save-match-data
2470 (org-table-make-reference
2471 (org-table-get-range (match-string 0 form) nil n0)
2472 keep-empty numbers lispp))
2473 t t form)))
2474 ;; Insert simple ranges
2475 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
2476 (setq form
2477 (replace-match
2478 (save-match-data
2479 (org-table-make-reference
2480 (org-sublist
2481 fields (string-to-number (match-string 1 form))
2482 (string-to-number (match-string 2 form)))
2483 keep-empty numbers lispp))
2484 t t form)))
2485 (setq form0 form)
2486 ;; Insert the references to fields in same row
2487 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
2488 (setq n (+ (string-to-number (match-string 1 form))
2489 (if (match-end 2) n0 0))
2490 x (nth (1- (if (= n 0) n0 (max n 1))) fields))
2491 (unless x (error "Invalid field specifier \"%s\""
2492 (match-string 0 form)))
2493 (setq form (replace-match
2494 (save-match-data
2495 (org-table-make-reference x nil numbers lispp))
2496 t t form)))
2498 (if lispp
2499 (setq ev (condition-case nil
2500 (eval (eval (read form)))
2501 (error "#ERROR"))
2502 ev (if (numberp ev) (number-to-string ev) ev))
2503 (or (fboundp 'calc-eval)
2504 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2505 (setq ev (calc-eval (cons form modes)
2506 (if numbers 'num))))
2508 (when org-table-formula-debug
2509 (with-output-to-temp-buffer "*Substitution History*"
2510 (princ (format "Substitution history of formula
2511 Orig: %s
2512 $xyz-> %s
2513 @r$c-> %s
2514 $1-> %s\n" orig formula form0 form))
2515 (if (listp ev)
2516 (princ (format " %s^\nError: %s"
2517 (make-string (car ev) ?\-) (nth 1 ev)))
2518 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2519 ev (or fmt "NONE")
2520 (if fmt (format fmt (string-to-number ev)) ev)))))
2521 (setq bw (get-buffer-window "*Substitution History*"))
2522 (org-fit-window-to-buffer bw)
2523 (unless (and (interactive-p) (not ndown))
2524 (unless (let (inhibit-redisplay)
2525 (y-or-n-p "Debugging Formula. Continue to next? "))
2526 (org-table-align)
2527 (error "Abort"))
2528 (delete-window bw)
2529 (message "")))
2530 (if (listp ev) (setq fmt nil ev "#ERROR"))
2531 (org-table-justify-field-maybe
2532 (if fmt (format fmt (string-to-number ev)) ev))
2533 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2534 (call-interactively 'org-return)
2535 (setq ndown 0)))
2536 (and down (org-table-maybe-recalculate-line))
2537 (or suppress-align (and org-table-may-need-update
2538 (org-table-align))))))
2540 (defun org-table-put-field-property (prop value)
2541 (save-excursion
2542 (put-text-property (progn (skip-chars-backward "^|") (point))
2543 (progn (skip-chars-forward "^|") (point))
2544 prop value)))
2546 (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
2547 "Get a calc vector from a column, according to descriptor DESC.
2548 Optional arguments TBEG and COL can give the beginning of the table and
2549 the current column, to avoid unnecessary parsing.
2551 HIGHLIGHT means just highlight the range.
2553 When CORNERS-ONLY is set, only return the corners of the range as
2554 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2555 in the buffer and column1 and column2 are table column numbers."
2556 (if (not (equal (string-to-char desc) ?@))
2557 (setq desc (concat "@" desc)))
2558 (save-excursion
2559 (or tbeg (setq tbeg (org-table-begin)))
2560 (or col (setq col (org-table-current-column)))
2561 (let ((thisline (org-current-line))
2562 beg end c1 c2 r1 r2 rangep tmp)
2563 (unless (string-match org-table-range-regexp desc)
2564 (error "Invalid table range specifier `%s'" desc))
2565 (setq rangep (match-end 3)
2566 r1 (and (match-end 1) (match-string 1 desc))
2567 r2 (and (match-end 4) (match-string 4 desc))
2568 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
2569 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
2571 (and c1 (setq c1 (+ (string-to-number c1)
2572 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
2573 (and c2 (setq c2 (+ (string-to-number c2)
2574 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
2575 (if (equal r1 "") (setq r1 nil))
2576 (if (equal r2 "") (setq r2 nil))
2577 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
2578 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
2579 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2580 (if (not r1) (setq r1 thisline))
2581 (if (not r2) (setq r2 thisline))
2582 (if (not c1) (setq c1 col))
2583 (if (not c2) (setq c2 col))
2584 (if (and (not corners-only)
2585 (or (not rangep) (and (= r1 r2) (= c1 c2))))
2586 ;; just one field
2587 (progn
2588 (org-goto-line r1)
2589 (while (not (looking-at org-table-dataline-regexp))
2590 (beginning-of-line 2))
2591 (prog1 (org-trim (org-table-get-field c1))
2592 (if highlight (org-table-highlight-rectangle (point) (point)))))
2593 ;; A range, return a vector
2594 ;; First sort the numbers to get a regular ractangle
2595 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
2596 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
2597 (if corners-only
2598 ;; Only return the corners of the range
2599 (list r1 c1 r2 c2)
2600 ;; Copy the range values into a list
2601 (org-goto-line r1)
2602 (while (not (looking-at org-table-dataline-regexp))
2603 (beginning-of-line 2))
2604 (org-table-goto-column c1)
2605 (setq beg (point))
2606 (org-goto-line r2)
2607 (while (not (looking-at org-table-dataline-regexp))
2608 (beginning-of-line 0))
2609 (org-table-goto-column c2)
2610 (setq end (point))
2611 (if highlight
2612 (org-table-highlight-rectangle
2613 beg (progn (skip-chars-forward "^|\n") (point))))
2614 ;; return string representation of calc vector
2615 (mapcar 'org-trim
2616 (apply 'append (org-table-copy-region beg end))))))))
2618 (defun org-table-get-descriptor-line (desc &optional cline bline table)
2619 "Analyze descriptor DESC and retrieve the corresponding line number.
2620 The cursor is currently in line CLINE, the table begins in line BLINE,
2621 and TABLE is a vector with line types."
2622 (if (string-match "^[0-9]+$" desc)
2623 (aref org-table-dlines (string-to-number desc))
2624 (setq cline (or cline (org-current-line))
2625 bline (or bline org-table-current-begin-line)
2626 table (or table org-table-current-line-types))
2627 (if (or
2628 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
2629 ;; 1 2 3 4 5 6
2630 (and (not (match-end 3)) (not (match-end 6)))
2631 (and (match-end 3) (match-end 6) (not (match-end 5))))
2632 (error "Invalid row descriptor `%s'" desc))
2633 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
2634 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
2635 (odir (and (match-end 5) (match-string 5 desc)))
2636 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
2637 (i (- cline bline))
2638 (rel (and (match-end 6)
2639 (or (and (match-end 1) (not (match-end 3)))
2640 (match-end 5)))))
2641 (if (and hn (not hdir))
2642 (progn
2643 (setq i 0 hdir "+")
2644 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
2645 (if (and (not hn) on (not odir))
2646 (error "Should never happen");;(aref org-table-dlines on)
2647 (if (and hn (> hn 0))
2648 (setq i (org-table-find-row-type table i 'hline (equal hdir "-")
2649 nil hn cline desc)))
2650 (if on
2651 (setq i (org-table-find-row-type table i 'dline (equal odir "-")
2652 rel on cline desc)))
2653 (+ bline i)))))
2655 (defun org-table-find-row-type (table i type backwards relative n cline desc)
2656 "FIXME: Needs more documentation."
2657 (let ((l (length table)))
2658 (while (> n 0)
2659 (while (and (setq i (+ i (if backwards -1 1)))
2660 (>= i 0) (< i l)
2661 (not (eq (aref table i) type))
2662 (if (and relative (eq (aref table i) 'hline))
2663 (cond
2664 ((eq org-table-relative-ref-may-cross-hline t) t)
2665 ((eq org-table-relative-ref-may-cross-hline 'error)
2666 (error "Row descriptor %s used in line %d crosses hline" desc cline))
2667 (t (setq i (- i (if backwards -1 1))
2668 n 1)
2669 nil))
2670 t)))
2671 (setq n (1- n)))
2672 (if (or (< i 0) (>= i l))
2673 (error "Row descriptor %s used in line %d leads outside table"
2674 desc cline)
2675 i)))
2677 (defun org-table-rewrite-old-row-references (s)
2678 (if (string-match "&[-+0-9I]" s)
2679 (error "Formula contains old &row reference, please rewrite using @-syntax")
2682 (defun org-table-make-reference (elements keep-empty numbers lispp)
2683 "Convert list ELEMENTS to something appropriate to insert into formula.
2684 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2685 NUMBERS indicates that everything should be converted to numbers.
2686 LISPP means to return something appropriate for a Lisp list."
2687 (if (stringp elements) ; just a single val
2688 (if lispp
2689 (if (eq lispp 'literal)
2690 elements
2691 (prin1-to-string (if numbers (string-to-number elements) elements)))
2692 (if (equal elements "") (setq elements "0"))
2693 (if numbers (setq elements (number-to-string (string-to-number elements))))
2694 (concat "(" elements ")"))
2695 (unless keep-empty
2696 (setq elements
2697 (delq nil
2698 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
2699 elements))))
2700 (setq elements (or elements '("0")))
2701 (if lispp
2702 (mapconcat
2703 (lambda (x)
2704 (if (eq lispp 'literal)
2706 (prin1-to-string (if numbers (string-to-number x) x))))
2707 elements " ")
2708 (concat "[" (mapconcat
2709 (lambda (x)
2710 (if numbers (number-to-string (string-to-number x)) x))
2711 elements
2712 ",") "]"))))
2714 (defun org-table-recalculate (&optional all noalign)
2715 "Recalculate the current table line by applying all stored formulas.
2716 With prefix arg ALL, do this for all lines in the table.
2717 With the prefix argument ALL is `(16)' \
2718 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2719 it is the symbol `iterate', recompute the table until it no longer changes.
2720 If NOALIGN is not nil, do not re-align the table after the computations
2721 are done. This is typically used internally to save time, if it is
2722 known that the table will be realigned a little later anyway."
2723 (interactive "P")
2724 (or (memq this-command org-recalc-commands)
2725 (setq org-recalc-commands (cons this-command org-recalc-commands)))
2726 (unless (org-at-table-p) (error "Not at a table"))
2727 (if (or (eq all 'iterate) (equal all '(16)))
2728 (org-table-iterate)
2729 (org-table-get-specials)
2730 (let* ((eqlist (sort (org-table-get-stored-formulas)
2731 (lambda (a b) (string< (car a) (car b)))))
2732 (eqlist1 (copy-sequence eqlist))
2733 (inhibit-redisplay (not debug-on-error))
2734 (line-re org-table-dataline-regexp)
2735 (thisline (org-current-line))
2736 (thiscol (org-table-current-column))
2737 seen-fields lhs1
2738 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name name1)
2739 ;; Insert constants in all formulas
2740 (setq eqlist
2741 (mapcar (lambda (x)
2742 (when (string-match "\\`$[<>]" (car x))
2743 (setq lhs1 (car x))
2744 (setq x (cons (substring
2745 (org-table-formula-handle-first/last-rc
2746 (car x)) 1)
2747 (cdr x)))
2748 (if (assoc (car x) eqlist1)
2749 (error "\"%s=\" formula tries to overwrite existing formula for column %s"
2750 lhs1 (car x))))
2751 (cons
2752 (org-table-formula-handle-first/last-rc (car x))
2753 (org-table-formula-substitute-names
2754 (org-table-formula-handle-first/last-rc (cdr x)))))
2755 eqlist))
2756 ;; Split the equation list
2757 (while (setq eq (pop eqlist))
2758 (if (<= (string-to-char (car eq)) ?9)
2759 (push eq eqlnum)
2760 (push eq eqlname)))
2761 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
2762 ;; Expand ranges in lhs of formulas
2763 (setq eqlname (org-table-expand-lhs-ranges eqlname))
2765 ;; Get the correct line range to process
2766 (if all
2767 (progn
2768 (setq end (move-marker (make-marker) (1+ (org-table-end))))
2769 (goto-char (setq beg (org-table-begin)))
2770 (if (re-search-forward org-table-calculate-mark-regexp end t)
2771 ;; This is a table with marked lines, compute selected lines
2772 (setq line-re org-table-recalculate-regexp)
2773 ;; Move forward to the first non-header line
2774 (if (and (re-search-forward org-table-dataline-regexp end t)
2775 (re-search-forward org-table-hline-regexp end t)
2776 (re-search-forward org-table-dataline-regexp end t))
2777 (setq beg (match-beginning 0))
2778 nil))) ;; just leave beg where it is
2779 (setq beg (point-at-bol)
2780 end (move-marker (make-marker) (1+ (point-at-eol)))))
2781 (goto-char beg)
2782 (and all (message "Re-applying formulas to full table..."))
2784 ;; First find the named fields, and mark them untouchable.
2785 ;; Also check if several field/range formulas try to set the same field.
2786 (remove-text-properties beg end '(org-untouchable t))
2787 (while (setq eq (pop eqlname))
2788 (setq name (car eq)
2789 a (assoc name org-table-named-field-locations))
2790 (setq name1 name)
2791 (if a (setq name1 (format "@%d$%d" (org-table-line-to-dline (nth 1 a))
2792 (nth 2 a))))
2793 (when (member name1 seen-fields)
2794 (error "Several field/range formulas try to set %s" name1))
2795 (push name1 seen-fields)
2797 (and (not a)
2798 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
2799 (setq a (list name
2800 (condition-case nil
2801 (aref org-table-dlines
2802 (string-to-number (match-string 1 name)))
2803 (error (error "Invalid row number in %s"
2804 name)))
2805 (string-to-number (match-string 2 name)))))
2806 (when (and a (or all (equal (nth 1 a) thisline)))
2807 (message "Re-applying formula to field: %s" name)
2808 (org-goto-line (nth 1 a))
2809 (org-table-goto-column (nth 2 a))
2810 (push (append a (list (cdr eq))) eqlname1)
2811 (org-table-put-field-property :org-untouchable t)))
2812 (setq eqlname1 (nreverse eqlname1))
2814 ;; Now evaluate the column formulas, but skip fields covered by
2815 ;; field formulas
2816 (goto-char beg)
2817 (while (re-search-forward line-re end t)
2818 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2819 ;; Unprotected line, recalculate
2820 (and all (message "Re-applying formulas to full table...(line %d)"
2821 (setq cnt (1+ cnt))))
2822 (setq org-last-recalc-line (org-current-line))
2823 (setq eql eqlnum)
2824 (while (setq entry (pop eql))
2825 (org-goto-line org-last-recalc-line)
2826 (org-table-goto-column (string-to-number (car entry)) nil 'force)
2827 (unless (get-text-property (point) :org-untouchable)
2828 (org-table-eval-formula nil (cdr entry)
2829 'noalign 'nocst 'nostore 'noanalysis)))))
2831 ;; Now evaluate the field formulas
2832 (while (setq eq (pop eqlname1))
2833 (message "Re-applying formula to field: %s" (car eq))
2834 (org-goto-line (nth 1 eq))
2835 (org-table-goto-column (nth 2 eq))
2836 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
2837 'nostore 'noanalysis))
2839 (org-goto-line thisline)
2840 (org-table-goto-column thiscol)
2841 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
2842 (or noalign (and org-table-may-need-update (org-table-align))
2843 (and all (message "Re-applying formulas to %d lines...done" cnt)))
2845 ;; back to initial position
2846 (message "Re-applying formulas...done")
2847 (org-goto-line thisline)
2848 (org-table-goto-column thiscol)
2849 (or noalign (and org-table-may-need-update (org-table-align))
2850 (and all (message "Re-applying formulas...done"))))))
2852 (defun org-table-iterate (&optional arg)
2853 "Recalculate the table until it does not change anymore.
2854 The maximun number of iterations is 10, but you can chose a different value
2855 with the prefix ARG."
2856 (interactive "P")
2857 (let ((imax (if arg (prefix-numeric-value arg) 10))
2858 (i 0)
2859 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2860 thistbl)
2861 (catch 'exit
2862 (while (< i imax)
2863 (setq i (1+ i))
2864 (org-table-recalculate 'all)
2865 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
2866 (if (not (string= lasttbl thistbl))
2867 (setq lasttbl thistbl)
2868 (if (> i 1)
2869 (message "Convergence after %d iterations" i)
2870 (message "Table was already stable"))
2871 (throw 'exit t)))
2872 (error "No convergence after %d iterations" i))))
2874 (defun org-table-recalculate-buffer-tables ()
2875 "Recalculate all tables in the current buffer."
2876 (interactive)
2877 (save-excursion
2878 (save-restriction
2879 (widen)
2880 (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
2882 (defun org-table-iterate-buffer-tables ()
2883 "Iterate all tables in the buffer, to converge inter-table dependencies."
2884 (interactive)
2885 (let* ((imax 10)
2886 (checksum (md5 (buffer-string)))
2889 (i imax))
2890 (save-excursion
2891 (save-restriction
2892 (widen)
2893 (catch 'exit
2894 (while (> i 0)
2895 (setq i (1- i))
2896 (org-table-map-tables (lambda () (org-table-recalculate t)) t)
2897 (if (equal checksum (setq c1 (md5 (buffer-string))))
2898 (progn
2899 (message "Convergence after %d iterations" (- imax i))
2900 (throw 'exit t))
2901 (setq checksum c1)))
2902 (error "No convergence after %d iterations" imax))))))
2904 (defun org-table-expand-lhs-ranges (equations)
2905 "Expand list of formulas.
2906 If some of the RHS in the formulas are ranges or a row reference, expand
2907 them to individual field equations for each field."
2908 (let (e res lhs rhs range r1 r2 c1 c2)
2909 (while (setq e (pop equations))
2910 (setq lhs (car e) rhs (cdr e))
2911 (cond
2912 ((string-match "^@-?[-+I0-9]+\\$-?[0-9]+$" lhs)
2913 ;; This just refers to one fixed field
2914 (push e res))
2915 ((string-match "^[a-zA-Z][a-zA-Z0-9]*$" lhs)
2916 ;; This just refers to one fixed named field
2917 (push e res))
2918 ((string-match "^@[0-9]+$" lhs)
2919 (loop for ic from 1 to org-table-current-ncol do
2920 (push (cons (format "%s$%d" lhs ic) rhs) res)
2921 (put-text-property 0 (length (caar res))
2922 :orig-eqn e (caar res))))
2924 (setq range (org-table-get-range lhs org-table-current-begin-pos
2925 1 nil 'corners))
2926 (setq r1 (nth 0 range) c1 (nth 1 range)
2927 r2 (nth 2 range) c2 (nth 3 range))
2928 (setq r1 (org-table-line-to-dline r1))
2929 (setq r2 (org-table-line-to-dline r2 'above))
2930 (loop for ir from r1 to r2 do
2931 (loop for ic from c1 to c2 do
2932 (push (cons (format "@%d$%d" ir ic) rhs) res)
2933 (put-text-property 0 (length (caar res))
2934 :orig-eqn e (caar res)))))))
2935 (nreverse res)))
2937 (defun org-table-formula-handle-first/last-rc (s)
2938 "Replace @<, @>, $<, $> with first/last row/column of the table.
2939 So @< and $< will always be replaced with @1 and $1, respectively.
2940 The advantage of these special markers are that structure editing of
2941 the table will not change them, while @1 and $1 will be modified
2942 when a line/row is swaped out of that privileged position. So for
2943 formulas that use a range of rows or columns, it may often be better
2944 to anchor the formula with \"I\" row markers, or to offset from the
2945 borders of the table using the @< @> $< $> makers."
2946 (let (n nmax len char)
2947 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)" s)
2948 (setq nmax (if (equal (match-string 1 s) "@")
2949 (1- (length org-table-dlines))
2950 org-table-current-ncol)
2951 len (- (match-end 2) (match-beginning 2))
2952 char (string-to-char (match-string 2 s))
2953 n (if (= char ?<)
2955 (- nmax len -1)))
2956 (if (or (< n 1) (> n nmax))
2957 (error "Reference \"%s\" in expression \"%s\" points outside table"
2958 (match-string 0 s) s))
2959 (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s))))
2962 (defun org-table-formula-substitute-names (f)
2963 "Replace $const with values in string F."
2964 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
2965 ;; First, check for column names
2966 (while (setq start (string-match org-table-column-name-regexp f start))
2967 (setq start (1+ start))
2968 (setq a (assoc (match-string 1 f) org-table-column-names))
2969 (setq f (replace-match (concat "$" (cdr a)) t t f)))
2970 ;; Parameters and constants
2971 (setq start 0)
2972 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start))
2973 (if (match-end 2)
2974 (setq start (match-end 2))
2975 (setq start (1+ start))
2976 (if (setq a (save-match-data
2977 (org-table-get-constant (match-string 1 f))))
2978 (setq f (replace-match
2979 (concat (if pp "(") a (if pp ")")) t t f)))))
2980 (if org-table-formula-debug
2981 (put-text-property 0 (length f) :orig-formula f1 f))
2984 (defun org-table-get-constant (const)
2985 "Find the value for a parameter or constant in a formula.
2986 Parameters get priority."
2987 (or (cdr (assoc const org-table-local-parameters))
2988 (cdr (assoc const org-table-formula-constants-local))
2989 (cdr (assoc const org-table-formula-constants))
2990 (and (fboundp 'constants-get) (constants-get const))
2991 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
2992 (org-entry-get nil (substring const 5) 'inherit))
2993 "#UNDEFINED_NAME"))
2995 (defvar org-table-fedit-map
2996 (let ((map (make-sparse-keymap)))
2997 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
2998 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
2999 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
3000 (org-defkey map "\C-c'" 'org-table-fedit-finish)
3001 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
3002 (org-defkey map "\C-c?" 'org-table-show-reference)
3003 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
3004 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
3005 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
3006 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
3007 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
3008 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
3009 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
3010 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
3011 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
3012 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
3013 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
3014 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
3015 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
3016 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
3017 map))
3019 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
3020 '("Edit-Formulas"
3021 ["Finish and Install" org-table-fedit-finish t]
3022 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
3023 ["Abort" org-table-fedit-abort t]
3024 "--"
3025 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
3026 ["Complete Lisp Symbol" lisp-complete-symbol t]
3027 "--"
3028 "Shift Reference at Point"
3029 ["Up" org-table-fedit-ref-up t]
3030 ["Down" org-table-fedit-ref-down t]
3031 ["Left" org-table-fedit-ref-left t]
3032 ["Right" org-table-fedit-ref-right t]
3034 "Change Test Row for Column Formulas"
3035 ["Up" org-table-fedit-line-up t]
3036 ["Down" org-table-fedit-line-down t]
3037 "--"
3038 ["Scroll Table Window" org-table-fedit-scroll t]
3039 ["Scroll Table Window down" org-table-fedit-scroll-down t]
3040 ["Show Table Grid" org-table-fedit-toggle-coordinates
3041 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
3042 org-table-overlay-coordinates)]
3043 "--"
3044 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3045 :style toggle :selected org-table-buffer-is-an]))
3047 (defvar org-pos)
3049 (defun org-table-edit-formulas ()
3050 "Edit the formulas of the current table in a separate buffer."
3051 (interactive)
3052 (when (save-excursion (beginning-of-line 1) (looking-at "[ \t]*#\\+TBLFM"))
3053 (beginning-of-line 0))
3054 (unless (org-at-table-p) (error "Not at a table"))
3055 (org-table-get-specials)
3056 (let ((key (org-table-current-field-formula 'key 'noerror))
3057 (eql (sort (org-table-get-stored-formulas 'noerror)
3058 'org-table-formula-less-p))
3059 (pos (move-marker (make-marker) (point)))
3060 (startline 1)
3061 (wc (current-window-configuration))
3062 (sel-win (selected-window))
3063 (titles '((column . "# Column Formulas\n")
3064 (field . "# Field and Range Formulas\n")
3065 (named . "# Named Field Formulas\n")))
3066 entry s type title)
3067 (org-switch-to-buffer-other-window "*Edit Formulas*")
3068 (erase-buffer)
3069 ;; Keep global-font-lock-mode from turning on font-lock-mode
3070 (let ((font-lock-global-modes '(not fundamental-mode)))
3071 (fundamental-mode))
3072 (org-set-local 'font-lock-global-modes (list 'not major-mode))
3073 (org-set-local 'org-pos pos)
3074 (org-set-local 'org-window-configuration wc)
3075 (org-set-local 'org-selected-window sel-win)
3076 (use-local-map org-table-fedit-map)
3077 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
3078 (easy-menu-add org-table-fedit-menu)
3079 (setq startline (org-current-line))
3080 (while (setq entry (pop eql))
3081 (setq type (cond
3082 ((string-match "\\`$[<>]" (car entry)) 'column)
3083 ((equal (string-to-char (car entry)) ?@) 'field)
3084 ((string-match "^[0-9]" (car entry)) 'column)
3085 (t 'named)))
3086 (when (setq title (assq type titles))
3087 (or (bobp) (insert "\n"))
3088 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
3089 (setq titles (remove title titles)))
3090 (if (equal key (car entry)) (setq startline (org-current-line)))
3091 (setq s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
3092 (car entry) " = " (cdr entry) "\n"))
3093 (remove-text-properties 0 (length s) '(face nil) s)
3094 (insert s))
3095 (if (eq org-table-use-standard-references t)
3096 (org-table-fedit-toggle-ref-type))
3097 (org-goto-line startline)
3098 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3100 (defun org-table-fedit-post-command ()
3101 (when (not (memq this-command '(lisp-complete-symbol)))
3102 (let ((win (selected-window)))
3103 (save-excursion
3104 (condition-case nil
3105 (org-table-show-reference)
3106 (error nil))
3107 (select-window win)))))
3109 (defun org-table-formula-to-user (s)
3110 "Convert a formula from internal to user representation."
3111 (if (eq org-table-use-standard-references t)
3112 (org-table-convert-refs-to-an s)
3115 (defun org-table-formula-from-user (s)
3116 "Convert a formula from user to internal representation."
3117 (if org-table-use-standard-references
3118 (org-table-convert-refs-to-rc s)
3121 (defun org-table-convert-refs-to-rc (s)
3122 "Convert spreadsheet references from A7 to @7$28.
3123 Works for single references, but also for entire formulas and even the
3124 full TBLFM line."
3125 (let ((start 0))
3126 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^)]*)\\)" s start)
3127 (cond
3128 ((match-end 3)
3129 ;; format match, just advance
3130 (setq start (match-end 0)))
3131 ((and (> (match-beginning 0) 0)
3132 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3133 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3134 ;; 3.e5 or something like this.
3135 (setq start (match-end 0)))
3136 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3137 ;; (member (match-string 1 s)
3138 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3140 ;; function name, just advance
3141 (setq start (match-end 0)))
3143 (setq start (match-beginning 0)
3144 s (replace-match
3145 (if (equal (match-string 2 s) "&")
3146 (format "$%d" (org-letters-to-number (match-string 1 s)))
3147 (format "@%d$%d"
3148 (string-to-number (match-string 2 s))
3149 (org-letters-to-number (match-string 1 s))))
3150 t t s)))))
3153 (defun org-table-convert-refs-to-an (s)
3154 "Convert spreadsheet references from to @7$28 to AB7.
3155 Works for single references, but also for entire formulas and even the
3156 full TBLFM line."
3157 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3158 (setq s (replace-match
3159 (format "%s%d"
3160 (org-number-to-letters
3161 (string-to-number (match-string 2 s)))
3162 (string-to-number (match-string 1 s)))
3163 t t s)))
3164 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3165 (setq s (replace-match (concat "\\1"
3166 (org-number-to-letters
3167 (string-to-number (match-string 2 s))) "&")
3168 t nil s)))
3171 (defun org-letters-to-number (s)
3172 "Convert a base 26 number represented by letters into an integer.
3173 For example: AB -> 28."
3174 (let ((n 0))
3175 (setq s (upcase s))
3176 (while (> (length s) 0)
3177 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3178 s (substring s 1)))
3181 (defun org-number-to-letters (n)
3182 "Convert an integer into a base 26 number represented by letters.
3183 For example: 28 -> AB."
3184 (let ((s ""))
3185 (while (> n 0)
3186 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3187 n (/ (1- n) 26)))
3190 (defun org-table-fedit-convert-buffer (function)
3191 "Convert all references in this buffer, using FUNCTION."
3192 (let ((line (org-current-line)))
3193 (goto-char (point-min))
3194 (while (not (eobp))
3195 (insert (funcall function (buffer-substring (point) (point-at-eol))))
3196 (delete-region (point) (point-at-eol))
3197 (or (eobp) (forward-char 1)))
3198 (org-goto-line line)))
3200 (defun org-table-fedit-toggle-ref-type ()
3201 "Convert all references in the buffer from B3 to @3$2 and back."
3202 (interactive)
3203 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
3204 (org-table-fedit-convert-buffer
3205 (if org-table-buffer-is-an
3206 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3207 (message "Reference type switched to %s"
3208 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3210 (defun org-table-fedit-ref-up ()
3211 "Shift the reference at point one row/hline up."
3212 (interactive)
3213 (org-table-fedit-shift-reference 'up))
3214 (defun org-table-fedit-ref-down ()
3215 "Shift the reference at point one row/hline down."
3216 (interactive)
3217 (org-table-fedit-shift-reference 'down))
3218 (defun org-table-fedit-ref-left ()
3219 "Shift the reference at point one field to the left."
3220 (interactive)
3221 (org-table-fedit-shift-reference 'left))
3222 (defun org-table-fedit-ref-right ()
3223 "Shift the reference at point one field to the right."
3224 (interactive)
3225 (org-table-fedit-shift-reference 'right))
3227 (defun org-table-fedit-shift-reference (dir)
3228 (cond
3229 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3230 (if (memq dir '(left right))
3231 (org-rematch-and-replace 1 (eq dir 'left))
3232 (error "Cannot shift reference in this direction")))
3233 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3234 ;; A B3-like reference
3235 (if (memq dir '(up down))
3236 (org-rematch-and-replace 2 (eq dir 'up))
3237 (org-rematch-and-replace 1 (eq dir 'left))))
3238 ((org-at-regexp-p
3239 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3240 ;; An internal reference
3241 (if (memq dir '(up down))
3242 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3243 (org-rematch-and-replace 5 (eq dir 'left))))))
3245 (defun org-rematch-and-replace (n &optional decr hline)
3246 "Re-match the group N, and replace it with the shifted reference."
3247 (or (match-end n) (error "Cannot shift reference in this direction"))
3248 (goto-char (match-beginning n))
3249 (and (looking-at (regexp-quote (match-string n)))
3250 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3251 t t)))
3253 (defun org-table-shift-refpart (ref &optional decr hline)
3254 "Shift a reference part REF.
3255 If DECR is set, decrease the references row/column, else increase.
3256 If HLINE is set, this may be a hline reference, it certainly is not
3257 a translation reference."
3258 (save-match-data
3259 (let* ((sign (string-match "^[-+]" ref)) n)
3261 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3262 (cond
3263 ((and hline (string-match "^I+" ref))
3264 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3265 (setq n (+ n (if decr -1 1)))
3266 (if (= n 0) (setq n (+ n (if decr -1 1))))
3267 (if sign
3268 (setq sign (if (< n 0) "-" "+") n (abs n))
3269 (setq n (max 1 n)))
3270 (concat sign (make-string n ?I)))
3272 ((string-match "^[0-9]+" ref)
3273 (setq n (string-to-number (concat sign ref)))
3274 (setq n (+ n (if decr -1 1)))
3275 (if sign
3276 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3277 (number-to-string (max 1 n))))
3279 ((string-match "^[a-zA-Z]+" ref)
3280 (org-number-to-letters
3281 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3283 (t (error "Cannot shift reference"))))))
3285 (defun org-table-fedit-toggle-coordinates ()
3286 "Toggle the display of coordinates in the referenced table."
3287 (interactive)
3288 (let ((pos (marker-position org-pos)))
3289 (with-current-buffer (marker-buffer org-pos)
3290 (save-excursion
3291 (goto-char pos)
3292 (org-table-toggle-coordinate-overlays)))))
3294 (defun org-table-fedit-finish (&optional arg)
3295 "Parse the buffer for formula definitions and install them.
3296 With prefix ARG, apply the new formulas to the table."
3297 (interactive "P")
3298 (org-table-remove-rectangle-highlight)
3299 (if org-table-use-standard-references
3300 (progn
3301 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3302 (setq org-table-buffer-is-an nil)))
3303 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3304 (goto-char (point-min))
3305 (while (re-search-forward
3306 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3307 nil t)
3308 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3309 form (match-string 3))
3310 (setq form (org-trim form))
3311 (when (not (equal form ""))
3312 (while (string-match "[ \t]*\n[ \t]*" form)
3313 (setq form (replace-match " " t t form)))
3314 (when (assoc var eql)
3315 (error "Double formulas for %s" var))
3316 (push (cons var form) eql)))
3317 (setq org-pos nil)
3318 (set-window-configuration org-window-configuration)
3319 (select-window sel-win)
3320 (goto-char pos)
3321 (unless (org-at-table-p)
3322 (error "Lost table position - cannot install formulas"))
3323 (org-table-store-formulas eql)
3324 (move-marker pos nil)
3325 (kill-buffer "*Edit Formulas*")
3326 (if arg
3327 (org-table-recalculate 'all)
3328 (message "New formulas installed - press C-u C-c C-c to apply."))))
3330 (defun org-table-fedit-abort ()
3331 "Abort editing formulas, without installing the changes."
3332 (interactive)
3333 (org-table-remove-rectangle-highlight)
3334 (let ((pos org-pos) (sel-win org-selected-window))
3335 (set-window-configuration org-window-configuration)
3336 (select-window sel-win)
3337 (goto-char pos)
3338 (move-marker pos nil)
3339 (message "Formula editing aborted without installing changes")))
3341 (defun org-table-fedit-lisp-indent ()
3342 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3343 (interactive)
3344 (let ((pos (point)) beg end ind)
3345 (beginning-of-line 1)
3346 (cond
3347 ((looking-at "[ \t]")
3348 (goto-char pos)
3349 (call-interactively 'lisp-indent-line))
3350 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3351 ((not (fboundp 'pp-buffer))
3352 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3353 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3354 (goto-char (- (match-end 0) 2))
3355 (setq beg (point))
3356 (setq ind (make-string (current-column) ?\ ))
3357 (condition-case nil (forward-sexp 1)
3358 (error
3359 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3360 (setq end (point))
3361 (save-restriction
3362 (narrow-to-region beg end)
3363 (if (eq last-command this-command)
3364 (progn
3365 (goto-char (point-min))
3366 (setq this-command nil)
3367 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3368 (replace-match " ")))
3369 (pp-buffer)
3370 (untabify (point-min) (point-max))
3371 (goto-char (1+ (point-min)))
3372 (while (re-search-forward "^." nil t)
3373 (beginning-of-line 1)
3374 (insert ind))
3375 (goto-char (point-max))
3376 (backward-delete-char 1)))
3377 (goto-char beg))
3378 (t nil))))
3380 (defvar org-show-positions nil)
3382 (defun org-table-show-reference (&optional local)
3383 "Show the location/value of the $ expression at point."
3384 (interactive)
3385 (org-table-remove-rectangle-highlight)
3386 (catch 'exit
3387 (let ((pos (if local (point) org-pos))
3388 (face2 'highlight)
3389 (org-inhibit-highlight-removal t)
3390 (win (selected-window))
3391 (org-show-positions nil)
3392 var name e what match dest)
3393 (if local (org-table-get-specials))
3394 (setq what (cond
3395 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3396 (setq match (concat (substring (match-string 0) 0 -1)
3397 "$1.."
3398 (substring (match-string 0) 0 -1)
3399 "$100"))
3400 'range)
3401 ((or (org-at-regexp-p org-table-range-regexp2)
3402 (org-at-regexp-p org-table-translate-regexp)
3403 (org-at-regexp-p org-table-range-regexp))
3404 (setq match
3405 (save-match-data
3406 (org-table-convert-refs-to-rc (match-string 0))))
3407 'range)
3408 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3409 ((org-at-regexp-p "\\$[0-9]+") 'column)
3410 ((not local) nil)
3411 (t (error "No reference at point")))
3412 match (and what (or match (match-string 0))))
3413 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3414 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3415 'secondary-selection))
3416 (org-add-hook 'before-change-functions
3417 'org-table-remove-rectangle-highlight)
3418 (if (eq what 'name) (setq var (substring match 1)))
3419 (when (eq what 'range)
3420 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
3421 (setq match (org-table-formula-substitute-names match)))
3422 (unless local
3423 (save-excursion
3424 (end-of-line 1)
3425 (re-search-backward "^\\S-" nil t)
3426 (beginning-of-line 1)
3427 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3428 (setq dest
3429 (save-match-data
3430 (org-table-convert-refs-to-rc (match-string 1))))
3431 (org-table-add-rectangle-overlay
3432 (match-beginning 1) (match-end 1) face2))))
3433 (if (and (markerp pos) (marker-buffer pos))
3434 (if (get-buffer-window (marker-buffer pos))
3435 (select-window (get-buffer-window (marker-buffer pos)))
3436 (org-switch-to-buffer-other-window (get-buffer-window
3437 (marker-buffer pos)))))
3438 (goto-char pos)
3439 (org-table-force-dataline)
3440 (when dest
3441 (setq name (substring dest 1))
3442 (cond
3443 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3444 (setq e (assoc name org-table-named-field-locations))
3445 (org-goto-line (nth 1 e))
3446 (org-table-goto-column (nth 2 e)))
3447 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
3448 (let ((l (string-to-number (match-string 1 dest)))
3449 (c (string-to-number (match-string 2 dest))))
3450 (org-goto-line (aref org-table-dlines l))
3451 (org-table-goto-column c)))
3452 (t (org-table-goto-column (string-to-number name))))
3453 (move-marker pos (point))
3454 (org-table-highlight-rectangle nil nil face2))
3455 (cond
3456 ((equal dest match))
3457 ((not match))
3458 ((eq what 'range)
3459 (condition-case nil
3460 (save-excursion
3461 (org-table-get-range match nil nil 'highlight))
3462 (error nil)))
3463 ((setq e (assoc var org-table-named-field-locations))
3464 (org-goto-line (nth 1 e))
3465 (org-table-goto-column (nth 2 e))
3466 (org-table-highlight-rectangle (point) (point))
3467 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3468 ((setq e (assoc var org-table-column-names))
3469 (org-table-goto-column (string-to-number (cdr e)))
3470 (org-table-highlight-rectangle (point) (point))
3471 (goto-char (org-table-begin))
3472 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3473 (org-table-end) t)
3474 (progn
3475 (goto-char (match-beginning 1))
3476 (org-table-highlight-rectangle)
3477 (message "Named column (column %s)" (cdr e)))
3478 (error "Column name not found")))
3479 ((eq what 'column)
3480 ;; column number
3481 (org-table-goto-column (string-to-number (substring match 1)))
3482 (org-table-highlight-rectangle (point) (point))
3483 (message "Column %s" (substring match 1)))
3484 ((setq e (assoc var org-table-local-parameters))
3485 (goto-char (org-table-begin))
3486 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3487 (progn
3488 (goto-char (match-beginning 1))
3489 (org-table-highlight-rectangle)
3490 (message "Local parameter."))
3491 (error "Parameter not found")))
3493 (cond
3494 ((not var) (error "No reference at point"))
3495 ((setq e (assoc var org-table-formula-constants-local))
3496 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3497 var (cdr e)))
3498 ((setq e (assoc var org-table-formula-constants))
3499 (message "Constant: $%s=%s in `org-table-formula-constants'."
3500 var (cdr e)))
3501 ((setq e (and (fboundp 'constants-get) (constants-get var)))
3502 (message "Constant: $%s=%s, from `constants.el'%s."
3503 var e (format " (%s units)" constants-unit-system)))
3504 (t (error "Undefined name $%s" var)))))
3505 (goto-char pos)
3506 (when (and org-show-positions
3507 (not (memq this-command '(org-table-fedit-scroll
3508 org-table-fedit-scroll-down))))
3509 (push pos org-show-positions)
3510 (push org-table-current-begin-pos org-show-positions)
3511 (let ((min (apply 'min org-show-positions))
3512 (max (apply 'max org-show-positions)))
3513 (goto-char min) (recenter 0)
3514 (goto-char max)
3515 (or (pos-visible-in-window-p max) (recenter -1))))
3516 (select-window win))))
3518 (defun org-table-force-dataline ()
3519 "Make sure the cursor is in a dataline in a table."
3520 (unless (save-excursion
3521 (beginning-of-line 1)
3522 (looking-at org-table-dataline-regexp))
3523 (let* ((re org-table-dataline-regexp)
3524 (p1 (save-excursion (re-search-forward re nil 'move)))
3525 (p2 (save-excursion (re-search-backward re nil 'move))))
3526 (cond ((and p1 p2)
3527 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
3528 p1 p2)))
3529 ((or p1 p2) (goto-char (or p1 p2)))
3530 (t (error "No table dataline around here"))))))
3532 (defun org-table-fedit-line-up ()
3533 "Move cursor one line up in the window showing the table."
3534 (interactive)
3535 (org-table-fedit-move 'previous-line))
3537 (defun org-table-fedit-line-down ()
3538 "Move cursor one line down in the window showing the table."
3539 (interactive)
3540 (org-table-fedit-move 'next-line))
3542 (defun org-table-fedit-move (command)
3543 "Move the cursor in the window showing the table.
3544 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3545 (let ((org-table-allow-automatic-line-recalculation nil)
3546 (pos org-pos) (win (selected-window)) p)
3547 (select-window (get-buffer-window (marker-buffer org-pos)))
3548 (setq p (point))
3549 (call-interactively command)
3550 (while (and (org-at-table-p)
3551 (org-at-table-hline-p))
3552 (call-interactively command))
3553 (or (org-at-table-p) (goto-char p))
3554 (move-marker pos (point))
3555 (select-window win)))
3557 (defun org-table-fedit-scroll (N)
3558 (interactive "p")
3559 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
3560 (scroll-other-window N)))
3562 (defun org-table-fedit-scroll-down (N)
3563 (interactive "p")
3564 (org-table-fedit-scroll (- N)))
3566 (defvar org-table-rectangle-overlays nil)
3568 (defun org-table-add-rectangle-overlay (beg end &optional face)
3569 "Add a new overlay."
3570 (let ((ov (make-overlay beg end)))
3571 (overlay-put ov 'face (or face 'secondary-selection))
3572 (push ov org-table-rectangle-overlays)))
3574 (defun org-table-highlight-rectangle (&optional beg end face)
3575 "Highlight rectangular region in a table."
3576 (setq beg (or beg (point)) end (or end (point)))
3577 (let ((b (min beg end))
3578 (e (max beg end))
3579 l1 c1 l2 c2 tmp)
3580 (and (boundp 'org-show-positions)
3581 (setq org-show-positions (cons b (cons e org-show-positions))))
3582 (goto-char (min beg end))
3583 (setq l1 (org-current-line)
3584 c1 (org-table-current-column))
3585 (goto-char (max beg end))
3586 (setq l2 (org-current-line)
3587 c2 (org-table-current-column))
3588 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
3589 (org-goto-line l1)
3590 (beginning-of-line 1)
3591 (loop for line from l1 to l2 do
3592 (when (looking-at org-table-dataline-regexp)
3593 (org-table-goto-column c1)
3594 (skip-chars-backward "^|\n") (setq beg (point))
3595 (org-table-goto-column c2)
3596 (skip-chars-forward "^|\n") (setq end (point))
3597 (org-table-add-rectangle-overlay beg end face))
3598 (beginning-of-line 2))
3599 (goto-char b))
3600 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
3602 (defun org-table-remove-rectangle-highlight (&rest ignore)
3603 "Remove the rectangle overlays."
3604 (unless org-inhibit-highlight-removal
3605 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
3606 (mapc 'delete-overlay org-table-rectangle-overlays)
3607 (setq org-table-rectangle-overlays nil)))
3609 (defvar org-table-coordinate-overlays nil
3610 "Collects the coordinate grid overlays, so that they can be removed.")
3611 (make-variable-buffer-local 'org-table-coordinate-overlays)
3613 (defun org-table-overlay-coordinates ()
3614 "Add overlays to the table at point, to show row/column coordinates."
3615 (interactive)
3616 (mapc 'delete-overlay org-table-coordinate-overlays)
3617 (setq org-table-coordinate-overlays nil)
3618 (save-excursion
3619 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
3620 (goto-char (org-table-begin))
3621 (while (org-at-table-p)
3622 (setq eol (point-at-eol))
3623 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
3624 (push ov org-table-coordinate-overlays)
3625 (setq hline (looking-at org-table-hline-regexp))
3626 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
3627 (format "%4d" (setq id (1+ id)))))
3628 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
3629 (when hline
3630 (setq ic 0)
3631 (while (re-search-forward "[+|]\\(-+\\)" eol t)
3632 (setq beg (1+ (match-beginning 0))
3633 ic (1+ ic)
3634 s1 (concat "$" (int-to-string ic))
3635 s2 (org-number-to-letters ic)
3636 str (if (eq org-table-use-standard-references t) s2 s1))
3637 (setq ov (make-overlay beg (+ beg (length str))))
3638 (push ov org-table-coordinate-overlays)
3639 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
3640 (beginning-of-line 2)))))
3642 (defun org-table-toggle-coordinate-overlays ()
3643 "Toggle the display of Row/Column numbers in tables."
3644 (interactive)
3645 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
3646 (message "Row/Column number display turned %s"
3647 (if org-table-overlay-coordinates "on" "off"))
3648 (if (and (org-at-table-p) org-table-overlay-coordinates)
3649 (org-table-align))
3650 (unless org-table-overlay-coordinates
3651 (mapc 'delete-overlay org-table-coordinate-overlays)
3652 (setq org-table-coordinate-overlays nil)))
3654 (defun org-table-toggle-formula-debugger ()
3655 "Toggle the formula debugger in tables."
3656 (interactive)
3657 (setq org-table-formula-debug (not org-table-formula-debug))
3658 (message "Formula debugging has been turned %s"
3659 (if org-table-formula-debug "on" "off")))
3661 ;;; The orgtbl minor mode
3663 ;; Define a minor mode which can be used in other modes in order to
3664 ;; integrate the org-mode table editor.
3666 ;; This is really a hack, because the org-mode table editor uses several
3667 ;; keys which normally belong to the major mode, for example the TAB and
3668 ;; RET keys. Here is how it works: The minor mode defines all the keys
3669 ;; necessary to operate the table editor, but wraps the commands into a
3670 ;; function which tests if the cursor is currently inside a table. If that
3671 ;; is the case, the table editor command is executed. However, when any of
3672 ;; those keys is used outside a table, the function uses `key-binding' to
3673 ;; look up if the key has an associated command in another currently active
3674 ;; keymap (minor modes, major mode, global), and executes that command.
3675 ;; There might be problems if any of the keys used by the table editor is
3676 ;; otherwise used as a prefix key.
3678 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3679 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3680 ;; addresses this by checking explicitly for both bindings.
3682 ;; The optimized version (see variable `orgtbl-optimized') takes over
3683 ;; all keys which are bound to `self-insert-command' in the *global map*.
3684 ;; Some modes bind other commands to simple characters, for example
3685 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3686 ;; active, this binding is ignored inside tables and replaced with a
3687 ;; modified self-insert.
3690 (defvar orgtbl-mode-map (make-keymap)
3691 "Keymap for `orgtbl-mode'.")
3693 ;;;###autoload
3694 (defun turn-on-orgtbl ()
3695 "Unconditionally turn on `orgtbl-mode'."
3696 (orgtbl-mode 1))
3698 (defvar org-old-auto-fill-inhibit-regexp nil
3699 "Local variable used by `orgtbl-mode'.")
3701 (defconst orgtbl-line-start-regexp
3702 "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\|TBLNAME\\):\\)"
3703 "Matches a line belonging to an orgtbl.")
3705 (defconst orgtbl-extra-font-lock-keywords
3706 (list (list (concat "^" orgtbl-line-start-regexp ".*")
3707 0 (quote 'org-table) 'prepend))
3708 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
3710 ;; Install it as a minor mode.
3711 (put 'orgtbl-mode :included t)
3712 (put 'orgtbl-mode :menu-tag "Org Table Mode")
3714 ;;;###autoload
3715 (define-minor-mode orgtbl-mode
3716 "The `org-mode' table editor as a minor mode for use in other modes."
3717 :lighter " OrgTbl" :keymap orgtbl-mode-map
3718 (org-load-modules-maybe)
3719 (cond
3720 ((org-mode-p)
3721 ;; Exit without error, in case some hook functions calls this
3722 ;; by accident in org-mode.
3723 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
3724 (orgtbl-mode
3725 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
3726 ;; Make sure we are first in minor-mode-map-alist
3727 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
3728 ;; FIXME: maybe it should use emulation-mode-map-alists?
3729 (and c (setq minor-mode-map-alist
3730 (cons c (delq c minor-mode-map-alist)))))
3731 (org-set-local (quote org-table-may-need-update) t)
3732 (org-add-hook 'before-change-functions 'org-before-change-function
3733 nil 'local)
3734 (org-set-local 'org-old-auto-fill-inhibit-regexp
3735 auto-fill-inhibit-regexp)
3736 (org-set-local 'auto-fill-inhibit-regexp
3737 (if auto-fill-inhibit-regexp
3738 (concat orgtbl-line-start-regexp "\\|"
3739 auto-fill-inhibit-regexp)
3740 orgtbl-line-start-regexp))
3741 (add-to-invisibility-spec '(org-cwidth))
3742 (when (fboundp 'font-lock-add-keywords)
3743 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
3744 (org-restart-font-lock))
3745 (easy-menu-add orgtbl-mode-menu))
3747 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
3748 (org-table-cleanup-narrow-column-properties)
3749 (org-remove-from-invisibility-spec '(org-cwidth))
3750 (remove-hook 'before-change-functions 'org-before-change-function t)
3751 (when (fboundp 'font-lock-remove-keywords)
3752 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
3753 (org-restart-font-lock))
3754 (easy-menu-remove orgtbl-mode-menu)
3755 (force-mode-line-update 'all))))
3757 (defun org-table-cleanup-narrow-column-properties ()
3758 "Remove all properties related to narrow-column invisibility."
3759 (let ((s (point-min)))
3760 (while (setq s (text-property-any s (point-max)
3761 'display org-narrow-column-arrow))
3762 (remove-text-properties s (1+ s) '(display t)))
3763 (setq s (point-min))
3764 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
3765 (remove-text-properties s (1+ s) '(org-cwidth t)))
3766 (setq s (point-min))
3767 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
3768 (remove-text-properties s (1+ s) '(invisible t)))))
3770 (defun orgtbl-make-binding (fun n &rest keys)
3771 "Create a function for binding in the table minor mode.
3772 FUN is the command to call inside a table. N is used to create a unique
3773 command name. KEYS are keys that should be checked in for a command
3774 to execute outside of tables."
3775 (eval
3776 (list 'defun
3777 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
3778 '(arg)
3779 (concat "In tables, run `" (symbol-name fun) "'.\n"
3780 "Outside of tables, run the binding of `"
3781 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
3782 "'.")
3783 '(interactive "p")
3784 (list 'if
3785 '(org-at-table-p)
3786 (list 'call-interactively (list 'quote fun))
3787 (list 'let '(orgtbl-mode)
3788 (list 'call-interactively
3789 (append '(or)
3790 (mapcar (lambda (k)
3791 (list 'key-binding k))
3792 keys)
3793 '('orgtbl-error))))))))
3795 (defun orgtbl-error ()
3796 "Error when there is no default binding for a table key."
3797 (interactive)
3798 (error "This key has no function outside tables"))
3800 (defun orgtbl-setup ()
3801 "Setup orgtbl keymaps."
3802 (let ((nfunc 0)
3803 (bindings
3804 '(([(meta shift left)] org-table-delete-column)
3805 ([(meta left)] org-table-move-column-left)
3806 ([(meta right)] org-table-move-column-right)
3807 ([(meta shift right)] org-table-insert-column)
3808 ([(meta shift up)] org-table-kill-row)
3809 ([(meta shift down)] org-table-insert-row)
3810 ([(meta up)] org-table-move-row-up)
3811 ([(meta down)] org-table-move-row-down)
3812 ("\C-c\C-w" org-table-cut-region)
3813 ("\C-c\M-w" org-table-copy-region)
3814 ("\C-c\C-y" org-table-paste-rectangle)
3815 ("\C-c-" org-table-insert-hline)
3816 ("\C-c}" org-table-toggle-coordinate-overlays)
3817 ("\C-c{" org-table-toggle-formula-debugger)
3818 ("\C-m" org-table-next-row)
3819 ([(shift return)] org-table-copy-down)
3820 ("\C-c?" org-table-field-info)
3821 ("\C-c " org-table-blank-field)
3822 ("\C-c+" org-table-sum)
3823 ("\C-c=" org-table-eval-formula)
3824 ("\C-c'" org-table-edit-formulas)
3825 ("\C-c`" org-table-edit-field)
3826 ("\C-c*" org-table-recalculate)
3827 ("\C-c^" org-table-sort-lines)
3828 ("\M-a" org-table-beginning-of-field)
3829 ("\M-e" org-table-end-of-field)
3830 ([(control ?#)] org-table-rotate-recalc-marks)))
3831 elt key fun cmd)
3832 (while (setq elt (pop bindings))
3833 (setq nfunc (1+ nfunc))
3834 (setq key (org-key (car elt))
3835 fun (nth 1 elt)
3836 cmd (orgtbl-make-binding fun nfunc key))
3837 (org-defkey orgtbl-mode-map key cmd))
3839 ;; Special treatment needed for TAB and RET
3840 (org-defkey orgtbl-mode-map [(return)]
3841 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
3842 (org-defkey orgtbl-mode-map "\C-m"
3843 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
3845 (org-defkey orgtbl-mode-map [(tab)]
3846 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
3847 (org-defkey orgtbl-mode-map "\C-i"
3848 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
3850 (org-defkey orgtbl-mode-map [(shift tab)]
3851 (orgtbl-make-binding 'org-table-previous-field 104
3852 [(shift tab)] [(tab)] "\C-i"))
3855 (unless (featurep 'xemacs)
3856 (org-defkey orgtbl-mode-map [S-iso-lefttab]
3857 (orgtbl-make-binding 'org-table-previous-field 107
3858 [S-iso-lefttab] [backtab] [(shift tab)]
3859 [(tab)] "\C-i")))
3861 (org-defkey orgtbl-mode-map [backtab]
3862 (orgtbl-make-binding 'org-table-previous-field 108
3863 [backtab] [S-iso-lefttab] [(shift tab)]
3864 [(tab)] "\C-i"))
3866 (org-defkey orgtbl-mode-map "\M-\C-m"
3867 (orgtbl-make-binding 'org-table-wrap-region 105
3868 "\M-\C-m" [(meta return)]))
3869 (org-defkey orgtbl-mode-map [(meta return)]
3870 (orgtbl-make-binding 'org-table-wrap-region 106
3871 [(meta return)] "\M-\C-m"))
3873 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
3874 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
3876 (when orgtbl-optimized
3877 ;; If the user wants maximum table support, we need to hijack
3878 ;; some standard editing functions
3879 (org-remap orgtbl-mode-map
3880 'self-insert-command 'orgtbl-self-insert-command
3881 'delete-char 'org-delete-char
3882 'delete-backward-char 'org-delete-backward-char)
3883 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
3884 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
3885 '("OrgTbl"
3886 ["Create or convert" org-table-create-or-convert-from-region
3887 :active (not (org-at-table-p)) :keys "C-c |" ]
3888 "--"
3889 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
3890 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
3891 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
3892 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
3893 "--"
3894 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
3895 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
3896 ["Copy Field from Above"
3897 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
3898 "--"
3899 ("Column"
3900 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
3901 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
3902 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
3903 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
3904 ("Row"
3905 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
3906 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
3907 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
3908 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
3909 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
3910 "--"
3911 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
3912 ("Rectangle"
3913 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
3914 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
3915 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
3916 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
3917 "--"
3918 ("Radio tables"
3919 ["Insert table template" orgtbl-insert-radio-table
3920 (assq major-mode orgtbl-radio-table-templates)]
3921 ["Comment/uncomment table" orgtbl-toggle-comment t])
3922 "--"
3923 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
3924 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
3925 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
3926 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
3927 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
3928 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
3929 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
3930 ["Sum Column/Rectangle" org-table-sum
3931 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
3932 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
3933 ["Debug Formulas"
3934 org-table-toggle-formula-debugger :active (org-at-table-p)
3935 :keys "C-c {"
3936 :style toggle :selected org-table-formula-debug]
3937 ["Show Col/Row Numbers"
3938 org-table-toggle-coordinate-overlays :active (org-at-table-p)
3939 :keys "C-c }"
3940 :style toggle :selected org-table-overlay-coordinates]
3944 (defun orgtbl-ctrl-c-ctrl-c (arg)
3945 "If the cursor is inside a table, realign the table.
3946 If it is a table to be sent away to a receiver, do it.
3947 With prefix arg, also recompute table."
3948 (interactive "P")
3949 (let ((pos (point)) action consts-str consts cst const-str)
3950 (save-excursion
3951 (beginning-of-line 1)
3952 (setq action (cond
3953 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
3954 ((looking-at "[ \t]*|") pos)
3955 ((looking-at "[ \t]*#\\+TBLFM:") 'recalc))))
3956 (cond
3957 ((integerp action)
3958 (goto-char action)
3959 (org-table-maybe-eval-formula)
3960 (if arg
3961 (call-interactively 'org-table-recalculate)
3962 (org-table-maybe-recalculate-line))
3963 (call-interactively 'org-table-align)
3964 (when (orgtbl-send-table 'maybe)
3965 (run-hooks 'orgtbl-after-send-table-hook)))
3966 ((eq action 'recalc)
3967 (save-excursion
3968 (goto-char (point-min))
3969 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t)
3970 (setq const-str (substring-no-properties (match-string 1)))
3971 (setq consts (append consts (org-split-string const-str "[ \t]+")))
3972 (when consts
3973 (let (e)
3974 (while (setq e (pop consts))
3975 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3976 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3977 (setq org-table-formula-constants-local cst)))))
3978 (save-excursion
3979 (beginning-of-line 1)
3980 (skip-chars-backward " \r\n\t")
3981 (if (org-at-table-p)
3982 (org-call-with-arg 'org-table-recalculate t))))
3983 (t (let (orgtbl-mode)
3984 (call-interactively (key-binding "\C-c\C-c")))))))
3986 (defun orgtbl-create-or-convert-from-region (arg)
3987 "Create table or convert region to table, if no conflicting binding.
3988 This installs the table binding `C-c |', but only if there is no
3989 conflicting binding to this key outside orgtbl-mode."
3990 (interactive "P")
3991 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
3992 (if cmd
3993 (call-interactively cmd)
3994 (call-interactively 'org-table-create-or-convert-from-region))))
3996 (defun orgtbl-tab (arg)
3997 "Justification and field motion for `orgtbl-mode'."
3998 (interactive "P")
3999 (if arg (org-table-edit-field t)
4000 (org-table-justify-field-maybe)
4001 (org-table-next-field)))
4003 (defun orgtbl-ret ()
4004 "Justification and field motion for `orgtbl-mode'."
4005 (interactive)
4006 (if (bobp)
4007 (newline)
4008 (org-table-justify-field-maybe)
4009 (org-table-next-row)))
4011 (defun orgtbl-self-insert-command (N)
4012 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4013 If the cursor is in a table looking at whitespace, the whitespace is
4014 overwritten, and the table is not marked as requiring realignment."
4015 (interactive "p")
4016 (if (and (org-at-table-p)
4018 (and org-table-auto-blank-field
4019 (member last-command
4020 '(orgtbl-hijacker-command-100
4021 orgtbl-hijacker-command-101
4022 orgtbl-hijacker-command-102
4023 orgtbl-hijacker-command-103
4024 orgtbl-hijacker-command-104
4025 orgtbl-hijacker-command-105
4026 yas/expand))
4027 (org-table-blank-field))
4029 (eq N 1)
4030 (looking-at "[^|\n]* +|"))
4031 (let (org-table-may-need-update)
4032 (goto-char (1- (match-end 0)))
4033 (delete-backward-char 1)
4034 (goto-char (match-beginning 0))
4035 (self-insert-command N))
4036 (setq org-table-may-need-update t)
4037 (let* (orgtbl-mode
4039 (cmd (or (key-binding
4040 (or (and (listp function-key-map)
4041 (setq a (assoc last-input-event function-key-map))
4042 (cdr a))
4043 (vector last-input-event)))
4044 'self-insert-command)))
4045 (call-interactively cmd)
4046 (if (and org-self-insert-cluster-for-undo
4047 (eq cmd 'self-insert-command))
4048 (if (not (eq last-command 'orgtbl-self-insert-command))
4049 (setq org-self-insert-command-undo-counter 1)
4050 (if (>= org-self-insert-command-undo-counter 20)
4051 (setq org-self-insert-command-undo-counter 1)
4052 (and (> org-self-insert-command-undo-counter 0)
4053 buffer-undo-list
4054 (not (cadr buffer-undo-list)) ; remove nil entry
4055 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4056 (setq org-self-insert-command-undo-counter
4057 (1+ org-self-insert-command-undo-counter))))))))
4059 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4060 "Regular expression matching exponentials as produced by calc.")
4062 (defun orgtbl-export (table target)
4063 (require 'org-exp)
4064 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
4065 (lines (org-split-string table "[ \t]*\n[ \t]*"))
4066 org-table-last-alignment org-table-last-column-widths
4067 maxcol column)
4068 (if (not (fboundp func))
4069 (error "Cannot export orgtbl table to %s" target))
4070 (setq lines (org-table-clean-before-export lines))
4071 (setq table
4072 (mapcar
4073 (lambda (x)
4074 (if (string-match org-table-hline-regexp x)
4075 'hline
4076 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4077 lines))
4078 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
4079 table)))
4080 (loop for i from (1- maxcol) downto 0 do
4081 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
4082 (setq column (delq nil column))
4083 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
4084 (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))
4085 (funcall func table nil)))
4087 (defun orgtbl-gather-send-defs ()
4088 "Gather a plist of :name, :transform, :params for each destination before
4089 a radio table."
4090 (save-excursion
4091 (goto-char (org-table-begin))
4092 (let (rtn)
4093 (beginning-of-line 0)
4094 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4095 (let ((name (org-no-properties (match-string 1)))
4096 (transform (intern (match-string 2)))
4097 (params (if (match-end 3)
4098 (read (concat "(" (match-string 3) ")")))))
4099 (push (list :name name :transform transform :params params)
4100 rtn)
4101 (beginning-of-line 0)))
4102 rtn)))
4104 (defun orgtbl-send-replace-tbl (name txt)
4105 "Find and replace table NAME with TXT."
4106 (save-excursion
4107 (goto-char (point-min))
4108 (unless (re-search-forward
4109 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4110 (error "Don't know where to insert translated table"))
4111 (goto-char (match-beginning 0))
4112 (beginning-of-line 2)
4113 (save-excursion
4114 (let ((beg (point)))
4115 (unless (re-search-forward
4116 (concat "END RECEIVE ORGTBL +" name) nil t)
4117 (error "Cannot find end of insertion region"))
4118 (beginning-of-line 1)
4119 (delete-region beg (point))))
4120 (insert txt "\n")))
4122 ;;;###autoload
4123 (defun org-table-to-lisp (&optional txt)
4124 "Convert the table at point to a Lisp structure.
4125 The structure will be a list. Each item is either the symbol `hline'
4126 for a horizontal separator line, or a list of field values as strings.
4127 The table is taken from the parameter TXT, or from the buffer at point."
4128 (unless txt
4129 (unless (org-at-table-p)
4130 (error "No table at point")))
4131 (let* ((txt (or txt
4132 (buffer-substring-no-properties (org-table-begin)
4133 (org-table-end))))
4134 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4136 (mapcar
4137 (lambda (x)
4138 (if (string-match org-table-hline-regexp x)
4139 'hline
4140 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4141 lines)))
4143 (defun orgtbl-send-table (&optional maybe)
4144 "Send a transformed version of this table to the receiver position.
4145 With argument MAYBE, fail quietly if no transformation is defined for
4146 this table."
4147 (interactive)
4148 (catch 'exit
4149 (unless (org-at-table-p) (error "Not at a table"))
4150 ;; when non-interactive, we assume align has just happened.
4151 (when (interactive-p) (org-table-align))
4152 (let ((dests (orgtbl-gather-send-defs))
4153 (txt (buffer-substring-no-properties (org-table-begin)
4154 (org-table-end)))
4155 (ntbl 0))
4156 (unless dests (if maybe (throw 'exit nil)
4157 (error "Don't know how to transform this table")))
4158 (dolist (dest dests)
4159 (let* ((name (plist-get dest :name))
4160 (transform (plist-get dest :transform))
4161 (params (plist-get dest :params))
4162 (skip (plist-get params :skip))
4163 (skipcols (plist-get params :skipcols))
4165 (lines (org-table-clean-before-export
4166 (nthcdr (or skip 0)
4167 (org-split-string txt "[ \t]*\n[ \t]*"))))
4168 (i0 (if org-table-clean-did-remove-column 2 1))
4169 (table (mapcar
4170 (lambda (x)
4171 (if (string-match org-table-hline-regexp x)
4172 'hline
4173 (org-remove-by-index
4174 (org-split-string (org-trim x) "\\s-*|\\s-*")
4175 skipcols i0)))
4176 lines))
4177 (fun (if (= i0 2) 'cdr 'identity))
4178 (org-table-last-alignment
4179 (org-remove-by-index (funcall fun org-table-last-alignment)
4180 skipcols i0))
4181 (org-table-last-column-widths
4182 (org-remove-by-index (funcall fun org-table-last-column-widths)
4183 skipcols i0))
4184 (txt (if (fboundp transform)
4185 (funcall transform table params)
4186 (error "No such transformation function %s" transform))))
4187 (orgtbl-send-replace-tbl name txt))
4188 (setq ntbl (1+ ntbl)))
4189 (message "Table converted and installed at %d receiver location%s"
4190 ntbl (if (> ntbl 1) "s" ""))
4191 (if (> ntbl 0)
4192 ntbl
4193 nil))))
4195 (defun org-remove-by-index (list indices &optional i0)
4196 "Remove the elements in LIST with indices in INDICES.
4197 First element has index 0, or I0 if given."
4198 (if (not indices)
4199 list
4200 (if (integerp indices) (setq indices (list indices)))
4201 (setq i0 (1- (or i0 0)))
4202 (delq :rm (mapcar (lambda (x)
4203 (setq i0 (1+ i0))
4204 (if (memq i0 indices) :rm x))
4205 list))))
4207 (defun orgtbl-toggle-comment ()
4208 "Comment or uncomment the orgtbl at point."
4209 (interactive)
4210 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4211 (re2 (concat "^" orgtbl-line-start-regexp))
4212 (commented (save-excursion (beginning-of-line 1)
4213 (cond ((looking-at re1) t)
4214 ((looking-at re2) nil)
4215 (t (error "Not at an org table")))))
4216 (re (if commented re1 re2))
4217 beg end)
4218 (save-excursion
4219 (beginning-of-line 1)
4220 (while (looking-at re) (beginning-of-line 0))
4221 (beginning-of-line 2)
4222 (setq beg (point))
4223 (while (looking-at re) (beginning-of-line 2))
4224 (setq end (point)))
4225 (comment-region beg end (if commented '(4) nil))))
4227 (defun orgtbl-insert-radio-table ()
4228 "Insert a radio table template appropriate for this major mode."
4229 (interactive)
4230 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4231 (txt (nth 1 e))
4232 name pos)
4233 (unless e (error "No radio table setup defined for %s" major-mode))
4234 (setq name (read-string "Table name: "))
4235 (while (string-match "%n" txt)
4236 (setq txt (replace-match name t t txt)))
4237 (or (bolp) (insert "\n"))
4238 (setq pos (point))
4239 (insert txt)
4240 (goto-char pos)))
4242 ;; Dynamically bound input and output for table formatting.
4243 (defvar *orgtbl-table* nil
4244 "Carries the current table through formatting routines.")
4245 (defvar *orgtbl-rtn* nil
4246 "Formatting routines push the output lines here.")
4247 ;; Formatting parameters for the current table section.
4248 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4249 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4250 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4251 (defvar *orgtbl-fmt* nil "Format for each entry.")
4252 (defvar *orgtbl-efmt* nil "Format for numbers.")
4253 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4254 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4255 (defvar *orgtbl-lstart* nil "Text starting a row.")
4256 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4257 (defvar *orgtbl-lend* nil "Text ending a row.")
4258 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4260 (defsubst orgtbl-get-fmt (fmt i)
4261 "Retrieve the format from FMT corresponding to the Ith column."
4262 (if (and (not (functionp fmt)) (consp fmt))
4263 (plist-get fmt i)
4264 fmt))
4266 (defsubst orgtbl-apply-fmt (fmt &rest args)
4267 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4268 (cond ((functionp fmt) (apply fmt args))
4269 (fmt (apply 'format fmt args))
4270 (args (car args))
4271 (t args)))
4273 (defsubst orgtbl-eval-str (str)
4274 "If STR is a function, evaluate it with no arguments."
4275 (if (functionp str)
4276 (funcall str)
4277 str))
4279 (defun orgtbl-format-line (line)
4280 "Format LINE as a table row."
4281 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4282 (let* ((i 0)
4283 (line
4284 (mapcar
4285 (lambda (f)
4286 (setq i (1+ i))
4287 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4288 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4289 (orgtbl-apply-fmt efmt (match-string 1 f)
4290 (match-string 2 f))
4291 f)))
4292 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4293 *orgtbl-default-fmt*)
4294 f)))
4295 line)))
4296 (push (if *orgtbl-lfmt*
4297 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4298 (concat (orgtbl-eval-str *orgtbl-lstart*)
4299 (mapconcat 'identity line *orgtbl-sep*)
4300 (orgtbl-eval-str *orgtbl-lend*)))
4301 *orgtbl-rtn*))))
4303 (defun orgtbl-format-section (section-stopper)
4304 "Format lines until the first occurrence of SECTION-STOPPER."
4305 (let (prevline)
4306 (progn
4307 (while (not (eq (car *orgtbl-table*) section-stopper))
4308 (if prevline (orgtbl-format-line prevline))
4309 (setq prevline (pop *orgtbl-table*)))
4310 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4311 (*orgtbl-lend* *orgtbl-llend*)
4312 (*orgtbl-lfmt* *orgtbl-llfmt*))
4313 (orgtbl-format-line prevline))))))
4315 (defun orgtbl-to-generic (table params)
4316 "Convert the orgtbl-mode TABLE to some other format.
4317 This generic routine can be used for many standard cases.
4318 TABLE is a list, each entry either the symbol `hline' for a horizontal
4319 separator line, or a list of fields for that line.
4320 PARAMS is a property list of parameters that can influence the conversion.
4321 For the generic converter, some parameters are obligatory: you need to
4322 specify either :lfmt, or all of (:lstart :lend :sep).
4324 Valid parameters are
4326 :splice When set to t, return only table body lines, don't wrap
4327 them into :tstart and :tend. Default is nil. When :splice
4328 is non-nil, this also means that the exporter should not look
4329 for and interpret header and footer sections.
4331 :hline String to be inserted on horizontal separation lines.
4332 May be nil to ignore hlines.
4334 :sep Separator between two fields
4335 :remove-nil-lines Do not include lines that evaluate to nil.
4338 Each in the following group may be either a string or a function
4339 of no arguments returning a string:
4340 :tstart String to start the table. Ignored when :splice is t.
4341 :tend String to end the table. Ignored when :splice is t.
4342 :lstart String to start a new table line.
4343 :llstart String to start the last table line, defaults to :lstart.
4344 :lend String to end a table line
4345 :llend String to end the last table line, defaults to :lend.
4347 Each in the following group may be a string, a function of one
4348 argument (the field or line) returning a string, or a plist
4349 mapping columns to either of the above:
4350 :lfmt Format for entire line, with enough %s to capture all fields.
4351 If this is present, :lstart, :lend, and :sep are ignored.
4352 :llfmt Format for the entire last line, defaults to :lfmt.
4353 :fmt A format to be used to wrap the field, should contain
4354 %s for the original field value. For example, to wrap
4355 everything in dollars, you could use :fmt \"$%s$\".
4356 This may also be a property list with column numbers and
4357 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4359 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4360 Same as above, specific for the header lines in the table.
4361 All lines before the first hline are treated as header.
4362 If any of these is not present, the data line value is used.
4364 This may be either a string or a function of two arguments:
4365 :efmt Use this format to print numbers with exponentials.
4366 The format should have %s twice for inserting mantissa
4367 and exponent, for example \"%s\\\\times10^{%s}\". This
4368 may also be a property list with column numbers and
4369 formats. :fmt will still be applied after :efmt.
4371 In addition to this, the parameters :skip and :skipcols are always handled
4372 directly by `orgtbl-send-table'. See manual."
4373 (interactive)
4375 (let* ((splicep (plist-get params :splice))
4376 (hline (plist-get params :hline))
4377 (remove-nil-linesp (plist-get params :remove-nil-lines))
4378 (remove-newlines (plist-get params :remove-newlines))
4379 (*orgtbl-hline* hline)
4380 (*orgtbl-table* table)
4381 (*orgtbl-sep* (plist-get params :sep))
4382 (*orgtbl-efmt* (plist-get params :efmt))
4383 (*orgtbl-lstart* (plist-get params :lstart))
4384 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4385 (*orgtbl-lend* (plist-get params :lend))
4386 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4387 (*orgtbl-lfmt* (plist-get params :lfmt))
4388 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4389 (*orgtbl-fmt* (plist-get params :fmt))
4390 *orgtbl-rtn*)
4392 ;; Put header
4393 (unless splicep
4394 (when (plist-member params :tstart)
4395 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4396 (if tstart (push tstart *orgtbl-rtn*)))))
4398 ;; Do we have a heading section? If so, format it and handle the
4399 ;; trailing hline.
4400 (if (and (not splicep)
4401 (or (consp (car *orgtbl-table*))
4402 (consp (nth 1 *orgtbl-table*)))
4403 (memq 'hline (cdr *orgtbl-table*)))
4404 (progn
4405 (when (eq 'hline (car *orgtbl-table*))
4406 ;; there is a hline before the first data line
4407 (and hline (push hline *orgtbl-rtn*))
4408 (pop *orgtbl-table*))
4409 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4410 *orgtbl-lstart*))
4411 (*orgtbl-llstart* (or (plist-get params :hllstart)
4412 *orgtbl-llstart*))
4413 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4414 (*orgtbl-llend* (or (plist-get params :hllend)
4415 (plist-get params :hlend) *orgtbl-llend*))
4416 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4417 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4418 (plist-get params :hlfmt) *orgtbl-llfmt*))
4419 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4420 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4421 (orgtbl-format-section 'hline))
4422 (if hline (push hline *orgtbl-rtn*))
4423 (pop *orgtbl-table*)))
4425 ;; Now format the main section.
4426 (orgtbl-format-section nil)
4428 (unless splicep
4429 (when (plist-member params :tend)
4430 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4431 (if tend (push tend *orgtbl-rtn*)))))
4433 (mapconcat (if remove-newlines
4434 (lambda (tend)
4435 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4436 'identity)
4437 (nreverse (if remove-nil-linesp
4438 (remq nil *orgtbl-rtn*)
4439 *orgtbl-rtn*)) "\n")))
4441 (defun orgtbl-to-tsv (table params)
4442 "Convert the orgtbl-mode table to TAB separated material."
4443 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4444 (defun orgtbl-to-csv (table params)
4445 "Convert the orgtbl-mode table to CSV material.
4446 This does take care of the proper quoting of fields with comma or quotes."
4447 (orgtbl-to-generic table (org-combine-plists
4448 '(:sep "," :fmt org-quote-csv-field)
4449 params)))
4451 (defun orgtbl-to-latex (table params)
4452 "Convert the orgtbl-mode TABLE to LaTeX.
4453 TABLE is a list, each entry either the symbol `hline' for a horizontal
4454 separator line, or a list of fields for that line.
4455 PARAMS is a property list of parameters that can influence the conversion.
4456 Supports all parameters from `orgtbl-to-generic'. Most important for
4457 LaTeX are:
4459 :splice When set to t, return only table body lines, don't wrap
4460 them into a tabular environment. Default is nil.
4462 :fmt A format to be used to wrap the field, should contain %s for the
4463 original field value. For example, to wrap everything in dollars,
4464 use :fmt \"$%s$\". This may also be a property list with column
4465 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4466 The format may also be a function that formats its one argument.
4468 :efmt Format for transforming numbers with exponentials. The format
4469 should have %s twice for inserting mantissa and exponent, for
4470 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4471 This may also be a property list with column numbers and formats.
4472 The format may also be a function that formats its two arguments.
4474 :llend If you find too much space below the last line of a table,
4475 pass a value of \"\" for :llend to suppress the final \\\\.
4477 The general parameters :skip and :skipcols have already been applied when
4478 this function is called."
4479 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4480 org-table-last-alignment ""))
4481 (params2
4482 (list
4483 :tstart (concat "\\begin{tabular}{" alignment "}")
4484 :tend "\\end{tabular}"
4485 :lstart "" :lend " \\\\" :sep " & "
4486 :efmt "%s\\,(%s)" :hline "\\hline")))
4487 (orgtbl-to-generic table (org-combine-plists params2 params))))
4489 (defun orgtbl-to-html (table params)
4490 "Convert the orgtbl-mode TABLE to HTML.
4491 TABLE is a list, each entry either the symbol `hline' for a horizontal
4492 separator line, or a list of fields for that line.
4493 PARAMS is a property list of parameters that can influence the conversion.
4494 Currently this function recognizes the following parameters:
4496 :splice When set to t, return only table body lines, don't wrap
4497 them into a <table> environment. Default is nil.
4499 The general parameters :skip and :skipcols have already been applied when
4500 this function is called. The function does *not* use `orgtbl-to-generic',
4501 so you cannot specify parameters for it."
4502 (let* ((splicep (plist-get params :splice))
4503 (html-table-tag org-export-html-table-tag)
4504 html)
4505 ;; Just call the formatter we already have
4506 ;; We need to make text lines for it, so put the fields back together.
4507 (setq html (org-format-org-table-html
4508 (mapcar
4509 (lambda (x)
4510 (if (eq x 'hline)
4511 "|----+----|"
4512 (concat "| " (mapconcat 'org-html-expand x " | ") " |")))
4513 table)
4514 splicep))
4515 (if (string-match "\n+\\'" html)
4516 (setq html (replace-match "" t t html)))
4517 html))
4519 (defun orgtbl-to-texinfo (table params)
4520 "Convert the orgtbl-mode TABLE to TeXInfo.
4521 TABLE is a list, each entry either the symbol `hline' for a horizontal
4522 separator line, or a list of fields for that line.
4523 PARAMS is a property list of parameters that can influence the conversion.
4524 Supports all parameters from `orgtbl-to-generic'. Most important for
4525 TeXInfo are:
4527 :splice nil/t When set to t, return only table body lines, don't wrap
4528 them into a multitable environment. Default is nil.
4530 :fmt fmt A format to be used to wrap the field, should contain
4531 %s for the original field value. For example, to wrap
4532 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4533 This may also be a property list with column numbers and
4534 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4535 Each format also may be a function that formats its one
4536 argument.
4538 :cf \"f1 f2..\" The column fractions for the table. By default these
4539 are computed automatically from the width of the columns
4540 under org-mode.
4542 The general parameters :skip and :skipcols have already been applied when
4543 this function is called."
4544 (let* ((total (float (apply '+ org-table-last-column-widths)))
4545 (colfrac (or (plist-get params :cf)
4546 (mapconcat
4547 (lambda (x) (format "%.3f" (/ (float x) total)))
4548 org-table-last-column-widths " ")))
4549 (params2
4550 (list
4551 :tstart (concat "@multitable @columnfractions " colfrac)
4552 :tend "@end multitable"
4553 :lstart "@item " :lend "" :sep " @tab "
4554 :hlstart "@headitem ")))
4555 (orgtbl-to-generic table (org-combine-plists params2 params))))
4557 (defun orgtbl-to-orgtbl (table params)
4558 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4559 Useful when slicing one table into many. The :hline, :sep,
4560 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4561 and :tend suppress strings without splicing; they can be set to
4562 provide ORGTBL directives for the generated table."
4563 (let* ((params2
4564 (list
4565 :remove-newlines t
4566 :tstart nil :tend nil
4567 :hline "|---"
4568 :sep " | "
4569 :lstart "| "
4570 :lend " |"))
4571 (params (org-combine-plists params2 params)))
4572 (orgtbl-to-generic table params)))
4574 (defun org-table-get-remote-range (name-or-id form)
4575 "Get a field value or a list of values in a range from table at ID.
4577 NAME-OR-ID may be the name of a table in the current file as set by
4578 a \"#+TBLNAME:\" directive. The first table following this line
4579 will then be used. Alternatively, it may be an ID referring to
4580 any entry, also in a different file. In this case, the first table
4581 in that entry will be referenced.
4582 FORM is a field or range descriptor like \"@2$3\" or or \"B3\" or
4583 \"@I$2..@II$2\". All the references must be absolute, not relative.
4585 The return value is either a single string for a single field, or a
4586 list of the fields in the rectangle ."
4587 (save-match-data
4588 (let ((id-loc nil)
4589 org-table-column-names org-table-column-name-regexp
4590 org-table-local-parameters org-table-named-field-locations
4591 org-table-current-line-types org-table-current-begin-line
4592 org-table-current-begin-pos org-table-dlines
4593 org-table-current-ncol
4594 org-table-hlines org-table-last-alignment
4595 org-table-last-column-widths org-table-last-alignment
4596 org-table-last-column-widths tbeg
4597 buffer loc)
4598 (setq form (org-table-convert-refs-to-rc form))
4599 (save-excursion
4600 (save-restriction
4601 (widen)
4602 (save-excursion
4603 (goto-char (point-min))
4604 (if (re-search-forward
4605 (concat "^[ \t]*#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4606 nil t)
4607 (setq buffer (current-buffer) loc (match-beginning 0))
4608 (setq id-loc (org-id-find name-or-id 'marker))
4609 (unless (and id-loc (markerp id-loc))
4610 (error "Can't find remote table \"%s\"" name-or-id))
4611 (setq buffer (marker-buffer id-loc)
4612 loc (marker-position id-loc))
4613 (move-marker id-loc nil)))
4614 (with-current-buffer buffer
4615 (save-excursion
4616 (save-restriction
4617 (widen)
4618 (goto-char loc)
4619 (forward-char 1)
4620 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4621 (not (match-beginning 1)))
4622 (error "Cannot find a table at NAME or ID %s" name-or-id))
4623 (setq tbeg (point-at-bol))
4624 (org-table-get-specials)
4625 (setq form (org-table-formula-substitute-names form))
4626 (if (and (string-match org-table-range-regexp form)
4627 (> (length (match-string 0 form)) 1))
4628 (save-match-data
4629 (org-table-get-range (match-string 0 form) tbeg 1))
4630 form)))))))))
4632 (provide 'org-table)
4634 ;; arch-tag: 4d21cfdd-0268-440a-84b0-09237a0fe0ef
4636 ;;; org-table.el ends here