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