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