Fix `org-hide-archived-subtrees'
[org-mode/org-tableheadings.git] / lisp / org-table.el
blobfa59113e260f746ef0e5ed6465a6a236a2ea2488
1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004-2014 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-export-string-as "ox"
42 (string backend &optional body-only ext-plist))
43 (declare-function org-export-create-backend "ox")
44 (declare-function org-export-get-backend "ox" (name))
46 (declare-function calc-eval "calc" (str &optional separator &rest args))
48 (defvar orgtbl-mode) ; defined below
49 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
50 (defvar constants-unit-system)
51 (defvar org-table-follow-field-mode)
53 (defvar orgtbl-after-send-table-hook nil
54 "Hook for functions attaching to `C-c C-c', if the table is sent.
55 This can be used to add additional functionality after the table is sent
56 to the receiver position, otherwise, if table is not sent, the functions
57 are not run.")
59 (defvar org-table-TBLFM-begin-regexp "|\n[ \t]*#\\+TBLFM: ")
61 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
62 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
63 In the optimized version, the table editor takes over all simple keys that
64 normally just insert a character. In tables, the characters are inserted
65 in a way to minimize disturbing the table structure (i.e. in overwrite mode
66 for empty fields). Outside tables, the correct binding of the keys is
67 restored.
69 The default for this option is t if the optimized version is also used in
70 Org-mode. See the variable `org-enable-table-editor' for details. Changing
71 this variable requires a restart of Emacs to become effective."
72 :group 'org-table
73 :type 'boolean)
75 (defcustom orgtbl-radio-table-templates
76 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
77 % END RECEIVE ORGTBL %n
78 \\begin{comment}
79 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
80 | | |
81 \\end{comment}\n")
82 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
83 @c END RECEIVE ORGTBL %n
84 @ignore
85 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
86 | | |
87 @end ignore\n")
88 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
89 <!-- END RECEIVE ORGTBL %n -->
90 <!--
91 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
92 | | |
93 -->\n")
94 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
95 #+ END RECEIVE ORGTBL %n
97 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
98 | | |
99 "))
100 "Templates for radio tables in different major modes.
101 Each template must define lines that will be treated as a comment and that
102 must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
103 lines where \"%n\" will be replaced with the name of the table during
104 insertion of the template. The transformed table will later be inserted
105 between these lines.
107 The template should also contain a minimal table in a multiline comment.
108 If multiline comments are not possible in the buffer language,
109 you can pack it into a string that will not be used when the code
110 is compiled or executed. Above the table will you need a line with
111 the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
112 convert the table into a data structure useful in the
113 language of the buffer. Check the manual for the section on
114 \"Translator functions\", and more generally check out
115 http://orgmode.org/manual/Tables-in-arbitrary-syntax.html#Tables-in-arbitrary-syntax
117 All occurrences of %n in a template will be replaced with the name of the
118 table, obtained by prompting the user."
119 :group 'org-table
120 :type '(repeat
121 (list (symbol :tag "Major mode")
122 (string :tag "Format"))))
124 (defgroup org-table-settings nil
125 "Settings for tables in Org-mode."
126 :tag "Org Table Settings"
127 :group 'org-table)
129 (defcustom org-table-default-size "5x2"
130 "The default size for newly created tables, Columns x Rows."
131 :group 'org-table-settings
132 :type 'string)
134 (defcustom org-table-number-regexp
135 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
136 "Regular expression for recognizing numbers in table columns.
137 If a table column contains mostly numbers, it will be aligned to the
138 right. If not, it will be aligned to the left.
140 The default value of this option is a regular expression which allows
141 anything which looks remotely like a number as used in scientific
142 context. For example, all of the following will be considered a
143 number:
144 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
146 Other options offered by the customize interface are more restrictive."
147 :group 'org-table-settings
148 :type '(choice
149 (const :tag "Positive Integers"
150 "^[0-9]+$")
151 (const :tag "Integers"
152 "^[-+]?[0-9]+$")
153 (const :tag "Floating Point Numbers"
154 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
155 (const :tag "Floating Point Number or Integer"
156 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
157 (const :tag "Exponential, Floating point, Integer"
158 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
159 (const :tag "Very General Number-Like, including hex and Calc radix"
160 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
161 (const :tag "Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
162 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
163 (string :tag "Regexp:")))
165 (defcustom org-table-number-fraction 0.5
166 "Fraction of numbers in a column required to make the column align right.
167 In a column all non-white fields are considered. If at least
168 this fraction of fields is matched by `org-table-number-regexp',
169 alignment to the right border applies."
170 :group 'org-table-settings
171 :type 'number)
173 (defgroup org-table-editing nil
174 "Behavior of tables during editing in Org-mode."
175 :tag "Org Table Editing"
176 :group 'org-table)
178 (defcustom org-table-automatic-realign t
179 "Non-nil means automatically re-align table when pressing TAB or RETURN.
180 When nil, aligning is only done with \\[org-table-align], or after column
181 removal/insertion."
182 :group 'org-table-editing
183 :type 'boolean)
185 (defcustom org-table-auto-blank-field t
186 "Non-nil means automatically blank table field when starting to type into it.
187 This only happens when typing immediately after a field motion
188 command (TAB, S-TAB or RET).
189 Only relevant when `org-enable-table-editor' is equal to `optimized'."
190 :group 'org-table-editing
191 :type 'boolean)
193 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
194 "Non-nil means automatically exit the follow mode.
195 When nil, the follow mode will stay on and be active in any table
196 the cursor enters. Since the table follow filed mode messes with the
197 window configuration, it is not recommended to set this variable to nil,
198 except maybe locally in a special file that has mostly tables with long
199 fields."
200 :group 'org-table
201 :version "24.1"
202 :type 'boolean)
204 (defcustom org-table-fix-formulas-confirm nil
205 "Whether the user should confirm when Org fixes formulas."
206 :group 'org-table-editing
207 :version "24.1"
208 :type '(choice
209 (const :tag "with yes-or-no" yes-or-no-p)
210 (const :tag "with y-or-n" y-or-n-p)
211 (const :tag "no confirmation" nil)))
212 (put 'org-table-fix-formulas-confirm
213 'safe-local-variable
214 #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
216 (defcustom org-table-tab-jumps-over-hlines t
217 "Non-nil means tab in the last column of a table with jump over a hline.
218 If a horizontal separator line is following the current line,
219 `org-table-next-field' can either create a new row before that line, or jump
220 over the line. When this option is nil, a new line will be created before
221 this line."
222 :group 'org-table-editing
223 :type 'boolean)
225 (defgroup org-table-calculation nil
226 "Options concerning tables in Org-mode."
227 :tag "Org Table Calculation"
228 :group 'org-table)
230 (defcustom org-table-use-standard-references 'from
231 "Should org-mode work with table references like B3 instead of @3$2?
232 Possible values are:
233 nil never use them
234 from accept as input, do not present for editing
235 t accept as input and present for editing"
236 :group 'org-table-calculation
237 :type '(choice
238 (const :tag "Never, don't even check user input for them" nil)
239 (const :tag "Always, both as user input, and when editing" t)
240 (const :tag "Convert user input, don't offer during editing" from)))
242 (defcustom org-table-copy-increment t
243 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
244 :group 'org-table-calculation
245 :version "25.1"
246 :package-version '(Org . "8.3")
247 :type '(choice
248 (const :tag "Use the difference between the current and the above fields" t)
249 (integer :tag "Use a number" 1)
250 (const :tag "Don't increment the value when copying a field" nil)))
252 (defcustom org-calc-default-modes
253 '(calc-internal-prec 12
254 calc-float-format (float 8)
255 calc-angle-mode deg
256 calc-prefer-frac nil
257 calc-symbolic-mode nil
258 calc-date-format (YYYY "-" MM "-" DD " " Www (" " hh ":" mm))
259 calc-display-working-message t
261 "List with Calc mode settings for use in `calc-eval' for table formulas.
262 The list must contain alternating symbols (Calc modes variables and values).
263 Don't remove any of the default settings, just change the values. Org-mode
264 relies on the variables to be present in the list."
265 :group 'org-table-calculation
266 :type 'plist)
268 (defcustom org-table-duration-custom-format 'hours
269 "Format for the output of calc computations like $1+$2;t.
270 The default value is 'hours, and will output the results as a
271 number of hours. Other allowed values are 'seconds, 'minutes and
272 'days, and the output will be a fraction of seconds, minutes or
273 days."
274 :group 'org-table-calculation
275 :version "24.1"
276 :type '(choice (symbol :tag "Seconds" 'seconds)
277 (symbol :tag "Minutes" 'minutes)
278 (symbol :tag "Hours " 'hours)
279 (symbol :tag "Days " 'days)))
281 (defcustom org-table-formula-field-format "%s"
282 "Format for fields which contain the result of a formula.
283 For example, using \"~%s~\" will display the result within tilde
284 characters. Beware that modifying the display can prevent the
285 field from being used in another formula."
286 :group 'org-table-settings
287 :version "24.1"
288 :type 'string)
290 (defcustom org-table-formula-evaluate-inline t
291 "Non-nil means TAB and RET evaluate a formula in current table field.
292 If the current field starts with an equal sign, it is assumed to be a formula
293 which should be evaluated as described in the manual and in the documentation
294 string of the command `org-table-eval-formula'. This feature requires the
295 Emacs calc package.
296 When this variable is nil, formula calculation is only available through
297 the command \\[org-table-eval-formula]."
298 :group 'org-table-calculation
299 :type 'boolean)
301 (defcustom org-table-formula-use-constants t
302 "Non-nil means interpret constants in formulas in tables.
303 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
304 by the value given in `org-table-formula-constants', or by a value obtained
305 from the `constants.el' package."
306 :group 'org-table-calculation
307 :type 'boolean)
309 (defcustom org-table-formula-constants nil
310 "Alist with constant names and values, for use in table formulas.
311 The car of each element is a name of a constant, without the `$' before it.
312 The cdr is the value as a string. For example, if you'd like to use the
313 speed of light in a formula, you would configure
315 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
317 and then use it in an equation like `$1*$c'.
319 Constants can also be defined on a per-file basis using a line like
321 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
322 :group 'org-table-calculation
323 :type '(repeat
324 (cons (string :tag "name")
325 (string :tag "value"))))
327 (defcustom org-table-allow-automatic-line-recalculation t
328 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
329 Automatically means when TAB or RET or C-c C-c are pressed in the line."
330 :group 'org-table-calculation
331 :type 'boolean)
333 (defcustom org-table-error-on-row-ref-crossing-hline t
334 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
335 :group 'org-table
336 :type 'boolean)
338 (defcustom org-table-relative-ref-may-cross-hline t
339 "Non-nil means relative formula references may cross hlines.
340 Here are the allowed values:
342 nil Relative references may not cross hlines. They will reference the
343 field next to the hline instead. Coming from below, the reference
344 will be to the field below the hline. Coming from above, it will be
345 to the field above.
346 t Relative references may cross hlines.
347 error An attempt to cross a hline will throw an error.
349 It is probably good to never set this variable to nil, for the sake of
350 portability of tables."
351 :group 'org-table-calculation
352 :type '(choice
353 (const :tag "Allow to cross" t)
354 (const :tag "Stick to hline" nil)
355 (const :tag "Error on attempt to cross" error)))
357 (defcustom org-table-formula-create-columns nil
358 "Non-nil means that evaluation of a field formula can add new
359 columns if an out-of-bounds field is being set."
360 :group 'org-table-calculation
361 :version "25.1"
362 :package-version '(Org . "8.3")
363 :type '(choice
364 (const :tag "Setting an out-of-bounds field generates an error (default)" nil)
365 (const :tag "Setting an out-of-bounds field silently adds columns as needed" t)
366 (const :tag "Setting an out-of-bounds field adds columns as needed, but issues a warning message" warn)
367 (const :tag "When setting an out-of-bounds field, the user is prompted" prompt)))
369 (defgroup org-table-import-export nil
370 "Options concerning table import and export in Org-mode."
371 :tag "Org Table Import Export"
372 :group 'org-table)
374 (defcustom org-table-export-default-format "orgtbl-to-tsv"
375 "Default export parameters for `org-table-export'.
376 These can be overridden for a specific table by setting the
377 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
378 radio tables for the different export transformations and
379 available parameters."
380 :group 'org-table-import-export
381 :type 'string)
383 (defcustom org-table-convert-region-max-lines 999
384 "Max lines that `org-table-convert-region' will attempt to process.
386 The function can be slow on larger regions; this safety feature
387 prevents it from hanging emacs."
388 :group 'org-table-import-export
389 :type 'integer
390 :version "25.1"
391 :package-version '(Org . "8.3"))
393 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
394 "Detects a table line marked for automatic recalculation.")
395 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
396 "Detects a table line marked for automatic recalculation.")
397 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
398 "Detects a table line marked for automatic recalculation.")
399 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
400 "Searching from within a table (any type) this finds the first line outside the table.")
401 (defvar org-table-last-highlighted-reference nil)
402 (defvar org-table-formula-history nil)
404 (defvar org-table-column-names nil
405 "Alist with column names, derived from the `!' line.")
406 (defvar org-table-column-name-regexp nil
407 "Regular expression matching the current column names.")
408 (defvar org-table-local-parameters nil
409 "Alist with parameter names, derived from the `$' line.")
410 (defvar org-table-named-field-locations nil
411 "Alist with locations of named fields.")
413 (defvar org-table-current-line-types nil
414 "Table row types, non-nil only for the duration of a command.")
415 (defvar org-table-current-begin-line nil
416 "Table begin line, non-nil only for the duration of a command.")
417 (defvar org-table-current-begin-pos nil
418 "Table begin position, non-nil only for the duration of a command.")
419 (defvar org-table-current-ncol nil
420 "Number of columns in table, non-nil only for the duration of a command.")
421 (defvar org-table-dlines nil
422 "Vector of data line line numbers in the current table.")
423 (defvar org-table-hlines nil
424 "Vector of hline line numbers in the current table.")
426 (defconst org-table-range-regexp
427 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
428 ;; 1 2 3 4 5
429 "Regular expression for matching ranges in formulas.")
431 (defconst org-table-range-regexp2
432 (concat
433 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
434 "\\.\\."
435 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
436 "Match a range for reference display.")
438 (defun org-table-colgroup-line-p (line)
439 "Is this a table line colgroup information?"
440 (save-match-data
441 (and (string-match "[<>]\\|&[lg]t;" line)
442 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
443 line)
444 (not (delq
446 (mapcar
447 (lambda (s)
448 (not (member s '("" "<" ">" "<>" "&lt;" "&gt;" "&lt;&gt;"))))
449 (org-split-string (match-string 1 line) "[ \t]*|[ \t]*")))))))
451 (defun org-table-cookie-line-p (line)
452 "Is this a table line with only alignment/width cookies?"
453 (save-match-data
454 (and (string-match "[<>]\\|&[lg]t;" line)
455 (or (string-match
456 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line)
457 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line))
458 (not (delq nil (mapcar
459 (lambda (s)
460 (not (or (equal s "")
461 (string-match
462 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s)
463 (string-match
464 "\\`&lt;\\([lrc]?[0-9]+\\|[lrc]\\)&gt;\\'"
465 s))))
466 (org-split-string (match-string 1 line)
467 "[ \t]*|[ \t]*")))))))
469 (defconst org-table-translate-regexp
470 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
471 "Match a reference that needs translation, for reference display.")
473 ;;;###autoload
474 (defun org-table-create-with-table.el ()
475 "Use the table.el package to insert a new table.
476 If there is already a table at point, convert between Org-mode tables
477 and table.el tables."
478 (interactive)
479 (require 'table)
480 (cond
481 ((org-at-table.el-p)
482 (if (y-or-n-p "Convert table to Org-mode table? ")
483 (org-table-convert)))
484 ((org-at-table-p)
485 (when (y-or-n-p "Convert table to table.el table? ")
486 (org-table-align)
487 (org-table-convert)))
488 (t (call-interactively 'table-insert))))
490 ;;;###autoload
491 (defun org-table-create-or-convert-from-region (arg)
492 "Convert region to table, or create an empty table.
493 If there is an active region, convert it to a table, using the function
494 `org-table-convert-region'. See the documentation of that function
495 to learn how the prefix argument is interpreted to determine the field
496 separator.
497 If there is no such region, create an empty table with `org-table-create'."
498 (interactive "P")
499 (if (org-region-active-p)
500 (org-table-convert-region (region-beginning) (region-end) arg)
501 (org-table-create arg)))
503 ;;;###autoload
504 (defun org-table-create (&optional size)
505 "Query for a size and insert a table skeleton.
506 SIZE is a string Columns x Rows like for example \"3x2\"."
507 (interactive "P")
508 (unless size
509 (setq size (read-string
510 (concat "Table size Columns x Rows [e.g. "
511 org-table-default-size "]: ")
512 "" nil org-table-default-size)))
514 (let* ((pos (point))
515 (indent (make-string (current-column) ?\ ))
516 (split (org-split-string size " *x *"))
517 (rows (string-to-number (nth 1 split)))
518 (columns (string-to-number (car split)))
519 (line (concat (apply 'concat indent "|" (make-list columns " |"))
520 "\n")))
521 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
522 (point-at-bol) (point)))
523 (beginning-of-line 1)
524 (newline))
525 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
526 (dotimes (i rows) (insert line))
527 (goto-char pos)
528 (if (> rows 1)
529 ;; Insert a hline after the first row.
530 (progn
531 (end-of-line 1)
532 (insert "\n|-")
533 (goto-char pos)))
534 (org-table-align)))
536 ;;;###autoload
537 (defun org-table-convert-region (beg0 end0 &optional separator)
538 "Convert region to a table.
539 The region goes from BEG0 to END0, but these borders will be moved
540 slightly, to make sure a beginning of line in the first line is included.
542 SEPARATOR specifies the field separator in the lines. It can have the
543 following values:
545 '(4) Use the comma as a field separator
546 '(16) Use a TAB as field separator
547 '(64) Prompt for a regular expression as field separator
548 integer When a number, use that many spaces as field separator
549 regexp When a regular expression, use it to match the separator
550 nil When nil, the command tries to be smart and figure out the
551 separator in the following way:
552 - when each line contains a TAB, assume TAB-separated material
553 - when each line contains a comma, assume CSV material
554 - else, assume one or more SPACE characters as separator."
555 (interactive "r\nP")
556 (let* ((beg (min beg0 end0))
557 (end (max beg0 end0))
559 (if (> (count-lines beg end) org-table-convert-region-max-lines)
560 (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
561 org-table-convert-region-max-lines)
562 (if (equal separator '(64))
563 (setq separator (read-regexp "Regexp for field separator")))
564 (goto-char beg)
565 (beginning-of-line 1)
566 (setq beg (point-marker))
567 (goto-char end)
568 (if (bolp) (backward-char 1) (end-of-line 1))
569 (setq end (point-marker))
570 ;; Get the right field separator
571 (unless separator
572 (goto-char beg)
573 (setq separator
574 (cond
575 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
576 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
577 (t 1))))
578 (goto-char beg)
579 (if (equal separator '(4))
580 (while (< (point) end)
581 ;; parse the csv stuff
582 (cond
583 ((looking-at "^") (insert "| "))
584 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
585 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
586 (replace-match "\\1")
587 (if (looking-at "\"") (insert "\"")))
588 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
589 ((looking-at "[ \t]*,") (replace-match " | "))
590 (t (beginning-of-line 2))))
591 (setq re (cond
592 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
593 ((equal separator '(16)) "^\\|\t")
594 ((integerp separator)
595 (if (< separator 1)
596 (user-error "Number of spaces in separator must be >= 1")
597 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
598 ((stringp separator)
599 (format "^ *\\|%s" separator))
600 (t (error "This should not happen"))))
601 (while (re-search-forward re end t)
602 (replace-match "| " t t)))
603 (goto-char beg)
604 (org-table-align))))
606 ;;;###autoload
607 (defun org-table-import (file arg)
608 "Import FILE as a table.
609 The file is assumed to be tab-separated. Such files can be produced by most
610 spreadsheet and database applications. If no tabs (at least one per line)
611 are found, lines will be split on whitespace into fields."
612 (interactive "f\nP")
613 (or (bolp) (newline))
614 (let ((beg (point))
615 (pm (point-max)))
616 (insert-file-contents file)
617 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
620 ;;;###autoload
621 (defun org-table-export (&optional file format)
622 "Export table to a file, with configurable format.
623 Such a file can be imported into usual spreadsheet programs.
625 FILE can be the output file name. If not given, it will be taken
626 from a TABLE_EXPORT_FILE property in the current entry or higher
627 up in the hierarchy, or the user will be prompted for a file
628 name. FORMAT can be an export format, of the same kind as it
629 used when `orgtbl-mode' sends a table in a different format.
631 The command suggests a format depending on TABLE_EXPORT_FORMAT,
632 whether it is set locally or up in the hierarchy, then on the
633 extension of the given file name, and finally on the variable
634 `org-table-export-default-format'."
635 (interactive)
636 (unless (org-at-table-p) (user-error "No table at point"))
637 (org-table-align) ; Make sure we have everything we need.
638 (let ((file (or file (org-entry-get (point) "TABLE_EXPORT_FILE" t))))
639 (unless file
640 (setq file (read-file-name "Export table to: "))
641 (unless (or (not (file-exists-p file))
642 (y-or-n-p (format "Overwrite file %s? " file)))
643 (user-error "File not written")))
644 (when (file-directory-p file)
645 (user-error "This is a directory path, not a file"))
646 (when (and (buffer-file-name (buffer-base-buffer))
647 (org-file-equal-p
648 (file-truename file)
649 (file-truename (buffer-file-name (buffer-base-buffer)))))
650 (user-error "Please specify a file name that is different from current"))
651 (let ((fileext (concat (file-name-extension file) "$"))
652 (format (or format (org-entry-get (point) "TABLE_EXPORT_FORMAT" t))))
653 (unless format
654 (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
655 "orgtbl-to-html" "orgtbl-to-generic"
656 "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
657 "orgtbl-to-unicode"))
658 (deffmt-readable
659 (replace-regexp-in-string
660 "\t" "\\t"
661 (replace-regexp-in-string
662 "\n" "\\n"
663 (or (car (delq nil
664 (mapcar
665 (lambda (f)
666 (and (org-string-match-p fileext f) f))
667 formats)))
668 org-table-export-default-format)
669 t t) t t)))
670 (setq format
671 (org-completing-read
672 "Format: " formats nil nil deffmt-readable))))
673 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format)
674 (let ((transform (intern (match-string 1 format)))
675 (params (and (match-end 2)
676 (read (concat "(" (match-string 2 format) ")"))))
677 (table (org-table-to-lisp
678 (buffer-substring-no-properties
679 (org-table-begin) (org-table-end)))))
680 (unless (fboundp transform)
681 (user-error "No such transformation function %s" transform))
682 (let (buf)
683 (with-current-buffer (find-file-noselect file)
684 (setq buf (current-buffer))
685 (erase-buffer)
686 (fundamental-mode)
687 (insert (funcall transform table params) "\n")
688 (save-buffer))
689 (kill-buffer buf))
690 (message "Export done."))
691 (user-error "TABLE_EXPORT_FORMAT invalid")))))
693 (defvar org-table-aligned-begin-marker (make-marker)
694 "Marker at the beginning of the table last aligned.
695 Used to check if cursor still is in that table, to minimize realignment.")
696 (defvar org-table-aligned-end-marker (make-marker)
697 "Marker at the end of the table last aligned.
698 Used to check if cursor still is in that table, to minimize realignment.")
699 (defvar org-table-last-alignment nil
700 "List of flags for flushright alignment, from the last re-alignment.
701 This is being used to correctly align a single field after TAB or RET.")
702 (defvar org-table-last-column-widths nil
703 "List of max width of fields in each column.
704 This is being used to correctly align a single field after TAB or RET.")
705 (defvar org-table-formula-debug nil
706 "Non-nil means debug table formulas.
707 When nil, simply write \"#ERROR\" in corrupted fields.")
708 (make-variable-buffer-local 'org-table-formula-debug)
709 (defvar org-table-overlay-coordinates nil
710 "Overlay coordinates after each align of a table.")
711 (make-variable-buffer-local 'org-table-overlay-coordinates)
713 (defvar org-last-recalc-line nil)
714 (defvar org-table-do-narrow t) ; for dynamic scoping
715 (defconst org-narrow-column-arrow "=>"
716 "Used as display property in narrowed table columns.")
718 ;;;###autoload
719 (defun org-table-align ()
720 "Align the table at point by aligning all vertical bars."
721 (interactive)
722 (let* (
723 ;; Limits of table
724 (beg (org-table-begin))
725 (end (org-table-end))
726 ;; Current cursor position
727 (linepos (org-current-line))
728 (colpos (org-table-current-column))
729 (winstart (window-start))
730 (winstartline (org-current-line (min winstart (1- (point-max)))))
731 lines (new "") lengths l typenums ty fields maxfields i
732 column
733 (indent "") cnt frac
734 rfmt hfmt
735 (spaces '(1 . 1))
736 (sp1 (car spaces))
737 (sp2 (cdr spaces))
738 (rfmt1 (concat
739 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
740 (hfmt1 (concat
741 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
742 emptystrings links dates emph raise narrow
743 falign falign1 fmax f1 f2 len c e space)
744 (untabify beg end)
745 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
746 ;; Check if we have links or dates
747 (goto-char beg)
748 (setq links (re-search-forward org-bracket-link-regexp end t))
749 (goto-char beg)
750 (setq emph (and org-hide-emphasis-markers
751 (re-search-forward org-emph-re end t)))
752 (goto-char beg)
753 (setq raise (and org-use-sub-superscripts
754 (re-search-forward org-match-substring-regexp end t)))
755 (goto-char beg)
756 (setq dates (and org-display-custom-times
757 (re-search-forward org-ts-regexp-both end t)))
758 ;; Make sure the link properties are right
759 (when links (goto-char beg) (while (org-activate-bracket-links end)))
760 ;; Make sure the date properties are right
761 (when dates (goto-char beg) (while (org-activate-dates end)))
762 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
763 (when raise (goto-char beg) (while (org-raise-scripts end)))
765 ;; Check if we are narrowing any columns
766 (goto-char beg)
767 (setq narrow (and org-table-do-narrow
768 org-format-transports-properties-p
769 (re-search-forward "<[lrc]?[0-9]+>" end t)))
770 (goto-char beg)
771 (setq falign (re-search-forward "<[lrc][0-9]*>" end t))
772 (goto-char beg)
773 ;; Get the rows
774 (setq lines (org-split-string
775 (buffer-substring beg end) "\n"))
776 ;; Store the indentation of the first line
777 (if (string-match "^ *" (car lines))
778 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
779 ;; Mark the hlines by setting the corresponding element to nil
780 ;; At the same time, we remove trailing space.
781 (setq lines (mapcar (lambda (l)
782 (if (string-match "^ *|-" l)
784 (if (string-match "[ \t]+$" l)
785 (substring l 0 (match-beginning 0))
786 l)))
787 lines))
788 ;; Get the data fields by splitting the lines.
789 (setq fields (mapcar
790 (lambda (l)
791 (org-split-string l " *| *"))
792 (delq nil (copy-sequence lines))))
793 ;; How many fields in the longest line?
794 (condition-case nil
795 (setq maxfields (apply 'max (mapcar 'length fields)))
796 (error
797 (kill-region beg end)
798 (org-table-create org-table-default-size)
799 (user-error "Empty table - created default table")))
800 ;; A list of empty strings to fill any short rows on output
801 (setq emptystrings (make-list maxfields ""))
802 ;; Check for special formatting.
803 (setq i -1)
804 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
805 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
806 ;; Check if there is an explicit width specified
807 (setq fmax nil)
808 (when (or narrow falign)
809 (setq c column fmax nil falign1 nil)
810 (while c
811 (setq e (pop c))
812 (when (and (stringp e) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e))
813 (if (match-end 1) (setq falign1 (match-string 1 e)))
814 (if (and org-table-do-narrow (match-end 2))
815 (setq fmax (string-to-number (match-string 2 e)) c nil))))
816 ;; Find fields that are wider than fmax, and shorten them
817 (when fmax
818 (loop for xx in column do
819 (when (and (stringp xx)
820 (> (org-string-width xx) fmax))
821 (org-add-props xx nil
822 'help-echo
823 (concat "Clipped table field, use C-c ` to edit. Full value is:\n"
824 (org-no-properties (copy-sequence xx))))
825 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
826 (unless (> f1 1)
827 (user-error "Cannot narrow field starting with wide link \"%s\""
828 (match-string 0 xx)))
829 (setq f2 (length xx))
830 (if (= (org-string-width xx)
832 (setq f2 f1)
833 (setq f2 1)
834 (while (< (org-string-width (substring xx 0 f2))
836 (setq f2 (1+ f2))))
837 (add-text-properties f2 (length xx) (list 'org-cwidth t) xx)
838 (add-text-properties (if (>= (string-width (substring xx (1- f2) f2)) 2)
839 (1- f2) (- f2 2)) f2
840 (list 'display org-narrow-column-arrow)
841 xx)))))
842 ;; Get the maximum width for each column
843 (push (apply 'max (or fmax 1) 1 (mapcar 'org-string-width column))
844 lengths)
845 ;; Get the fraction of numbers, to decide about alignment of the column
846 (if falign1
847 (push (equal (downcase falign1) "r") typenums)
848 (setq cnt 0 frac 0.0)
849 (loop for x in column do
850 (if (equal x "")
852 (setq frac ( / (+ (* frac cnt)
853 (if (string-match org-table-number-regexp x) 1 0))
854 (setq cnt (1+ cnt))))))
855 (push (>= frac org-table-number-fraction) typenums)))
856 (setq lengths (nreverse lengths) typenums (nreverse typenums))
858 ;; Store the alignment of this table, for later editing of single fields
859 (setq org-table-last-alignment typenums
860 org-table-last-column-widths lengths)
862 ;; With invisible characters, `format' does not get the field width right
863 ;; So we need to make these fields wide by hand.
864 (when (or links emph raise)
865 (loop for i from 0 upto (1- maxfields) do
866 (setq len (nth i lengths))
867 (loop for j from 0 upto (1- (length fields)) do
868 (setq c (nthcdr i (car (nthcdr j fields))))
869 (if (and (stringp (car c))
870 (or (text-property-any 0 (length (car c))
871 'invisible 'org-link (car c))
872 (text-property-any 0 (length (car c))
873 'org-dwidth t (car c)))
874 (< (org-string-width (car c)) len))
875 (progn
876 (setq space (make-string (- len (org-string-width (car c))) ?\ ))
877 (setcar c (if (nth i typenums)
878 (concat space (car c))
879 (concat (car c) space))))))))
881 ;; Compute the formats needed for output of the table
882 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
883 (while (setq l (pop lengths))
884 (setq ty (if (pop typenums) "" "-")) ; number types flushright
885 (setq rfmt (concat rfmt (format rfmt1 ty l))
886 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
887 (setq rfmt (concat rfmt "\n")
888 hfmt (concat (substring hfmt 0 -1) "|\n"))
890 (setq new (mapconcat
891 (lambda (l)
892 (if l (apply 'format rfmt
893 (append (pop fields) emptystrings))
894 hfmt))
895 lines ""))
896 (move-marker org-table-aligned-begin-marker (point))
897 (insert new)
898 ;; Replace the old one
899 (delete-region (point) end)
900 (move-marker end nil)
901 (move-marker org-table-aligned-end-marker (point))
902 (when (and orgtbl-mode (not (derived-mode-p 'org-mode)))
903 (goto-char org-table-aligned-begin-marker)
904 (while (org-hide-wide-columns org-table-aligned-end-marker)))
905 ;; Try to move to the old location
906 (org-goto-line winstartline)
907 (setq winstart (point-at-bol))
908 (org-goto-line linepos)
909 (when (eq (window-buffer (selected-window)) (current-buffer))
910 (set-window-start (selected-window) winstart 'noforce))
911 (org-table-goto-column colpos)
912 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
913 (setq org-table-may-need-update nil)
916 ;;;###autoload
917 (defun org-table-begin (&optional table-type)
918 "Find the beginning of the table and return its position.
919 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
920 (save-excursion
921 (if (not (re-search-backward
922 (if table-type org-table-any-border-regexp
923 org-table-border-regexp)
924 nil t))
925 (progn (goto-char (point-min)) (point))
926 (goto-char (match-beginning 0))
927 (beginning-of-line 2)
928 (point))))
930 ;;;###autoload
931 (defun org-table-end (&optional table-type)
932 "Find the end of the table and return its position.
933 With argument TABLE-TYPE, go to the end of a table.el-type table."
934 (save-excursion
935 (if (not (re-search-forward
936 (if table-type org-table-any-border-regexp
937 org-table-border-regexp)
938 nil t))
939 (goto-char (point-max))
940 (goto-char (match-beginning 0)))
941 (point-marker)))
943 ;;;###autoload
944 (defun org-table-justify-field-maybe (&optional new)
945 "Justify the current field, text to left, number to right.
946 Optional argument NEW may specify text to replace the current field content."
947 (cond
948 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
949 ((org-at-table-hline-p))
950 ((and (not new)
951 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
952 (current-buffer)))
953 (< (point) org-table-aligned-begin-marker)
954 (>= (point) org-table-aligned-end-marker)))
955 ;; This is not the same table, force a full re-align
956 (setq org-table-may-need-update t))
957 (t ;; realign the current field, based on previous full realign
958 (let* ((pos (point)) s
959 (col (org-table-current-column))
960 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
961 l f n o e)
962 (when (> col 0)
963 (skip-chars-backward "^|\n")
964 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
965 (progn
966 (setq s (match-string 1)
967 o (match-string 0)
968 l (max 1
969 (- (org-string-width
970 (buffer-substring-no-properties
971 (match-end 0) (match-beginning 0))) 3))
972 e (not (= (match-beginning 2) (match-end 2))))
973 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
974 l (if e "|" (setq org-table-may-need-update t) ""))
975 n (format f s))
976 (if new
977 (if (<= (org-string-width new) l)
978 (setq n (format f new))
979 (setq n (concat new "|") org-table-may-need-update t)))
980 (if (equal (string-to-char n) ?-) (setq n (concat " " n)))
981 (or (equal n o)
982 (let (org-table-may-need-update)
983 (replace-match n t t))))
984 (setq org-table-may-need-update t))
985 (goto-char pos))))))
987 ;;;###autoload
988 (defun org-table-next-field ()
989 "Go to the next field in the current table, creating new lines as needed.
990 Before doing so, re-align the table if necessary."
991 (interactive)
992 (org-table-maybe-eval-formula)
993 (org-table-maybe-recalculate-line)
994 (if (and org-table-automatic-realign
995 org-table-may-need-update)
996 (org-table-align))
997 (let ((end (org-table-end)))
998 (if (org-at-table-hline-p)
999 (end-of-line 1))
1000 (condition-case nil
1001 (progn
1002 (re-search-forward "|" end)
1003 (if (looking-at "[ \t]*$")
1004 (re-search-forward "|" end))
1005 (if (and (looking-at "-")
1006 org-table-tab-jumps-over-hlines
1007 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
1008 (goto-char (match-beginning 1)))
1009 (if (looking-at "-")
1010 (progn
1011 (beginning-of-line 0)
1012 (org-table-insert-row 'below))
1013 (if (looking-at " ") (forward-char 1))))
1014 (error
1015 (org-table-insert-row 'below)))))
1017 ;;;###autoload
1018 (defun org-table-previous-field ()
1019 "Go to the previous field in the table.
1020 Before doing so, re-align the table if necessary."
1021 (interactive)
1022 (org-table-justify-field-maybe)
1023 (org-table-maybe-recalculate-line)
1024 (if (and org-table-automatic-realign
1025 org-table-may-need-update)
1026 (org-table-align))
1027 (if (org-at-table-hline-p)
1028 (end-of-line 1))
1029 (condition-case nil
1030 (progn
1031 (re-search-backward "|" (org-table-begin))
1032 (re-search-backward "|" (org-table-begin)))
1033 (error (user-error "Cannot move to previous table field")))
1034 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1035 (re-search-backward "|" (org-table-begin)))
1036 (if (looking-at "| ?")
1037 (goto-char (match-end 0))))
1039 (defun org-table-beginning-of-field (&optional n)
1040 "Move to the end of the current table field.
1041 If already at or after the end, move to the end of the next table field.
1042 With numeric argument N, move N-1 fields forward first."
1043 (interactive "p")
1044 (let ((pos (point)))
1045 (while (> n 1)
1046 (setq n (1- n))
1047 (org-table-previous-field))
1048 (if (not (re-search-backward "|" (point-at-bol 0) t))
1049 (user-error "No more table fields before the current")
1050 (goto-char (match-end 0))
1051 (and (looking-at " ") (forward-char 1)))
1052 (if (>= (point) pos) (org-table-beginning-of-field 2))))
1054 (defun org-table-end-of-field (&optional n)
1055 "Move to the beginning of the current table field.
1056 If already at or before the beginning, move to the beginning of the
1057 previous field.
1058 With numeric argument N, move N-1 fields backward first."
1059 (interactive "p")
1060 (let ((pos (point)))
1061 (while (> n 1)
1062 (setq n (1- n))
1063 (org-table-next-field))
1064 (when (re-search-forward "|" (point-at-eol 1) t)
1065 (backward-char 1)
1066 (skip-chars-backward " ")
1067 (if (and (equal (char-before (point)) ?|) (looking-at " "))
1068 (forward-char 1)))
1069 (if (<= (point) pos) (org-table-end-of-field 2))))
1071 ;;;###autoload
1072 (defun org-table-next-row ()
1073 "Go to the next row (same column) in the current table.
1074 Before doing so, re-align the table if necessary."
1075 (interactive)
1076 (org-table-maybe-eval-formula)
1077 (org-table-maybe-recalculate-line)
1078 (if (or (looking-at "[ \t]*$")
1079 (save-excursion (skip-chars-backward " \t") (bolp)))
1080 (newline)
1081 (if (and org-table-automatic-realign
1082 org-table-may-need-update)
1083 (org-table-align))
1084 (let ((col (org-table-current-column)))
1085 (beginning-of-line 2)
1086 (if (or (not (org-at-table-p))
1087 (org-at-table-hline-p))
1088 (progn
1089 (beginning-of-line 0)
1090 (org-table-insert-row 'below)))
1091 (org-table-goto-column col)
1092 (skip-chars-backward "^|\n\r")
1093 (if (looking-at " ") (forward-char 1)))))
1095 ;;;###autoload
1096 (defun org-table-copy-down (n)
1097 "Copy the value of the current field one row below.
1099 If the field at the cursor is empty, copy the content of the
1100 nearest non-empty field above. With argument N, use the Nth
1101 non-empty field.
1103 If the current field is not empty, it is copied down to the next
1104 row, and the cursor is moved with it. Therefore, repeating this
1105 command causes the column to be filled row-by-row.
1107 If the variable `org-table-copy-increment' is non-nil and the
1108 field is an integer or a timestamp, it will be incremented while
1109 copying. By default, increment by the difference between the
1110 value in the current field and the one in the field above. To
1111 increment using a fixed integer, set `org-table-copy-increment'
1112 to a number. In the case of a timestamp, increment by days."
1113 (interactive "p")
1114 (let* ((colpos (org-table-current-column))
1115 (col (current-column))
1116 (field (save-excursion (org-table-get-field)))
1117 (field-up (or (save-excursion
1118 (org-table-get (1- (org-table-current-line))
1119 (org-table-current-column))) ""))
1120 (non-empty (string-match "[^ \t]" field))
1121 (non-empty-up (string-match "[^ \t]" field-up))
1122 (beg (org-table-begin))
1123 (orig-n n)
1124 txt txt-up inc)
1125 (org-table-check-inside-data-field)
1126 (if (not non-empty)
1127 (save-excursion
1128 (setq txt
1129 (catch 'exit
1130 (while (progn (beginning-of-line 1)
1131 (re-search-backward org-table-dataline-regexp
1132 beg t))
1133 (org-table-goto-column colpos t)
1134 (if (and (looking-at
1135 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1136 (<= (setq n (1- n)) 0))
1137 (throw 'exit (match-string 1))))))
1138 (setq field-up
1139 (catch 'exit
1140 (while (progn (beginning-of-line 1)
1141 (re-search-backward org-table-dataline-regexp
1142 beg t))
1143 (org-table-goto-column colpos t)
1144 (if (and (looking-at
1145 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1146 (<= (setq n (1- n)) 0))
1147 (throw 'exit (match-string 1))))))
1148 (setq non-empty-up (and field-up (string-match "[^ \t]" field-up))))
1149 ;; Above field was not empty, go down to the next row
1150 (setq txt (org-trim field))
1151 (org-table-next-row)
1152 (org-table-blank-field))
1153 (if non-empty-up (setq txt-up (org-trim field-up)))
1154 (setq inc (cond
1155 ((numberp org-table-copy-increment) org-table-copy-increment)
1156 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up)
1157 (string-match org-ts-regexp3 txt))
1158 (- (org-time-string-to-absolute txt)
1159 (org-time-string-to-absolute txt-up)))
1160 ((string-match org-ts-regexp3 txt) 1)
1161 ((string-match "^[0-9]+\\(\.[0-9]+\\)?" txt-up)
1162 (- (string-to-number txt)
1163 (string-to-number (match-string 0 txt-up))))
1164 (t 1)))
1165 (t 1)))
1166 (if (not txt)
1167 (user-error "No non-empty field found")
1168 (if (and org-table-copy-increment
1169 (not (equal orig-n 0))
1170 (string-match "^[-+^/*0-9eE.]+$" txt)
1171 (< (string-to-number txt) 100000000))
1172 (setq txt (calc-eval (concat txt "+" (number-to-string inc)))))
1173 (insert txt)
1174 (org-move-to-column col)
1175 (if (and org-table-copy-increment (org-at-timestamp-p t))
1176 (org-timestamp-up-day inc)
1177 (org-table-maybe-recalculate-line))
1178 (org-table-align)
1179 (org-move-to-column col))))
1181 (defun org-table-check-inside-data-field (&optional noerror)
1182 "Is point inside a table data field?
1183 I.e. not on a hline or before the first or after the last column?
1184 This actually throws an error, so it aborts the current command."
1185 (if (or (not (org-at-table-p))
1186 (= (org-table-current-column) 0)
1187 (org-at-table-hline-p)
1188 (looking-at "[ \t]*$"))
1189 (if noerror
1191 (user-error "Not in table data field"))
1194 (defvar org-table-clip nil
1195 "Clipboard for table regions.")
1197 (defun org-table-get (line column)
1198 "Get the field in table line LINE, column COLUMN.
1199 If LINE is larger than the number of data lines in the table, the function
1200 returns nil. However, if COLUMN is too large, we will simply return an
1201 empty string.
1202 If LINE is nil, use the current line.
1203 If COLUMN is nil, use the current column."
1204 (setq column (or column (org-table-current-column)))
1205 (save-excursion
1206 (and (or (not line) (org-table-goto-line line))
1207 (org-trim (org-table-get-field column)))))
1209 (defun org-table-put (line column value &optional align)
1210 "Put VALUE into line LINE, column COLUMN.
1211 When ALIGN is set, also realign the table."
1212 (setq column (or column (org-table-current-column)))
1213 (prog1 (save-excursion
1214 (and (or (not line) (org-table-goto-line line))
1215 (progn (org-table-goto-column column nil 'force) t)
1216 (org-table-get-field column value)))
1217 (and align (org-table-align))))
1219 (defun org-table-current-line ()
1220 "Return the index of the current data line."
1221 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1222 (save-excursion
1223 (goto-char (org-table-begin))
1224 (while (and (re-search-forward org-table-dataline-regexp end t)
1225 (setq cnt (1+ cnt))
1226 (< (point-at-eol) pos))))
1227 cnt))
1229 (defun org-table-goto-line (N)
1230 "Go to the Nth data line in the current table.
1231 Return t when the line exists, nil if it does not exist."
1232 (goto-char (org-table-begin))
1233 (let ((end (org-table-end)) (cnt 0))
1234 (while (and (re-search-forward org-table-dataline-regexp end t)
1235 (< (setq cnt (1+ cnt)) N)))
1236 (= cnt N)))
1238 ;;;###autoload
1239 (defun org-table-blank-field ()
1240 "Blank the current table field or active region."
1241 (interactive)
1242 (org-table-check-inside-data-field)
1243 (if (and (org-called-interactively-p 'any) (org-region-active-p))
1244 (let (org-table-clip)
1245 (org-table-cut-region (region-beginning) (region-end)))
1246 (skip-chars-backward "^|")
1247 (backward-char 1)
1248 (if (looking-at "|[^|\n]+")
1249 (let* ((pos (match-beginning 0))
1250 (match (match-string 0))
1251 (len (org-string-width match)))
1252 (replace-match (concat "|" (make-string (1- len) ?\ )))
1253 (goto-char (+ 2 pos))
1254 (substring match 1)))))
1256 (defun org-table-get-field (&optional n replace)
1257 "Return the value of the field in column N of current row.
1258 N defaults to current field.
1259 If REPLACE is a string, replace field with this value. The return value
1260 is always the old value."
1261 (and n (org-table-goto-column n))
1262 (skip-chars-backward "^|\n")
1263 (backward-char 1)
1264 (if (looking-at "|[^|\r\n]*")
1265 (let* ((pos (match-beginning 0))
1266 (val (buffer-substring (1+ pos) (match-end 0))))
1267 (if replace
1268 (replace-match (concat "|" (if (equal replace "") " " replace))
1269 t t))
1270 (goto-char (min (point-at-eol) (+ 2 pos)))
1271 val)
1272 (forward-char 1) ""))
1274 ;;;###autoload
1275 (defun org-table-field-info (arg)
1276 "Show info about the current field, and highlight any reference at point."
1277 (interactive "P")
1278 (unless (org-at-table-p) (user-error "Not at a table"))
1279 (org-table-get-specials)
1280 (save-excursion
1281 (let* ((pos (point))
1282 (col (org-table-current-column))
1283 (cname (car (rassoc (int-to-string col) org-table-column-names)))
1284 (name (car (rassoc (list (org-current-line) col)
1285 org-table-named-field-locations)))
1286 (eql (org-table-expand-lhs-ranges
1287 (mapcar
1288 (lambda (e)
1289 (cons (org-table-formula-handle-first/last-rc
1290 (car e)) (cdr e)))
1291 (org-table-get-stored-formulas))))
1292 (dline (org-table-current-dline))
1293 (ref (format "@%d$%d" dline col))
1294 (ref1 (org-table-convert-refs-to-an ref))
1295 (fequation (or (assoc name eql) (assoc ref eql)))
1296 (cequation (assoc (int-to-string col) eql))
1297 (eqn (or fequation cequation)))
1298 (if (and eqn (get-text-property 0 :orig-eqn (car eqn)))
1299 (setq eqn (get-text-property 0 :orig-eqn (car eqn))))
1300 (goto-char pos)
1301 (condition-case nil
1302 (org-table-show-reference 'local)
1303 (error nil))
1304 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1305 dline col
1306 (if cname (concat " or $" cname) "")
1307 dline col ref1
1308 (if name (concat " or $" name) "")
1309 ;; FIXME: formula info not correct if special table line
1310 (if eqn
1311 (concat ", formula: "
1312 (org-table-formula-to-user
1313 (concat
1314 (if (string-match "^[$@]"(car eqn)) "" "$")
1315 (car eqn) "=" (cdr eqn))))
1316 "")))))
1318 (defun org-table-current-column ()
1319 "Find out which column we are in."
1320 (interactive)
1321 (if (org-called-interactively-p 'any) (org-table-check-inside-data-field))
1322 (save-excursion
1323 (let ((cnt 0) (pos (point)))
1324 (beginning-of-line 1)
1325 (while (search-forward "|" pos t)
1326 (setq cnt (1+ cnt)))
1327 (when (org-called-interactively-p 'interactive)
1328 (message "In table column %d" cnt))
1329 cnt)))
1331 ;;;###autoload
1332 (defun org-table-current-dline ()
1333 "Find out what table data line we are in.
1334 Only data lines count for this."
1335 (interactive)
1336 (when (org-called-interactively-p 'any)
1337 (org-table-check-inside-data-field))
1338 (save-excursion
1339 (let ((cnt 0) (pos (point)))
1340 (goto-char (org-table-begin))
1341 (while (<= (point) pos)
1342 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
1343 (beginning-of-line 2))
1344 (when (org-called-interactively-p 'any)
1345 (message "This is table line %d" cnt))
1346 cnt)))
1348 ;;;###autoload
1349 (defun org-table-goto-column (n &optional on-delim force)
1350 "Move the cursor to the Nth column in the current table line.
1351 With optional argument ON-DELIM, stop with point before the left delimiter
1352 of the field.
1353 If there are less than N fields, just go to after the last delimiter.
1354 However, when FORCE is non-nil, create new columns if necessary."
1355 (interactive "p")
1356 (beginning-of-line 1)
1357 (when (> n 0)
1358 (while (and (> (setq n (1- n)) -1)
1359 (or (search-forward "|" (point-at-eol) t)
1360 (and force
1361 (progn (end-of-line 1)
1362 (skip-chars-backward "^|")
1363 (insert " | ")
1364 t)))))
1365 (when (and force (not (looking-at ".*|")))
1366 (save-excursion (end-of-line 1) (insert " | ")))
1367 (if on-delim
1368 (backward-char 1)
1369 (if (looking-at " ") (forward-char 1)))))
1371 ;;;###autoload
1372 (defun org-table-insert-column ()
1373 "Insert a new column into the table."
1374 (interactive)
1375 (if (not (org-at-table-p))
1376 (user-error "Not at a table"))
1377 (org-table-find-dataline)
1378 (let* ((col (max 1 (org-table-current-column)))
1379 (beg (org-table-begin))
1380 (end (org-table-end))
1381 ;; Current cursor position
1382 (linepos (org-current-line))
1383 (colpos col))
1384 (goto-char beg)
1385 (while (< (point) end)
1386 (if (org-at-table-hline-p)
1388 (org-table-goto-column col t)
1389 (insert "| "))
1390 (beginning-of-line 2))
1391 (move-marker end nil)
1392 (org-goto-line linepos)
1393 (org-table-goto-column colpos)
1394 (org-table-align)
1395 (when (or (not org-table-fix-formulas-confirm)
1396 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1397 (org-table-fix-formulas "$" nil (1- col) 1)
1398 (org-table-fix-formulas "$LR" nil (1- col) 1))))
1400 (defun org-table-find-dataline ()
1401 "Find a data line in the current table, which is needed for column commands."
1402 (if (and (org-at-table-p)
1403 (not (org-at-table-hline-p)))
1405 (let ((col (current-column))
1406 (end (org-table-end)))
1407 (org-move-to-column col)
1408 (while (and (< (point) end)
1409 (or (not (= (current-column) col))
1410 (org-at-table-hline-p)))
1411 (beginning-of-line 2)
1412 (org-move-to-column col))
1413 (if (and (org-at-table-p)
1414 (not (org-at-table-hline-p)))
1416 (user-error
1417 "Please position cursor in a data line for column operations")))))
1419 (defun org-table-line-to-dline (line &optional above)
1420 "Turn a buffer line number into a data line number.
1421 If there is no data line in this line, return nil.
1422 If there is no matching dline (most likely te reference was a hline), the
1423 first dline below it is used. When ABOVE is non-nil, the one above is used."
1424 (catch 'exit
1425 (let ((ll (length org-table-dlines))
1427 (if above
1428 (progn
1429 (setq i (1- ll))
1430 (while (> i 0)
1431 (if (<= (aref org-table-dlines i) line)
1432 (throw 'exit i))
1433 (setq i (1- i))))
1434 (setq i 1)
1435 (while (< i ll)
1436 (if (>= (aref org-table-dlines i) line)
1437 (throw 'exit i))
1438 (setq i (1+ i)))))
1439 nil))
1441 ;;;###autoload
1442 (defun org-table-delete-column ()
1443 "Delete a column from the table."
1444 (interactive)
1445 (if (not (org-at-table-p))
1446 (user-error "Not at a table"))
1447 (org-table-find-dataline)
1448 (org-table-check-inside-data-field)
1449 (let* ((col (org-table-current-column))
1450 (beg (org-table-begin))
1451 (end (org-table-end))
1452 ;; Current cursor position
1453 (linepos (org-current-line))
1454 (colpos col))
1455 (goto-char beg)
1456 (while (< (point) end)
1457 (if (org-at-table-hline-p)
1459 (org-table-goto-column col t)
1460 (and (looking-at "|[^|\n]+|")
1461 (replace-match "|")))
1462 (beginning-of-line 2))
1463 (move-marker end nil)
1464 (org-goto-line linepos)
1465 (org-table-goto-column colpos)
1466 (org-table-align)
1467 (when (or (not org-table-fix-formulas-confirm)
1468 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1469 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
1470 col -1 col)
1471 (org-table-fix-formulas "$LR" (list (cons (number-to-string col) "INVALID"))
1472 col -1 col))))
1474 ;;;###autoload
1475 (defun org-table-move-column-right ()
1476 "Move column to the right."
1477 (interactive)
1478 (org-table-move-column nil))
1479 ;;;###autoload
1480 (defun org-table-move-column-left ()
1481 "Move column to the left."
1482 (interactive)
1483 (org-table-move-column 'left))
1485 ;;;###autoload
1486 (defun org-table-move-column (&optional left)
1487 "Move the current column to the right. With arg LEFT, move to the left."
1488 (interactive "P")
1489 (if (not (org-at-table-p))
1490 (user-error "Not at a table"))
1491 (org-table-find-dataline)
1492 (org-table-check-inside-data-field)
1493 (let* ((col (org-table-current-column))
1494 (col1 (if left (1- col) col))
1495 (beg (org-table-begin))
1496 (end (org-table-end))
1497 ;; Current cursor position
1498 (linepos (org-current-line))
1499 (colpos (if left (1- col) (1+ col))))
1500 (if (and left (= col 1))
1501 (user-error "Cannot move column further left"))
1502 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
1503 (user-error "Cannot move column further right"))
1504 (goto-char beg)
1505 (while (< (point) end)
1506 (if (org-at-table-hline-p)
1508 (org-table-goto-column col1 t)
1509 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1510 (replace-match "|\\2|\\1|")))
1511 (beginning-of-line 2))
1512 (move-marker end nil)
1513 (org-goto-line linepos)
1514 (org-table-goto-column colpos)
1515 (org-table-align)
1516 (when (or (not org-table-fix-formulas-confirm)
1517 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1518 (org-table-fix-formulas
1519 "$" (list (cons (number-to-string col) (number-to-string colpos))
1520 (cons (number-to-string colpos) (number-to-string col))))
1521 (org-table-fix-formulas
1522 "$LR" (list (cons (number-to-string col) (number-to-string colpos))
1523 (cons (number-to-string colpos) (number-to-string col)))))))
1525 ;;;###autoload
1526 (defun org-table-move-row-down ()
1527 "Move table row down."
1528 (interactive)
1529 (org-table-move-row nil))
1530 ;;;###autoload
1531 (defun org-table-move-row-up ()
1532 "Move table row up."
1533 (interactive)
1534 (org-table-move-row 'up))
1536 ;;;###autoload
1537 (defun org-table-move-row (&optional up)
1538 "Move the current table line down. With arg UP, move it up."
1539 (interactive "P")
1540 (let* ((col (current-column))
1541 (pos (point))
1542 (hline1p (save-excursion (beginning-of-line 1)
1543 (looking-at org-table-hline-regexp)))
1544 (dline1 (org-table-current-dline))
1545 (dline2 (+ dline1 (if up -1 1)))
1546 (tonew (if up 0 2))
1547 txt hline2p)
1548 (beginning-of-line tonew)
1549 (unless (org-at-table-p)
1550 (goto-char pos)
1551 (user-error "Cannot move row further"))
1552 (setq hline2p (looking-at org-table-hline-regexp))
1553 (goto-char pos)
1554 (beginning-of-line 1)
1555 (setq pos (point))
1556 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
1557 (delete-region (point) (1+ (point-at-eol)))
1558 (beginning-of-line tonew)
1559 (insert txt)
1560 (beginning-of-line 0)
1561 (org-move-to-column col)
1562 (unless (or hline1p hline2p
1563 (not (or (not org-table-fix-formulas-confirm)
1564 (funcall org-table-fix-formulas-confirm
1565 "Fix formulas? "))))
1566 (org-table-fix-formulas
1567 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
1568 (cons (number-to-string dline2) (number-to-string dline1)))))))
1570 ;;;###autoload
1571 (defun org-table-insert-row (&optional arg)
1572 "Insert a new row above the current line into the table.
1573 With prefix ARG, insert below the current line."
1574 (interactive "P")
1575 (if (not (org-at-table-p))
1576 (user-error "Not at a table"))
1577 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1578 (new (org-table-clean-line line)))
1579 ;; Fix the first field if necessary
1580 (if (string-match "^[ \t]*| *[#$] *|" line)
1581 (setq new (replace-match (match-string 0 line) t t new)))
1582 (beginning-of-line (if arg 2 1))
1583 (let (org-table-may-need-update) (insert-before-markers new "\n"))
1584 (beginning-of-line 0)
1585 (re-search-forward "| ?" (point-at-eol) t)
1586 (and (or org-table-may-need-update org-table-overlay-coordinates)
1587 (org-table-align))
1588 (when (or (not org-table-fix-formulas-confirm)
1589 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1590 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1))))
1592 ;;;###autoload
1593 (defun org-table-insert-hline (&optional above)
1594 "Insert a horizontal-line below the current line into the table.
1595 With prefix ABOVE, insert above the current line."
1596 (interactive "P")
1597 (if (not (org-at-table-p))
1598 (user-error "Not at a table"))
1599 (when (eobp) (insert "\n") (backward-char 1))
1600 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1601 (org-table-align))
1602 (let ((line (org-table-clean-line
1603 (buffer-substring (point-at-bol) (point-at-eol))))
1604 (col (current-column)))
1605 (while (string-match "|\\( +\\)|" line)
1606 (setq line (replace-match
1607 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1608 ?-) "|") t t line)))
1609 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
1610 (beginning-of-line (if above 1 2))
1611 (insert line "\n")
1612 (beginning-of-line (if above 1 -1))
1613 (org-move-to-column col)
1614 (and org-table-overlay-coordinates (org-table-align))))
1616 ;;;###autoload
1617 (defun org-table-hline-and-move (&optional same-column)
1618 "Insert a hline and move to the row below that line."
1619 (interactive "P")
1620 (let ((col (org-table-current-column)))
1621 (org-table-maybe-eval-formula)
1622 (org-table-maybe-recalculate-line)
1623 (org-table-insert-hline)
1624 (end-of-line 2)
1625 (if (looking-at "\n[ \t]*|-")
1626 (progn (insert "\n|") (org-table-align))
1627 (org-table-next-field))
1628 (if same-column (org-table-goto-column col))))
1630 (defun org-table-clean-line (s)
1631 "Convert a table line S into a string with only \"|\" and space.
1632 In particular, this does handle wide and invisible characters."
1633 (if (string-match "^[ \t]*|-" s)
1634 ;; It's a hline, just map the characters
1635 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
1636 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
1637 (setq s (replace-match
1638 (concat "|" (make-string (org-string-width (match-string 1 s))
1639 ?\ ) "|")
1640 t t s)))
1643 ;;;###autoload
1644 (defun org-table-kill-row ()
1645 "Delete the current row or horizontal line from the table."
1646 (interactive)
1647 (if (not (org-at-table-p))
1648 (user-error "Not at a table"))
1649 (let ((col (current-column))
1650 (dline (org-table-current-dline)))
1651 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1652 (if (not (org-at-table-p)) (beginning-of-line 0))
1653 (org-move-to-column col)
1654 (when (or (not org-table-fix-formulas-confirm)
1655 (funcall org-table-fix-formulas-confirm "Fix formulas? "))
1656 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
1657 dline -1 dline))))
1659 ;;;###autoload
1660 (defun org-table-sort-lines (with-case &optional sorting-type)
1661 "Sort table lines according to the column at point.
1663 The position of point indicates the column to be used for
1664 sorting, and the range of lines is the range between the nearest
1665 horizontal separator lines, or the entire table of no such lines
1666 exist. If point is before the first column, you will be prompted
1667 for the sorting column. If there is an active region, the mark
1668 specifies the first line and the sorting column, while point
1669 should be in the last line to be included into the sorting.
1671 The command then prompts for the sorting type which can be
1672 alphabetically, numerically, or by time (as given in a time stamp
1673 in the field, or as a HH:MM value). Sorting in reverse order is
1674 also possible.
1676 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1678 If SORTING-TYPE is specified when this function is called from a Lisp
1679 program, no prompting will take place. SORTING-TYPE must be a character,
1680 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1681 should be done in reverse order."
1682 (interactive "P")
1683 (let* ((thisline (org-current-line))
1684 (thiscol (org-table-current-column))
1685 (otc org-table-overlay-coordinates)
1686 beg end bcol ecol tend tbeg column lns pos)
1687 (when (equal thiscol 0)
1688 (if (org-called-interactively-p 'any)
1689 (setq thiscol
1690 (string-to-number
1691 (read-string "Use column N for sorting: ")))
1692 (setq thiscol 1))
1693 (org-table-goto-column thiscol))
1694 (org-table-check-inside-data-field)
1695 (if (org-region-active-p)
1696 (progn
1697 (setq beg (region-beginning) end (region-end))
1698 (goto-char beg)
1699 (setq column (org-table-current-column)
1700 beg (point-at-bol))
1701 (goto-char end)
1702 (setq end (point-at-bol 2)))
1703 (setq column (org-table-current-column)
1704 pos (point)
1705 tbeg (org-table-begin)
1706 tend (org-table-end))
1707 (if (re-search-backward org-table-hline-regexp tbeg t)
1708 (setq beg (point-at-bol 2))
1709 (goto-char tbeg)
1710 (setq beg (point-at-bol 1)))
1711 (goto-char pos)
1712 (if (re-search-forward org-table-hline-regexp tend t)
1713 (setq end (point-at-bol 1))
1714 (goto-char tend)
1715 (setq end (point-at-bol))))
1716 (setq beg (move-marker (make-marker) beg)
1717 end (move-marker (make-marker) end))
1718 (untabify beg end)
1719 (goto-char beg)
1720 (org-table-goto-column column)
1721 (skip-chars-backward "^|")
1722 (setq bcol (current-column))
1723 (org-table-goto-column (1+ column))
1724 (skip-chars-backward "^|")
1725 (setq ecol (1- (current-column)))
1726 (org-table-goto-column column)
1727 (setq lns (mapcar (lambda(x) (cons
1728 (org-sort-remove-invisible
1729 (nth (1- column)
1730 (org-split-string x "[ \t]*|[ \t]*")))
1732 (org-split-string (buffer-substring beg end) "\n")))
1733 (setq lns (org-do-sort lns "Table" with-case sorting-type))
1734 (when org-table-overlay-coordinates
1735 (org-table-toggle-coordinate-overlays))
1736 (delete-region beg end)
1737 (move-marker beg nil)
1738 (move-marker end nil)
1739 (insert (mapconcat 'cdr lns "\n") "\n")
1740 (org-goto-line thisline)
1741 (org-table-goto-column thiscol)
1742 (when otc (org-table-toggle-coordinate-overlays))
1743 (message "%d lines sorted, based on column %d" (length lns) column)))
1745 ;;;###autoload
1746 (defun org-table-cut-region (beg end)
1747 "Copy region in table to the clipboard and blank all relevant fields.
1748 If there is no active region, use just the field at point."
1749 (interactive (list
1750 (if (org-region-active-p) (region-beginning) (point))
1751 (if (org-region-active-p) (region-end) (point))))
1752 (org-table-copy-region beg end 'cut))
1754 ;;;###autoload
1755 (defun org-table-copy-region (beg end &optional cut)
1756 "Copy rectangular region in table to clipboard.
1757 A special clipboard is used which can only be accessed
1758 with `org-table-paste-rectangle'."
1759 (interactive (list
1760 (if (org-region-active-p) (region-beginning) (point))
1761 (if (org-region-active-p) (region-end) (point))
1762 current-prefix-arg))
1763 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1764 region cols
1765 (rpl (if cut " " nil)))
1766 (goto-char beg)
1767 (org-table-check-inside-data-field)
1768 (setq l01 (org-current-line)
1769 c01 (org-table-current-column))
1770 (goto-char end)
1771 (org-table-check-inside-data-field)
1772 (setq l02 (org-current-line)
1773 c02 (org-table-current-column))
1774 (setq l1 (min l01 l02) l2 (max l01 l02)
1775 c1 (min c01 c02) c2 (max c01 c02))
1776 (catch 'exit
1777 (while t
1778 (catch 'nextline
1779 (if (> l1 l2) (throw 'exit t))
1780 (org-goto-line l1)
1781 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
1782 (setq cols nil ic1 c1 ic2 c2)
1783 (while (< ic1 (1+ ic2))
1784 (push (org-table-get-field ic1 rpl) cols)
1785 (setq ic1 (1+ ic1)))
1786 (push (nreverse cols) region)
1787 (setq l1 (1+ l1)))))
1788 (setq org-table-clip (nreverse region))
1789 (if cut (org-table-align))
1790 org-table-clip))
1792 ;;;###autoload
1793 (defun org-table-paste-rectangle ()
1794 "Paste a rectangular region into a table.
1795 The upper right corner ends up in the current field. All involved fields
1796 will be overwritten. If the rectangle does not fit into the present table,
1797 the table is enlarged as needed. The process ignores horizontal separator
1798 lines."
1799 (interactive)
1800 (unless (and org-table-clip (listp org-table-clip))
1801 (user-error "First cut/copy a region to paste!"))
1802 (org-table-check-inside-data-field)
1803 (let* ((clip org-table-clip)
1804 (line (org-current-line))
1805 (col (org-table-current-column))
1806 (org-enable-table-editor t)
1807 (org-table-automatic-realign nil)
1808 c cols field)
1809 (while (setq cols (pop clip))
1810 (while (org-at-table-hline-p) (beginning-of-line 2))
1811 (if (not (org-at-table-p))
1812 (progn (end-of-line 0) (org-table-next-field)))
1813 (setq c col)
1814 (while (setq field (pop cols))
1815 (org-table-goto-column c nil 'force)
1816 (org-table-get-field nil field)
1817 (setq c (1+ c)))
1818 (beginning-of-line 2))
1819 (org-goto-line line)
1820 (org-table-goto-column col)
1821 (org-table-align)))
1823 ;;;###autoload
1824 (defun org-table-convert ()
1825 "Convert from `org-mode' table to table.el and back.
1826 Obviously, this only works within limits. When an Org-mode table is
1827 converted to table.el, all horizontal separator lines get lost, because
1828 table.el uses these as cell boundaries and has no notion of horizontal lines.
1829 A table.el table can be converted to an Org-mode table only if it does not
1830 do row or column spanning. Multiline cells will become multiple cells.
1831 Beware, Org-mode does not test if the table can be successfully converted - it
1832 blindly applies a recipe that works for simple tables."
1833 (interactive)
1834 (require 'table)
1835 (if (org-at-table.el-p)
1836 ;; convert to Org-mode table
1837 (let ((beg (move-marker (make-marker) (org-table-begin t)))
1838 (end (move-marker (make-marker) (org-table-end t))))
1839 (table-unrecognize-region beg end)
1840 (goto-char beg)
1841 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
1842 (replace-match ""))
1843 (goto-char beg))
1844 (if (org-at-table-p)
1845 ;; convert to table.el table
1846 (let ((beg (move-marker (make-marker) (org-table-begin)))
1847 (end (move-marker (make-marker) (org-table-end))))
1848 ;; first, get rid of all horizontal lines
1849 (goto-char beg)
1850 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
1851 (replace-match ""))
1852 ;; insert a hline before first
1853 (goto-char beg)
1854 (org-table-insert-hline 'above)
1855 (beginning-of-line -1)
1856 ;; insert a hline after each line
1857 (while (progn (beginning-of-line 3) (< (point) end))
1858 (org-table-insert-hline))
1859 (goto-char beg)
1860 (setq end (move-marker end (org-table-end)))
1861 ;; replace "+" at beginning and ending of hlines
1862 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
1863 (replace-match "\\1+-"))
1864 (goto-char beg)
1865 (while (re-search-forward "-|[ \t]*$" end t)
1866 (replace-match "-+"))
1867 (goto-char beg)))))
1869 (defun org-table-transpose-table-at-point ()
1870 "Transpose Org table at point and eliminate hlines.
1871 So a table like
1873 | 1 | 2 | 4 | 5 |
1874 |---+---+---+---|
1875 | a | b | c | d |
1876 | e | f | g | h |
1878 will be transposed as
1880 | 1 | a | e |
1881 | 2 | b | f |
1882 | 4 | c | g |
1883 | 5 | d | h |
1885 Note that horizontal lines disappear."
1886 (interactive)
1887 (let* ((table (delete 'hline (org-table-to-lisp)))
1888 (dline_old (org-table-current-line))
1889 (col_old (org-table-current-column))
1890 (contents (mapcar (lambda (p)
1891 (let ((tp table))
1892 (mapcar
1893 (lambda (rown)
1894 (prog1
1895 (pop (car tp))
1896 (setq tp (cdr tp))))
1897 table)))
1898 (car table))))
1899 (goto-char (org-table-begin))
1900 (re-search-forward "|")
1901 (backward-char)
1902 (delete-region (point) (org-table-end))
1903 (insert (mapconcat
1904 (lambda(x)
1905 (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
1906 contents ""))
1907 (org-table-goto-line col_old)
1908 (org-table-goto-column dline_old))
1909 (org-table-align))
1911 ;;;###autoload
1912 (defun org-table-wrap-region (arg)
1913 "Wrap several fields in a column like a paragraph.
1914 This is useful if you'd like to spread the contents of a field over several
1915 lines, in order to keep the table compact.
1917 If there is an active region, and both point and mark are in the same column,
1918 the text in the column is wrapped to minimum width for the given number of
1919 lines. Generally, this makes the table more compact. A prefix ARG may be
1920 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1921 formats the selected text to two lines. If the region was longer than two
1922 lines, the remaining lines remain empty. A negative prefix argument reduces
1923 the current number of lines by that amount. The wrapped text is pasted back
1924 into the table. If you formatted it to more lines than it was before, fields
1925 further down in the table get overwritten - so you might need to make space in
1926 the table first.
1928 If there is no region, the current field is split at the cursor position and
1929 the text fragment to the right of the cursor is prepended to the field one
1930 line down.
1932 If there is no region, but you specify a prefix ARG, the current field gets
1933 blank, and the content is appended to the field above."
1934 (interactive "P")
1935 (org-table-check-inside-data-field)
1936 (if (org-region-active-p)
1937 ;; There is a region: fill as a paragraph
1938 (let* ((beg (region-beginning))
1939 (cline (save-excursion (goto-char beg) (org-current-line)))
1940 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
1941 nlines)
1942 (org-table-cut-region (region-beginning) (region-end))
1943 (if (> (length (car org-table-clip)) 1)
1944 (user-error "Region must be limited to single column"))
1945 (setq nlines (if arg
1946 (if (< arg 1)
1947 (+ (length org-table-clip) arg)
1948 arg)
1949 (length org-table-clip)))
1950 (setq org-table-clip
1951 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
1952 nil nlines)))
1953 (org-goto-line cline)
1954 (org-table-goto-column ccol)
1955 (org-table-paste-rectangle))
1956 ;; No region, split the current field at point
1957 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
1958 (skip-chars-forward "^\r\n|"))
1959 (if arg
1960 ;; combine with field above
1961 (let ((s (org-table-blank-field))
1962 (col (org-table-current-column)))
1963 (beginning-of-line 0)
1964 (while (org-at-table-hline-p) (beginning-of-line 0))
1965 (org-table-goto-column col)
1966 (skip-chars-forward "^|")
1967 (skip-chars-backward " ")
1968 (insert " " (org-trim s))
1969 (org-table-align))
1970 ;; split field
1971 (if (looking-at "\\([^|]+\\)+|")
1972 (let ((s (match-string 1)))
1973 (replace-match " |")
1974 (goto-char (match-beginning 0))
1975 (org-table-next-row)
1976 (insert (org-trim s) " ")
1977 (org-table-align))
1978 (org-table-next-row)))))
1980 (defvar org-field-marker nil)
1982 ;;;###autoload
1983 (defun org-table-edit-field (arg)
1984 "Edit table field in a different window.
1985 This is mainly useful for fields that contain hidden parts.
1986 When called with a \\[universal-argument] prefix, just make the full field visible so that
1987 it can be edited in place."
1988 (interactive "P")
1989 (cond
1990 ((equal arg '(16))
1991 (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
1992 (arg
1993 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1994 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1995 (remove-text-properties b e '(org-cwidth t invisible t
1996 display t intangible t))
1997 (if (and (boundp 'font-lock-mode) font-lock-mode)
1998 (font-lock-fontify-block))))
2000 (let ((pos (point-marker))
2001 (coord
2002 (if (eq org-table-use-standard-references t)
2003 (concat (org-number-to-letters (org-table-current-column))
2004 (int-to-string (org-table-current-dline)))
2005 (concat "@" (int-to-string (org-table-current-dline))
2006 "$" (int-to-string (org-table-current-column)))))
2007 (field (org-table-get-field))
2008 (cw (current-window-configuration))
2010 (goto-char pos)
2011 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2012 (when (and (local-variable-p 'org-field-marker)
2013 (markerp org-field-marker))
2014 (move-marker org-field-marker nil))
2015 (erase-buffer)
2016 (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n")
2017 (let ((org-inhibit-startup t)) (org-mode))
2018 (auto-fill-mode -1)
2019 (setq truncate-lines nil)
2020 (setq word-wrap t)
2021 (goto-char (setq p (point-max)))
2022 (insert (org-trim field))
2023 (remove-text-properties p (point-max)
2024 '(invisible t org-cwidth t display t
2025 intangible t))
2026 (goto-char p)
2027 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
2028 (org-set-local 'org-window-configuration cw)
2029 (org-set-local 'org-field-marker pos)
2030 (message "Edit and finish with C-c C-c")))))
2032 (defun org-table-finish-edit-field ()
2033 "Finish editing a table data field.
2034 Remove all newline characters, insert the result into the table, realign
2035 the table and kill the editing buffer."
2036 (let ((pos org-field-marker)
2037 (cw org-window-configuration)
2038 (cb (current-buffer))
2039 text)
2040 (goto-char (point-min))
2041 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
2042 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
2043 (replace-match " "))
2044 (setq text (org-trim (buffer-string)))
2045 (set-window-configuration cw)
2046 (kill-buffer cb)
2047 (select-window (get-buffer-window (marker-buffer pos)))
2048 (goto-char pos)
2049 (move-marker pos nil)
2050 (org-table-check-inside-data-field)
2051 (org-table-get-field nil text)
2052 (org-table-align)
2053 (message "New field value inserted")))
2055 (define-minor-mode org-table-follow-field-mode
2056 "Minor mode to make the table field editor window follow the cursor.
2057 When this mode is active, the field editor window will always show the
2058 current field. The mode exits automatically when the cursor leaves the
2059 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2060 nil " TblFollow" nil
2061 (if org-table-follow-field-mode
2062 (org-add-hook 'post-command-hook 'org-table-follow-fields-with-editor
2063 'append 'local)
2064 (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
2065 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2066 (win (and buf (get-buffer-window buf))))
2067 (when win (delete-window win))
2068 (when buf
2069 (with-current-buffer buf
2070 (move-marker org-field-marker nil))
2071 (kill-buffer buf)))))
2073 (defun org-table-follow-fields-with-editor ()
2074 (if (and org-table-exit-follow-field-mode-when-leaving-table
2075 (not (org-at-table-p)))
2076 ;; We have left the table, exit the follow mode
2077 (org-table-follow-field-mode -1)
2078 (when (org-table-check-inside-data-field 'noerror)
2079 (let ((win (selected-window)))
2080 (org-table-edit-field nil)
2081 (org-fit-window-to-buffer)
2082 (select-window win)))))
2084 (defvar org-timecnt) ; dynamically scoped parameter
2086 ;;;###autoload
2087 (defun org-table-sum (&optional beg end nlast)
2088 "Sum numbers in region of current table column.
2089 The result will be displayed in the echo area, and will be available
2090 as kill to be inserted with \\[yank].
2092 If there is an active region, it is interpreted as a rectangle and all
2093 numbers in that rectangle will be summed. If there is no active
2094 region and point is located in a table column, sum all numbers in that
2095 column.
2097 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2098 numbers are assumed to be times as well (in decimal hours) and the
2099 numbers are added as such.
2101 If NLAST is a number, only the NLAST fields will actually be summed."
2102 (interactive)
2103 (save-excursion
2104 (let (col (org-timecnt 0) diff h m s org-table-clip)
2105 (cond
2106 ((and beg end)) ; beg and end given explicitly
2107 ((org-region-active-p)
2108 (setq beg (region-beginning) end (region-end)))
2110 (setq col (org-table-current-column))
2111 (goto-char (org-table-begin))
2112 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
2113 (user-error "No table data"))
2114 (org-table-goto-column col)
2115 (setq beg (point))
2116 (goto-char (org-table-end))
2117 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
2118 (user-error "No table data"))
2119 (org-table-goto-column col)
2120 (setq end (point))))
2121 (let* ((items (apply 'append (org-table-copy-region beg end)))
2122 (items1 (cond ((not nlast) items)
2123 ((>= nlast (length items)) items)
2124 (t (setq items (reverse items))
2125 (setcdr (nthcdr (1- nlast) items) nil)
2126 (nreverse items))))
2127 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
2128 items1)))
2129 (res (apply '+ numbers))
2130 (sres (if (= org-timecnt 0)
2131 (number-to-string res)
2132 (setq diff (* 3600 res)
2133 h (floor (/ diff 3600)) diff (mod diff 3600)
2134 m (floor (/ diff 60)) diff (mod diff 60)
2135 s diff)
2136 (format "%.0f:%02.0f:%02.0f" h m s))))
2137 (kill-new sres)
2138 (if (org-called-interactively-p 'interactive)
2139 (message "%s"
2140 (substitute-command-keys
2141 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2142 (length numbers) sres))))
2143 sres))))
2145 (defun org-table-get-number-for-summing (s)
2146 (let (n)
2147 (if (string-match "^ *|? *" s)
2148 (setq s (replace-match "" nil nil s)))
2149 (if (string-match " *|? *$" s)
2150 (setq s (replace-match "" nil nil s)))
2151 (setq n (string-to-number s))
2152 (cond
2153 ((and (string-match "0" s)
2154 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
2155 ((string-match "\\`[ \t]+\\'" s) nil)
2156 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
2157 (let ((h (string-to-number (or (match-string 1 s) "0")))
2158 (m (string-to-number (or (match-string 2 s) "0")))
2159 (s (string-to-number (or (match-string 4 s) "0"))))
2160 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
2161 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
2162 ((equal n 0) nil)
2163 (t n))))
2165 (defun org-table-current-field-formula (&optional key noerror)
2166 "Return the formula active for the current field.
2167 Assumes that specials are in place.
2168 If KEY is given, return the key to this formula.
2169 Otherwise return the formula preceded with \"=\" or \":=\"."
2170 (let* ((name (car (rassoc (list (org-current-line)
2171 (org-table-current-column))
2172 org-table-named-field-locations)))
2173 (col (org-table-current-column))
2174 (scol (int-to-string col))
2175 (ref (format "@%d$%d" (org-table-current-dline) col))
2176 (stored-list (org-table-get-stored-formulas noerror))
2177 (ass (or (assoc name stored-list)
2178 (assoc ref stored-list)
2179 (assoc scol stored-list))))
2180 (if key
2181 (car ass)
2182 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
2183 (cdr ass))))))
2185 (defun org-table-get-formula (&optional equation named)
2186 "Read a formula from the minibuffer, offer stored formula as default.
2187 When NAMED is non-nil, look for a named equation."
2188 (let* ((stored-list (org-table-get-stored-formulas))
2189 (name (car (rassoc (list (org-current-line)
2190 (org-table-current-column))
2191 org-table-named-field-locations)))
2192 (ref (format "@%d$%d" (org-table-current-dline)
2193 (org-table-current-column)))
2194 (refass (assoc ref stored-list))
2195 (nameass (assoc name stored-list))
2196 (scol (if named
2197 (if (and name (not (string-match "^LR[0-9]+$" name)))
2198 name
2199 ref)
2200 (int-to-string (org-table-current-column))))
2201 (dummy (and (or nameass refass) (not named)
2202 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2203 (message "Formula not replaced")))
2204 (name (or name ref))
2205 (org-table-may-need-update nil)
2206 (stored (cdr (assoc scol stored-list)))
2207 (eq (cond
2208 ((and stored equation (string-match "^ *=? *$" equation))
2209 stored)
2210 ((stringp equation)
2211 equation)
2212 (t (org-table-formula-from-user
2213 (read-string
2214 (org-table-formula-to-user
2215 (format "%s formula %s%s="
2216 (if named "Field" "Column")
2217 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
2218 scol))
2219 (if stored (org-table-formula-to-user stored) "")
2220 'org-table-formula-history
2221 )))))
2222 mustsave)
2223 (when (not (string-match "\\S-" eq))
2224 ;; remove formula
2225 (setq stored-list (delq (assoc scol stored-list) stored-list))
2226 (org-table-store-formulas stored-list)
2227 (user-error "Formula removed"))
2228 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
2229 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
2230 (if (and name (not named))
2231 ;; We set the column equation, delete the named one.
2232 (setq stored-list (delq (assoc name stored-list) stored-list)
2233 mustsave t))
2234 (if stored
2235 (setcdr (assoc scol stored-list) eq)
2236 (setq stored-list (cons (cons scol eq) stored-list)))
2237 (if (or mustsave (not (equal stored eq)))
2238 (org-table-store-formulas stored-list))
2239 eq))
2241 (defun org-table-store-formulas (alist)
2242 "Store the list of formulas below the current table."
2243 (setq alist (sort alist 'org-table-formula-less-p))
2244 (let ((case-fold-search t))
2245 (save-excursion
2246 (goto-char (org-table-end))
2247 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2248 (progn
2249 ;; don't overwrite TBLFM, we might use text properties to store stuff
2250 (goto-char (match-beginning 3))
2251 (delete-region (match-beginning 3) (match-end 0)))
2252 (org-indent-line)
2253 (insert (or (match-string 2) "#+TBLFM:")))
2254 (insert " "
2255 (mapconcat (lambda (x)
2256 (concat
2257 (if (equal (string-to-char (car x)) ?@) "" "$")
2258 (car x) "=" (cdr x)))
2259 alist "::")
2260 "\n"))))
2262 (defsubst org-table-formula-make-cmp-string (a)
2263 (when (string-match "\\`$[<>]" a)
2264 (let ((arrow (string-to-char (substring a 1))))
2265 ;; Fake a high number to make sure this is sorted at the end.
2266 (setq a (org-table-formula-handle-first/last-rc a))
2267 (setq a (format "$%d" (+ 10000
2268 (if (= arrow ?<) -1000 0)
2269 (string-to-number (substring a 1)))))))
2270 (when (string-match
2271 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2273 (concat
2274 (if (match-end 2)
2275 (format "@%05d" (string-to-number (match-string 2 a))) "")
2276 (if (match-end 4)
2277 (format "$%05d" (string-to-number (match-string 4 a))) "")
2278 (if (match-end 5)
2279 (concat "@@" (match-string 5 a))))))
2281 (defun org-table-formula-less-p (a b)
2282 "Compare two formulas for sorting."
2283 (let ((as (org-table-formula-make-cmp-string (car a)))
2284 (bs (org-table-formula-make-cmp-string (car b))))
2285 (and as bs (string< as bs))))
2287 ;;;###autoload
2288 (defun org-table-get-stored-formulas (&optional noerror)
2289 "Return an alist with the stored formulas directly after current table."
2290 (interactive) ;; FIXME interactive?
2291 (let ((case-fold-search t) scol eq eq-alist strings string seen)
2292 (save-excursion
2293 (goto-char (org-table-end))
2294 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2295 (setq strings (org-split-string (org-match-string-no-properties 2)
2296 " *:: *"))
2297 (while (setq string (pop strings))
2298 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string)
2299 (setq scol (if (match-end 2)
2300 (match-string 2 string)
2301 (match-string 1 string))
2302 scol (if (member (string-to-char scol) '(?< ?>))
2303 (concat "$" scol) scol)
2304 eq (match-string 3 string)
2305 eq-alist (cons (cons scol eq) eq-alist))
2306 (if (member scol seen)
2307 (if noerror
2308 (progn
2309 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
2310 (ding)
2311 (sit-for 2))
2312 (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
2313 (push scol seen))))))
2314 (nreverse eq-alist)))
2316 (defun org-table-fix-formulas (key replace &optional limit delta remove)
2317 "Modify the equations after the table structure has been edited.
2318 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2319 For all numbers larger than LIMIT, shift them by DELTA."
2320 (save-excursion
2321 (goto-char (org-table-end))
2322 (while (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
2323 (let ((msg "The formulas in #+TBLFM have been updated")
2324 (re (concat key "\\([0-9]+\\)"))
2325 (re2
2326 (when remove
2327 (if (or (equal key "$") (equal key "$LR"))
2328 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2329 (regexp-quote key) remove)
2330 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
2331 s n a)
2332 (when remove
2333 (while (re-search-forward re2 (point-at-eol) t)
2334 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2335 (if (equal (char-before (match-beginning 0)) ?.)
2336 (user-error
2337 "Change makes TBLFM term %s invalid, use undo to recover"
2338 (match-string 0))
2339 (replace-match "")))))
2340 (while (re-search-forward re (point-at-eol) t)
2341 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2342 (setq s (match-string 1) n (string-to-number s))
2343 (cond
2344 ((setq a (assoc s replace))
2345 (replace-match (concat key (cdr a)) t t)
2346 (message msg))
2347 ((and limit (> n limit))
2348 (replace-match (concat key (int-to-string (+ n delta))) t t)
2349 (message msg))))))
2350 (forward-line))))
2352 (defun org-table-get-specials ()
2353 "Get the column names and local parameters for this table."
2354 (save-excursion
2355 (let ((beg (org-table-begin)) (end (org-table-end))
2356 names name fields fields1 field cnt
2357 c v l line col types dlines hlines last-dline)
2358 (setq org-table-column-names nil
2359 org-table-local-parameters nil
2360 org-table-named-field-locations nil
2361 org-table-current-begin-line nil
2362 org-table-current-begin-pos nil
2363 org-table-current-line-types nil
2364 org-table-current-ncol 0)
2365 (goto-char beg)
2366 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
2367 (setq names (org-split-string (match-string 1) " *| *")
2368 cnt 1)
2369 (while (setq name (pop names))
2370 (setq cnt (1+ cnt))
2371 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name)
2372 (push (cons name (int-to-string cnt)) org-table-column-names))))
2373 (setq org-table-column-names (nreverse org-table-column-names))
2374 (setq org-table-column-name-regexp
2375 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
2376 (goto-char beg)
2377 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
2378 (setq fields (org-split-string (match-string 1) " *| *"))
2379 (while (setq field (pop fields))
2380 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
2381 (push (cons (match-string 1 field) (match-string 2 field))
2382 org-table-local-parameters))))
2383 (goto-char beg)
2384 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
2385 (setq c (match-string 1)
2386 fields (org-split-string (match-string 2) " *| *"))
2387 (save-excursion
2388 (beginning-of-line (if (equal c "_") 2 0))
2389 (setq line (org-current-line) col 1)
2390 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2391 (setq fields1 (org-split-string (match-string 1) " *| *"))))
2392 (while (and fields1 (setq field (pop fields)))
2393 (setq v (pop fields1) col (1+ col))
2394 (when (and (stringp field) (stringp v)
2395 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field))
2396 (push (cons field v) org-table-local-parameters)
2397 (push (list field line col) org-table-named-field-locations))))
2398 ;; Analyse the line types
2399 (goto-char beg)
2400 (setq org-table-current-begin-line (org-current-line)
2401 org-table-current-begin-pos (point)
2402 l org-table-current-begin-line)
2403 (while (looking-at "[ \t]*|\\(-\\)?")
2404 (push (if (match-end 1) 'hline 'dline) types)
2405 (if (match-end 1) (push l hlines) (push l dlines))
2406 (beginning-of-line 2)
2407 (setq l (1+ l)))
2408 (push 'hline types) ;; add an imaginary extra hline to the end
2409 (setq org-table-current-line-types (apply 'vector (nreverse types))
2410 last-dline (car dlines)
2411 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
2412 org-table-hlines (apply 'vector (cons nil (nreverse hlines))))
2413 (org-goto-line last-dline)
2414 (let* ((l last-dline)
2415 (fields (org-split-string
2416 (buffer-substring (point-at-bol) (point-at-eol))
2417 "[ \t]*|[ \t]*"))
2418 (nfields (length fields))
2419 al al2)
2420 (setq org-table-current-ncol nfields)
2421 (loop for i from 1 to nfields do
2422 (push (list (format "LR%d" i) l i) al)
2423 (push (cons (format "LR%d" i) (nth (1- i) fields)) al2))
2424 (setq org-table-named-field-locations
2425 (append org-table-named-field-locations al))
2426 (setq org-table-local-parameters
2427 (append org-table-local-parameters al2))))))
2429 ;;;###autoload
2430 (defun org-table-maybe-eval-formula ()
2431 "Check if the current field starts with \"=\" or \":=\".
2432 If yes, store the formula and apply it."
2433 ;; We already know we are in a table. Get field will only return a formula
2434 ;; when appropriate. It might return a separator line, but no problem.
2435 (when org-table-formula-evaluate-inline
2436 (let* ((field (org-trim (or (org-table-get-field) "")))
2437 named eq)
2438 (when (string-match "^:?=\\(.*[^=]\\)$" field)
2439 (setq named (equal (string-to-char field) ?:)
2440 eq (match-string 1 field))
2441 (if (or (fboundp 'calc-eval)
2442 (equal (substring eq 0 (min 2 (length eq))) "'("))
2443 (org-table-eval-formula (if named '(4) nil)
2444 (org-table-formula-from-user eq))
2445 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2447 (defvar org-recalc-commands nil
2448 "List of commands triggering the recalculation of a line.
2449 Will be filled automatically during use.")
2451 (defvar org-recalc-marks
2452 '((" " . "Unmarked: no special line, no automatic recalculation")
2453 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2454 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
2455 ("!" . "Column name definition line. Reference in formula as $name.")
2456 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
2457 ("_" . "Names for values in row below this one.")
2458 ("^" . "Names for values in row above this one.")))
2460 ;;;###autoload
2461 (defun org-table-rotate-recalc-marks (&optional newchar)
2462 "Rotate the recalculation mark in the first column.
2463 If in any row, the first field is not consistent with a mark,
2464 insert a new column for the markers.
2465 When there is an active region, change all the lines in the region,
2466 after prompting for the marking character.
2467 After each change, a message will be displayed indicating the meaning
2468 of the new mark."
2469 (interactive)
2470 (unless (org-at-table-p) (user-error "Not at a table"))
2471 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
2472 (beg (org-table-begin))
2473 (end (org-table-end))
2474 (l (org-current-line))
2475 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2476 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2477 (have-col
2478 (save-excursion
2479 (goto-char beg)
2480 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
2481 (col (org-table-current-column))
2482 (forcenew (car (assoc newchar org-recalc-marks)))
2483 epos new)
2484 (when l1
2485 (message "Change region to what mark? Type # * ! $ or SPC: ")
2486 (setq newchar (char-to-string (read-char-exclusive))
2487 forcenew (car (assoc newchar org-recalc-marks))))
2488 (if (and newchar (not forcenew))
2489 (user-error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2490 newchar))
2491 (if l1 (org-goto-line l1))
2492 (save-excursion
2493 (beginning-of-line 1)
2494 (unless (looking-at org-table-dataline-regexp)
2495 (user-error "Not at a table data line")))
2496 (unless have-col
2497 (org-table-goto-column 1)
2498 (org-table-insert-column)
2499 (org-table-goto-column (1+ col)))
2500 (setq epos (point-at-eol))
2501 (save-excursion
2502 (beginning-of-line 1)
2503 (org-table-get-field
2504 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2505 (concat " "
2506 (setq new (or forcenew
2507 (cadr (member (match-string 1) marks))))
2508 " ")
2509 " # ")))
2510 (if (and l1 l2)
2511 (progn
2512 (org-goto-line l1)
2513 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
2514 (and (looking-at org-table-dataline-regexp)
2515 (org-table-get-field 1 (concat " " new " "))))
2516 (org-goto-line l1)))
2517 (if (not (= epos (point-at-eol))) (org-table-align))
2518 (org-goto-line l)
2519 (and (org-called-interactively-p 'interactive)
2520 (message "%s" (cdr (assoc new org-recalc-marks))))))
2522 ;;;###autoload
2523 (defun org-table-maybe-recalculate-line ()
2524 "Recompute the current line if marked for it, and if we haven't just done it."
2525 (interactive)
2526 (and org-table-allow-automatic-line-recalculation
2527 (not (and (memq last-command org-recalc-commands)
2528 (equal org-last-recalc-line (org-current-line))))
2529 (save-excursion (beginning-of-line 1)
2530 (looking-at org-table-auto-recalculate-regexp))
2531 (org-table-recalculate) t))
2533 (defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
2534 (defsubst org-set-calc-mode (var &optional value)
2535 (if (stringp var)
2536 (setq var (assoc var '(("D" calc-angle-mode deg)
2537 ("R" calc-angle-mode rad)
2538 ("F" calc-prefer-frac t)
2539 ("S" calc-symbolic-mode t)))
2540 value (nth 2 var) var (nth 1 var)))
2541 (if (memq var org-tbl-calc-modes)
2542 (setcar (cdr (memq var org-tbl-calc-modes)) value)
2543 (cons var (cons value org-tbl-calc-modes)))
2544 org-tbl-calc-modes)
2546 ;;;###autoload
2547 (defun org-table-eval-formula (&optional arg equation
2548 suppress-align suppress-const
2549 suppress-store suppress-analysis)
2550 "Replace the table field value at the cursor by the result of a calculation.
2552 This function makes use of Dave Gillespie's Calc package, in my view the
2553 most exciting program ever written for GNU Emacs. So you need to have Calc
2554 installed in order to use this function.
2556 In a table, this command replaces the value in the current field with the
2557 result of a formula. It also installs the formula as the \"current\" column
2558 formula, by storing it in a special line below the table. When called
2559 with a `C-u' prefix, the current field must be a named field, and the
2560 formula is installed as valid in only this specific field.
2562 When called with two `C-u' prefixes, insert the active equation
2563 for the field back into the current field, so that it can be
2564 edited there. This is useful in order to use \\[org-table-show-reference]
2565 to check the referenced fields.
2567 When called, the command first prompts for a formula, which is read in
2568 the minibuffer. Previously entered formulas are available through the
2569 history list, and the last used formula is offered as a default.
2570 These stored formulas are adapted correctly when moving, inserting, or
2571 deleting columns with the corresponding commands.
2573 The formula can be any algebraic expression understood by the Calc package.
2574 For details, see the Org-mode manual.
2576 This function can also be called from Lisp programs and offers
2577 additional arguments: EQUATION can be the formula to apply. If this
2578 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2579 used to speed-up recursive calls by by-passing unnecessary aligns.
2580 SUPPRESS-CONST suppresses the interpretation of constants in the
2581 formula, assuming that this has been done already outside the function.
2582 SUPPRESS-STORE means the formula should not be stored, either because
2583 it is already stored, or because it is a modified equation that should
2584 not overwrite the stored one."
2585 (interactive "P")
2586 (org-table-check-inside-data-field)
2587 (or suppress-analysis (org-table-get-specials))
2588 (if (equal arg '(16))
2589 (let ((eq (org-table-current-field-formula)))
2590 (or eq (user-error "No equation active for current field"))
2591 (org-table-get-field nil eq)
2592 (org-table-align)
2593 (setq org-table-may-need-update t))
2594 (let* (fields
2595 (ndown (if (integerp arg) arg 1))
2596 (org-table-automatic-realign nil)
2597 (case-fold-search nil)
2598 (down (> ndown 1))
2599 (formula (if (and equation suppress-store)
2600 equation
2601 (org-table-get-formula equation (equal arg '(4)))))
2602 (n0 (org-table-current-column))
2603 (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
2604 (numbers nil) ; was a variable, now fixed default
2605 (keep-empty nil)
2606 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2607 duration duration-output-format)
2608 ;; Parse the format string. Since we have a lot of modes, this is
2609 ;; a lot of work. However, I think calc still uses most of the time.
2610 (if (string-match ";" formula)
2611 (let ((tmp (org-split-string formula ";")))
2612 (setq formula (car tmp)
2613 fmt (concat (cdr (assoc "%" org-table-local-parameters))
2614 (nth 1 tmp)))
2615 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
2616 (setq c (string-to-char (match-string 1 fmt))
2617 n (string-to-number (match-string 2 fmt)))
2618 (if (= c ?p)
2619 (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
2620 (setq org-tbl-calc-modes
2621 (org-set-calc-mode
2622 'calc-float-format
2623 (list (cdr (assoc c '((?n . float) (?f . fix)
2624 (?s . sci) (?e . eng))))
2625 n))))
2626 (setq fmt (replace-match "" t t fmt)))
2627 (if (string-match "T" fmt)
2628 (setq duration t numbers t
2629 duration-output-format nil
2630 fmt (replace-match "" t t fmt)))
2631 (if (string-match "t" fmt)
2632 (setq duration t
2633 duration-output-format org-table-duration-custom-format
2634 numbers t
2635 fmt (replace-match "" t t fmt)))
2636 (if (string-match "N" fmt)
2637 (setq numbers t
2638 fmt (replace-match "" t t fmt)))
2639 (if (string-match "L" fmt)
2640 (setq literal t
2641 fmt (replace-match "" t t fmt)))
2642 (if (string-match "E" fmt)
2643 (setq keep-empty t
2644 fmt (replace-match "" t t fmt)))
2645 (while (string-match "[DRFS]" fmt)
2646 (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
2647 (setq fmt (replace-match "" t t fmt)))
2648 (unless (string-match "\\S-" fmt)
2649 (setq fmt nil))))
2650 (if (and (not suppress-const) org-table-formula-use-constants)
2651 (setq formula (org-table-formula-substitute-names formula)))
2652 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
2653 (while (> ndown 0)
2654 (setq fields (org-split-string
2655 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2656 " *| *"))
2657 ;; replace fields with duration values if relevant
2658 (if duration
2659 (setq fields
2660 (mapcar (lambda (x) (org-table-time-string-to-seconds x))
2661 fields)))
2662 (if (eq numbers t)
2663 (setq fields (mapcar
2664 (lambda (x)
2665 (if (string-match "\\S-" x)
2666 (number-to-string (string-to-number x))
2668 fields)))
2669 (setq ndown (1- ndown))
2670 (setq form (copy-sequence formula)
2671 lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
2672 (if (and lispp literal) (setq lispp 'literal))
2674 ;; Insert row and column number of formula result field
2675 (while (string-match "[@$]#" form)
2676 (setq form
2677 (replace-match
2678 (format "%d"
2679 (save-match-data
2680 (if (equal (substring form (match-beginning 0)
2681 (1+ (match-beginning 0)))
2682 "@")
2683 (org-table-current-dline)
2684 (org-table-current-column))))
2685 t t form)))
2687 ;; Check for old vertical references
2688 (org-table--error-on-old-row-references form)
2689 ;; Insert remote references
2690 (setq form (org-table-remote-reference-indirection form))
2691 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
2692 (setq form
2693 (replace-match
2694 (save-match-data
2695 (org-table-make-reference
2696 (let ((rmtrng (org-table-get-remote-range
2697 (match-string 1 form) (match-string 2 form))))
2698 (if duration
2699 (if (listp rmtrng)
2700 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
2701 (org-table-time-string-to-seconds rmtrng))
2702 rmtrng))
2703 keep-empty numbers lispp))
2704 t t form)))
2705 ;; Insert complex ranges
2706 (while (and (string-match org-table-range-regexp form)
2707 (> (length (match-string 0 form)) 1))
2708 (setq formrg (save-match-data
2709 (org-table-get-range (match-string 0 form) nil n0)))
2710 (setq formrpl
2711 (save-match-data
2712 (org-table-make-reference
2713 ;; possibly handle durations
2714 (if duration
2715 (if (listp formrg)
2716 (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
2717 (org-table-time-string-to-seconds formrg))
2718 formrg)
2719 keep-empty numbers lispp)))
2720 (if (not (save-match-data
2721 (string-match (regexp-quote form) formrpl)))
2722 (setq form (replace-match formrpl t t form))
2723 (user-error "Spreadsheet error: invalid reference \"%s\"" form)))
2724 ;; Insert simple ranges
2725 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
2726 (setq form
2727 (replace-match
2728 (save-match-data
2729 (org-table-make-reference
2730 (org-sublist
2731 fields (string-to-number (match-string 1 form))
2732 (string-to-number (match-string 2 form)))
2733 keep-empty numbers lispp))
2734 t t form)))
2735 (setq form0 form)
2736 ;; Insert the references to fields in same row
2737 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
2738 (setq n (+ (string-to-number (match-string 1 form))
2739 (if (match-end 2) n0 0))
2740 x (nth (1- (if (= n 0) n0 (max n 1))) fields)
2741 formrpl (save-match-data
2742 (org-table-make-reference
2743 x keep-empty numbers lispp)))
2744 (when (or (not x)
2745 (save-match-data
2746 (string-match (regexp-quote formula) formrpl)))
2747 (user-error "Invalid field specifier \"%s\""
2748 (match-string 0 form)))
2749 (setq form (replace-match formrpl t t form)))
2751 (if lispp
2752 (setq ev (condition-case nil
2753 (eval (eval (read form)))
2754 (error "#ERROR"))
2755 ev (if (numberp ev) (number-to-string ev) ev)
2756 ev (if duration (org-table-time-seconds-to-string
2757 (string-to-number ev)
2758 duration-output-format) ev))
2759 (or (fboundp 'calc-eval)
2760 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2761 ;; Use <...> time-stamps so that Calc can handle them
2762 (while (string-match (concat "\\[" org-ts-regexp1 "\\]") form)
2763 (setq form (replace-match "<\\1>" nil nil form)))
2764 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2765 (when (string-match org-ts-regexp2 form)
2766 (let* ((ts (match-string 0 form))
2767 (tsp (apply 'encode-time (save-match-data (org-parse-time-string ts))))
2768 (system-time-locale "C")
2769 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
2770 (cdr org-time-stamp-formats))
2771 (car org-time-stamp-formats))))
2772 (setq form (replace-match (format-time-string tf tsp) t t form))))
2774 (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
2775 form
2776 (calc-eval (cons form org-tbl-calc-modes)
2777 (when (and (not keep-empty) numbers) 'num)))
2778 ev (if duration (org-table-time-seconds-to-string
2779 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
2780 (string-to-number (org-table-time-string-to-seconds ev))
2781 (string-to-number ev))
2782 duration-output-format)
2783 ev)))
2785 (when org-table-formula-debug
2786 (with-output-to-temp-buffer "*Substitution History*"
2787 (princ (format "Substitution history of formula
2788 Orig: %s
2789 $xyz-> %s
2790 @r$c-> %s
2791 $1-> %s\n" orig formula form0 form))
2792 (if (consp ev)
2793 (princ (format " %s^\nError: %s"
2794 (make-string (car ev) ?\-) (nth 1 ev)))
2795 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2796 ev (or fmt "NONE")
2797 (if fmt (format fmt (string-to-number ev)) ev)))))
2798 (setq bw (get-buffer-window "*Substitution History*"))
2799 (org-fit-window-to-buffer bw)
2800 (unless (and (org-called-interactively-p 'any) (not ndown))
2801 (unless (let (inhibit-redisplay)
2802 (y-or-n-p "Debugging Formula. Continue to next? "))
2803 (org-table-align)
2804 (user-error "Abort"))
2805 (delete-window bw)
2806 (message "")))
2807 (when (consp ev) (setq fmt nil ev "#ERROR"))
2808 (org-table-justify-field-maybe
2809 (format org-table-formula-field-format
2810 (if fmt (format fmt (string-to-number ev)) ev)))
2811 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2812 (call-interactively 'org-return)
2813 (setq ndown 0)))
2814 (and down (org-table-maybe-recalculate-line))
2815 (or suppress-align (and org-table-may-need-update
2816 (org-table-align))))))
2818 (defun org-table-put-field-property (prop value)
2819 (save-excursion
2820 (put-text-property (progn (skip-chars-backward "^|") (point))
2821 (progn (skip-chars-forward "^|") (point))
2822 prop value)))
2824 (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
2825 "Get a calc vector from a column, according to descriptor DESC.
2826 Optional arguments TBEG and COL can give the beginning of the table and
2827 the current column, to avoid unnecessary parsing.
2829 HIGHLIGHT means just highlight the range.
2831 When CORNERS-ONLY is set, only return the corners of the range as
2832 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2833 in the buffer and column1 and column2 are table column numbers."
2834 (if (not (equal (string-to-char desc) ?@))
2835 (setq desc (concat "@" desc)))
2836 (save-excursion
2837 (or tbeg (setq tbeg (org-table-begin)))
2838 (or col (setq col (org-table-current-column)))
2839 (let ((thisline (org-current-line))
2840 beg end c1 c2 r1 r2 rangep tmp)
2841 (unless (string-match org-table-range-regexp desc)
2842 (user-error "Invalid table range specifier `%s'" desc))
2843 (setq rangep (match-end 3)
2844 r1 (and (match-end 1) (match-string 1 desc))
2845 r2 (and (match-end 4) (match-string 4 desc))
2846 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
2847 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
2849 (and c1 (setq c1 (+ (string-to-number c1)
2850 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
2851 (and c2 (setq c2 (+ (string-to-number c2)
2852 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
2853 (if (equal r1 "") (setq r1 nil))
2854 (if (equal r2 "") (setq r2 nil))
2855 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
2856 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
2857 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2858 (if (not r1) (setq r1 thisline))
2859 (if (not r2) (setq r2 thisline))
2860 (if (or (not c1) (= 0 c1)) (setq c1 col))
2861 (if (or (not c2) (= 0 c2)) (setq c2 col))
2862 (if (and (not corners-only)
2863 (or (not rangep) (and (= r1 r2) (= c1 c2))))
2864 ;; just one field
2865 (progn
2866 (org-goto-line r1)
2867 (while (not (looking-at org-table-dataline-regexp))
2868 (beginning-of-line 2))
2869 (prog1 (org-trim (org-table-get-field c1))
2870 (if highlight (org-table-highlight-rectangle (point) (point)))))
2871 ;; A range, return a vector
2872 ;; First sort the numbers to get a regular rectangle
2873 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
2874 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
2875 (if corners-only
2876 ;; Only return the corners of the range
2877 (list r1 c1 r2 c2)
2878 ;; Copy the range values into a list
2879 (org-goto-line r1)
2880 (while (not (looking-at org-table-dataline-regexp))
2881 (beginning-of-line 2))
2882 (org-table-goto-column c1)
2883 (setq beg (point))
2884 (org-goto-line r2)
2885 (while (not (looking-at org-table-dataline-regexp))
2886 (beginning-of-line 0))
2887 (org-table-goto-column c2)
2888 (setq end (point))
2889 (if highlight
2890 (org-table-highlight-rectangle
2891 beg (progn (skip-chars-forward "^|\n") (point))))
2892 ;; return string representation of calc vector
2893 (mapcar 'org-trim
2894 (apply 'append (org-table-copy-region beg end))))))))
2896 (defun org-table-get-descriptor-line (desc &optional cline bline table)
2897 "Analyze descriptor DESC and retrieve the corresponding line number.
2898 The cursor is currently in line CLINE, the table begins in line BLINE,
2899 and TABLE is a vector with line types."
2900 (if (string-match "^[0-9]+$" desc)
2901 (aref org-table-dlines (string-to-number desc))
2902 (setq cline (or cline (org-current-line))
2903 bline (or bline org-table-current-begin-line)
2904 table (or table org-table-current-line-types))
2905 (if (or
2906 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
2907 ;; 1 2 3 4 5 6
2908 (and (not (match-end 3)) (not (match-end 6)))
2909 (and (match-end 3) (match-end 6) (not (match-end 5))))
2910 (user-error "Invalid row descriptor `%s'" desc))
2911 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
2912 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
2913 (odir (and (match-end 5) (match-string 5 desc)))
2914 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
2915 (i (- cline bline))
2916 (rel (and (match-end 6)
2917 (or (and (match-end 1) (not (match-end 3)))
2918 (match-end 5)))))
2919 (if (and hn (not hdir))
2920 (progn
2921 (setq i 0 hdir "+")
2922 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
2923 (if (and (not hn) on (not odir))
2924 (user-error "Should never happen");;(aref org-table-dlines on)
2925 (if (and hn (> hn 0))
2926 (setq i (org-table-find-row-type table i 'hline (equal hdir "-")
2927 nil hn cline desc)))
2928 (if on
2929 (setq i (org-table-find-row-type table i 'dline (equal odir "-")
2930 rel on cline desc)))
2931 (+ bline i)))))
2933 (defun org-table-find-row-type (table i type backwards relative n cline desc)
2934 "FIXME: Needs more documentation."
2935 (let ((l (length table)))
2936 (while (> n 0)
2937 (while (and (setq i (+ i (if backwards -1 1)))
2938 (>= i 0) (< i l)
2939 (not (eq (aref table i) type))
2940 (if (and relative (eq (aref table i) 'hline))
2941 (cond
2942 ((eq org-table-relative-ref-may-cross-hline t) t)
2943 ((eq org-table-relative-ref-may-cross-hline 'error)
2944 (user-error "Row descriptor %s used in line %d crosses hline" desc cline))
2945 (t (setq i (- i (if backwards -1 1))
2946 n 1)
2947 nil))
2948 t)))
2949 (setq n (1- n)))
2950 (if (or (< i 0) (>= i l))
2951 (user-error "Row descriptor %s used in line %d leads outside table"
2952 desc cline)
2953 i)))
2955 (defun org-table--error-on-old-row-references (s)
2956 (when (string-match "&[-+0-9I]" s)
2957 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
2959 (defun org-table-make-reference (elements keep-empty numbers lispp)
2960 "Convert list ELEMENTS to something appropriate to insert into formula.
2961 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2962 NUMBERS indicates that everything should be converted to numbers.
2963 LISPP non-nil means to return something appropriate for a Lisp
2964 list, 'literal is for the format specifier L."
2965 ;; Calc nan (not a number) is used for the conversion of the empty
2966 ;; field to a reference for several reasons: (i) It is accepted in a
2967 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
2968 ;; (ii) In a single field (not in range) it can be distinguished
2969 ;; from "(nan)" which is the reference made from a single field
2970 ;; containing "nan".
2971 (if (stringp elements)
2972 ;; field reference
2973 (if lispp
2974 (if (eq lispp 'literal)
2975 elements
2976 (if (and (eq elements "") (not keep-empty))
2978 (prin1-to-string
2979 (if numbers (string-to-number elements) elements))))
2980 (if (string-match "\\S-" elements)
2981 (progn
2982 (when numbers (setq elements (number-to-string
2983 (string-to-number elements))))
2984 (concat "(" elements ")"))
2985 (if (or (not keep-empty) numbers) "(0)" "nan")))
2986 ;; range reference
2987 (unless keep-empty
2988 (setq elements
2989 (delq nil
2990 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
2991 elements))))
2992 (setq elements (or elements '())) ; if delq returns nil then we need '()
2993 (if lispp
2994 (mapconcat
2995 (lambda (x)
2996 (if (eq lispp 'literal)
2998 (prin1-to-string (if numbers (string-to-number x) x))))
2999 elements " ")
3000 (concat "[" (mapconcat
3001 (lambda (x)
3002 (if (string-match "\\S-" x)
3003 (if numbers
3004 (number-to-string (string-to-number x))
3006 (if (or (not keep-empty) numbers) "0" "nan")))
3007 elements
3008 ",") "]"))))
3010 (defun org-table-message-once-per-second (t1 &rest args)
3011 "If there has been more than one second since T1, display message.
3012 ARGS are passed as arguments to the `message' function. Returns
3013 current time if a message is printed, otherwise returns T1. If
3014 T1 is nil, always messages."
3015 (let ((curtime (current-time)))
3016 (if (or (not t1) (< 0 (nth 1 (time-subtract curtime t1))))
3017 (progn (apply 'message args)
3018 curtime)
3019 t1)))
3021 ;;;###autoload
3022 (defun org-table-recalculate (&optional all noalign)
3023 "Recalculate the current table line by applying all stored formulas.
3024 With prefix arg ALL, do this for all lines in the table.
3025 With the prefix argument ALL is `(16)' \
3026 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
3027 it is the symbol `iterate', recompute the table until it no longer changes.
3028 If NOALIGN is not nil, do not re-align the table after the computations
3029 are done. This is typically used internally to save time, if it is
3030 known that the table will be realigned a little later anyway."
3031 (interactive "P")
3032 (or (memq this-command org-recalc-commands)
3033 (setq org-recalc-commands (cons this-command org-recalc-commands)))
3034 (unless (org-at-table-p) (user-error "Not at a table"))
3035 (if (or (eq all 'iterate) (equal all '(16)))
3036 (org-table-iterate)
3037 (org-table-get-specials)
3038 (let* ((eqlist (sort (org-table-get-stored-formulas)
3039 (lambda (a b) (string< (car a) (car b)))))
3040 (eqlist1 (copy-sequence eqlist))
3041 (inhibit-redisplay (not debug-on-error))
3042 (line-re org-table-dataline-regexp)
3043 (thisline (org-current-line))
3044 (thiscol (org-table-current-column))
3045 (log-first-time (current-time))
3046 (log-last-time log-first-time)
3047 seen-fields lhs1
3048 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name name1)
3049 ;; Insert constants in all formulas
3050 (when eqlist
3051 (setq eqlist
3052 (mapcar
3053 (lambda (x)
3054 (if (string-match "^@-?I+" (car x))
3055 (user-error "Can't assign to hline relative reference"))
3056 (when (string-match "\\`$[<>]" (car x))
3057 (setq lhs1 (car x))
3058 (setq x (cons (substring
3059 (org-table-formula-handle-first/last-rc
3060 (car x)) 1)
3061 (cdr x)))
3062 (if (assoc (car x) eqlist1)
3063 (user-error "\"%s=\" formula tries to overwrite existing formula for column %s"
3064 lhs1 (car x))))
3065 (cons
3066 (org-table-formula-handle-first/last-rc (car x))
3067 (org-table-formula-substitute-names
3068 (org-table-formula-handle-first/last-rc (cdr x)))))
3069 eqlist))
3070 ;; Split the equation list
3071 (while (setq eq (pop eqlist))
3072 (if (<= (string-to-char (car eq)) ?9)
3073 (push eq eqlnum)
3074 (push eq eqlname)))
3075 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
3076 ;; Expand ranges in lhs of formulas
3077 (setq eqlname (org-table-expand-lhs-ranges eqlname))
3079 ;; Get the correct line range to process
3080 (if all
3081 (progn
3082 (setq end (move-marker (make-marker) (1+ (org-table-end))))
3083 (goto-char (setq beg (org-table-begin)))
3084 (if (re-search-forward org-table-calculate-mark-regexp end t)
3085 ;; This is a table with marked lines, compute selected lines
3086 (setq line-re org-table-recalculate-regexp)
3087 ;; Move forward to the first non-header line
3088 (if (and (re-search-forward org-table-dataline-regexp end t)
3089 (re-search-forward org-table-hline-regexp end t)
3090 (re-search-forward org-table-dataline-regexp end t))
3091 (setq beg (match-beginning 0))
3092 nil))) ;; just leave beg where it is
3093 (setq beg (point-at-bol)
3094 end (move-marker (make-marker) (1+ (point-at-eol)))))
3095 (goto-char beg)
3097 ;; First find the named fields, and mark them untouchable.
3098 ;; Also check if several field/range formulas try to set the same field.
3099 (remove-text-properties beg end '(org-untouchable t))
3100 (while (setq eq (pop eqlname))
3101 (setq name (car eq)
3102 a (assoc name org-table-named-field-locations))
3103 (setq name1 name)
3104 (if a (setq name1 (format "@%d$%d" (org-table-line-to-dline (nth 1 a))
3105 (nth 2 a))))
3106 (when (member name1 seen-fields)
3107 (user-error "Several field/range formulas try to set %s" name1))
3108 (push name1 seen-fields)
3110 (and (not a)
3111 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
3112 (setq a (list name
3113 (condition-case nil
3114 (aref org-table-dlines
3115 (string-to-number (match-string 1 name)))
3116 (error (user-error "Invalid row number in %s"
3117 name)))
3118 (string-to-number (match-string 2 name)))))
3119 (when (and a (or all (equal (nth 1 a) thisline)))
3120 (setq log-last-time
3121 (org-table-message-once-per-second
3122 (and all log-last-time)
3123 "Re-applying formula to field: %s" name))
3124 (org-goto-line (nth 1 a))
3125 (org-table-goto-column (nth 2 a))
3126 (push (append a (list (cdr eq))) eqlname1)
3127 (org-table-put-field-property :org-untouchable t)))
3128 (setq eqlname1 (nreverse eqlname1))
3130 ;; Now evaluate the column formulas, but skip fields covered
3131 ;; by field formulas
3132 (goto-char beg)
3133 (while (re-search-forward line-re end t)
3134 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
3135 ;; Unprotected line, recalculate
3136 (setq cnt (1+ cnt))
3137 (and all (setq log-last-time
3138 (org-table-message-once-per-second
3139 log-last-time
3140 "Re-applying formulas to full table...(line %d)" cnt)))
3141 (setq org-last-recalc-line (org-current-line))
3142 (setq eql eqlnum)
3143 (while (setq entry (pop eql))
3144 (org-goto-line org-last-recalc-line)
3145 (org-table-goto-column (string-to-number (car entry)) nil 'force)
3146 (unless (get-text-property (point) :org-untouchable)
3147 (org-table-eval-formula
3148 nil (cdr entry)
3149 'noalign 'nocst 'nostore 'noanalysis)))))
3151 ;; Now evaluate the field formulas
3152 (while (setq eq (pop eqlname1))
3153 (setq log-last-time
3154 (org-table-message-once-per-second
3155 (and all log-last-time)
3156 "Re-applying formula to field: %s" (car eq)))
3157 (org-goto-line (nth 1 eq))
3158 (let ((column-target (nth 2 eq)))
3159 (when (> column-target 1000)
3160 (user-error "Formula column target too large"))
3161 (let* ((column-count (progn (end-of-line)
3162 (1- (org-table-current-column))))
3163 (create-new-column
3164 (and (> column-target column-count)
3165 (or (eq org-table-formula-create-columns t)
3166 (and
3167 (eq org-table-formula-create-columns 'warn)
3168 (progn
3169 (org-display-warning
3170 "Out-of-bounds formula added columns")
3172 (and
3173 (eq org-table-formula-create-columns 'prompt)
3174 (yes-or-no-p
3175 "Out-of-bounds formula. Add columns?"))))))
3176 (org-table-goto-column column-target nil create-new-column))
3178 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
3179 'nostore 'noanalysis)))
3181 (org-goto-line thisline)
3182 (org-table-goto-column thiscol)
3183 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
3184 (or noalign (and org-table-may-need-update (org-table-align))
3185 (and all (org-table-message-once-per-second
3186 log-first-time
3187 "Re-applying formulas to %d lines...done" cnt)))
3190 ;; back to initial position
3191 (org-table-message-once-per-second
3192 (and all log-first-time)
3193 "Re-applying formulas...done")
3195 (org-goto-line thisline)
3196 (org-table-goto-column thiscol)
3197 (or noalign (and org-table-may-need-update (org-table-align)))))))
3199 ;;;###autoload
3200 (defun org-table-iterate (&optional arg)
3201 "Recalculate the table until it does not change anymore.
3202 The maximum number of iterations is 10, but you can choose a different value
3203 with the prefix ARG."
3204 (interactive "P")
3205 (let ((imax (if arg (prefix-numeric-value arg) 10))
3206 (i 0)
3207 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3208 thistbl)
3209 (catch 'exit
3210 (while (< i imax)
3211 (setq i (1+ i))
3212 (org-table-recalculate 'all)
3213 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
3214 (if (not (string= lasttbl thistbl))
3215 (setq lasttbl thistbl)
3216 (if (> i 1)
3217 (message "Convergence after %d iterations" i)
3218 (message "Table was already stable"))
3219 (throw 'exit t)))
3220 (user-error "No convergence after %d iterations" i))))
3222 ;;;###autoload
3223 (defun org-table-recalculate-buffer-tables ()
3224 "Recalculate all tables in the current buffer."
3225 (interactive)
3226 (save-excursion
3227 (save-restriction
3228 (widen)
3229 (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
3231 ;;;###autoload
3232 (defun org-table-iterate-buffer-tables ()
3233 "Iterate all tables in the buffer, to converge inter-table dependencies."
3234 (interactive)
3235 (let* ((imax 10)
3236 (i imax)
3237 (checksum (md5 (buffer-string)))
3239 (save-excursion
3240 (save-restriction
3241 (widen)
3242 (catch 'exit
3243 (while (> i 0)
3244 (setq i (1- i))
3245 (org-table-map-tables (lambda () (org-table-recalculate t)) t)
3246 (if (equal checksum (setq c1 (md5 (buffer-string))))
3247 (progn
3248 (message "Convergence after %d iterations" (- imax i))
3249 (throw 'exit t))
3250 (setq checksum c1)))
3251 (user-error "No convergence after %d iterations" imax))))))
3253 (defun org-table-calc-current-TBLFM (&optional arg)
3254 "Apply the #+TBLFM in the line at point to the table."
3255 (interactive "P")
3256 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3257 (let ((formula (buffer-substring
3258 (point-at-bol)
3259 (point-at-eol)))
3260 s e)
3261 (save-excursion
3262 ;; Insert a temporary formula at right after the table
3263 (goto-char (org-table-TBLFM-begin))
3264 (setq s (set-marker (make-marker) (point)))
3265 (insert (concat formula "\n"))
3266 (setq e (set-marker (make-marker) (point)))
3267 ;; Recalculate the table
3268 (beginning-of-line 0) ; move to the inserted line
3269 (skip-chars-backward " \r\n\t")
3270 (if (org-at-table-p)
3271 (unwind-protect
3272 (org-call-with-arg 'org-table-recalculate (or arg t))
3273 ;; delete the formula inserted temporarily
3274 (delete-region s e))))))
3276 (defun org-table-TBLFM-begin ()
3277 "Find the beginning of the TBLFM lines and return its position.
3278 Return nil when the beginning of TBLFM line was not found."
3279 (save-excursion
3280 (when (progn (forward-line 1)
3281 (re-search-backward
3282 org-table-TBLFM-begin-regexp
3283 nil t))
3284 (point-at-bol 2))))
3286 (defun org-table-expand-lhs-ranges (equations)
3287 "Expand list of formulas.
3288 If some of the RHS in the formulas are ranges or a row reference, expand
3289 them to individual field equations for each field."
3290 (let (e res lhs rhs range r1 r2 c1 c2)
3291 (while (setq e (pop equations))
3292 (setq lhs (car e) rhs (cdr e))
3293 (cond
3294 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs)
3295 ;; This just refers to one fixed field
3296 (push e res))
3297 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs)
3298 ;; This just refers to one fixed named field
3299 (push e res))
3300 ((string-match "^@[0-9]+$" lhs)
3301 (loop for ic from 1 to org-table-current-ncol do
3302 (push (cons (format "%s$%d" lhs ic) rhs) res)
3303 (put-text-property 0 (length (caar res))
3304 :orig-eqn e (caar res))))
3306 (setq range (org-table-get-range lhs org-table-current-begin-pos
3307 1 nil 'corners))
3308 (setq r1 (nth 0 range) c1 (nth 1 range)
3309 r2 (nth 2 range) c2 (nth 3 range))
3310 (setq r1 (org-table-line-to-dline r1))
3311 (setq r2 (org-table-line-to-dline r2 'above))
3312 (loop for ir from r1 to r2 do
3313 (loop for ic from c1 to c2 do
3314 (push (cons (format "@%d$%d" ir ic) rhs) res)
3315 (put-text-property 0 (length (caar res))
3316 :orig-eqn e (caar res)))))))
3317 (nreverse res)))
3319 (defun org-table-formula-handle-first/last-rc (s)
3320 "Replace @<, @>, $<, $> with first/last row/column of the table.
3321 So @< and $< will always be replaced with @1 and $1, respectively.
3322 The advantage of these special markers are that structure editing of
3323 the table will not change them, while @1 and $1 will be modified
3324 when a line/row is swapped out of that privileged position. So for
3325 formulas that use a range of rows or columns, it may often be better
3326 to anchor the formula with \"I\" row markers, or to offset from the
3327 borders of the table using the @< @> $< $> makers."
3328 (let (n nmax len char (start 0))
3329 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3330 s start)
3331 (if (match-end 3)
3332 (setq start (match-end 3))
3333 (setq nmax (if (equal (match-string 1 s) "@")
3334 (1- (length org-table-dlines))
3335 org-table-current-ncol)
3336 len (- (match-end 2) (match-beginning 2))
3337 char (string-to-char (match-string 2 s))
3338 n (if (= char ?<)
3340 (- nmax len -1)))
3341 (if (or (< n 1) (> n nmax))
3342 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3343 (match-string 0 s) s))
3344 (setq start (match-beginning 0))
3345 (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
3348 (defun org-table-formula-substitute-names (f)
3349 "Replace $const with values in string F."
3350 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
3351 ;; First, check for column names
3352 (while (setq start (string-match org-table-column-name-regexp f start))
3353 (setq start (1+ start))
3354 (setq a (assoc (match-string 1 f) org-table-column-names))
3355 (setq f (replace-match (concat "$" (cdr a)) t t f)))
3356 ;; Parameters and constants
3357 (setq start 0)
3358 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start))
3359 (if (match-end 2)
3360 (setq start (match-end 2))
3361 (setq start (1+ start))
3362 (if (setq a (save-match-data
3363 (org-table-get-constant (match-string 1 f))))
3364 (setq f (replace-match
3365 (concat (if pp "(") a (if pp ")")) t t f)))))
3366 (if org-table-formula-debug
3367 (put-text-property 0 (length f) :orig-formula f1 f))
3370 (defun org-table-get-constant (const)
3371 "Find the value for a parameter or constant in a formula.
3372 Parameters get priority."
3373 (or (cdr (assoc const org-table-local-parameters))
3374 (cdr (assoc const org-table-formula-constants-local))
3375 (cdr (assoc const org-table-formula-constants))
3376 (and (fboundp 'constants-get) (constants-get const))
3377 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
3378 (org-entry-get nil (substring const 5) 'inherit))
3379 "#UNDEFINED_NAME"))
3381 (defvar org-table-fedit-map
3382 (let ((map (make-sparse-keymap)))
3383 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
3384 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
3385 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
3386 (org-defkey map "\C-c'" 'org-table-fedit-finish)
3387 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
3388 (org-defkey map "\C-c?" 'org-table-show-reference)
3389 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
3390 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
3391 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
3392 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
3393 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
3394 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
3395 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
3396 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
3397 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
3398 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
3399 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
3400 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
3401 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
3402 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
3403 map))
3405 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
3406 '("Edit-Formulas"
3407 ["Finish and Install" org-table-fedit-finish t]
3408 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
3409 ["Abort" org-table-fedit-abort t]
3410 "--"
3411 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
3412 ["Complete Lisp Symbol" lisp-complete-symbol t]
3413 "--"
3414 "Shift Reference at Point"
3415 ["Up" org-table-fedit-ref-up t]
3416 ["Down" org-table-fedit-ref-down t]
3417 ["Left" org-table-fedit-ref-left t]
3418 ["Right" org-table-fedit-ref-right t]
3420 "Change Test Row for Column Formulas"
3421 ["Up" org-table-fedit-line-up t]
3422 ["Down" org-table-fedit-line-down t]
3423 "--"
3424 ["Scroll Table Window" org-table-fedit-scroll t]
3425 ["Scroll Table Window down" org-table-fedit-scroll-down t]
3426 ["Show Table Grid" org-table-fedit-toggle-coordinates
3427 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
3428 org-table-overlay-coordinates)]
3429 "--"
3430 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3431 :style toggle :selected org-table-buffer-is-an]))
3433 (defvar org-pos)
3435 ;;;###autoload
3436 (defun org-table-edit-formulas ()
3437 "Edit the formulas of the current table in a separate buffer."
3438 (interactive)
3439 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t)) (looking-at "[ \t]*#\\+TBLFM")))
3440 (beginning-of-line 0))
3441 (unless (org-at-table-p) (user-error "Not at a table"))
3442 (org-table-get-specials)
3443 (let ((key (org-table-current-field-formula 'key 'noerror))
3444 (eql (sort (org-table-get-stored-formulas 'noerror)
3445 'org-table-formula-less-p))
3446 (pos (point-marker))
3447 (startline 1)
3448 (wc (current-window-configuration))
3449 (sel-win (selected-window))
3450 (titles '((column . "# Column Formulas\n")
3451 (field . "# Field and Range Formulas\n")
3452 (named . "# Named Field Formulas\n")))
3453 entry s type title)
3454 (org-switch-to-buffer-other-window "*Edit Formulas*")
3455 (erase-buffer)
3456 ;; Keep global-font-lock-mode from turning on font-lock-mode
3457 (let ((font-lock-global-modes '(not fundamental-mode)))
3458 (fundamental-mode))
3459 (org-set-local 'font-lock-global-modes (list 'not major-mode))
3460 (org-set-local 'org-pos pos)
3461 (org-set-local 'org-window-configuration wc)
3462 (org-set-local 'org-selected-window sel-win)
3463 (use-local-map org-table-fedit-map)
3464 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
3465 (easy-menu-add org-table-fedit-menu)
3466 (setq startline (org-current-line))
3467 (while (setq entry (pop eql))
3468 (setq type (cond
3469 ((string-match "\\`$[<>]" (car entry)) 'column)
3470 ((equal (string-to-char (car entry)) ?@) 'field)
3471 ((string-match "^[0-9]" (car entry)) 'column)
3472 (t 'named)))
3473 (when (setq title (assq type titles))
3474 (or (bobp) (insert "\n"))
3475 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
3476 (setq titles (remove title titles)))
3477 (if (equal key (car entry)) (setq startline (org-current-line)))
3478 (setq s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
3479 (car entry) " = " (cdr entry) "\n"))
3480 (remove-text-properties 0 (length s) '(face nil) s)
3481 (insert s))
3482 (if (eq org-table-use-standard-references t)
3483 (org-table-fedit-toggle-ref-type))
3484 (org-goto-line startline)
3485 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3487 (defun org-table-fedit-post-command ()
3488 (when (not (memq this-command '(lisp-complete-symbol)))
3489 (let ((win (selected-window)))
3490 (save-excursion
3491 (condition-case nil
3492 (org-table-show-reference)
3493 (error nil))
3494 (select-window win)))))
3496 (defun org-table-formula-to-user (s)
3497 "Convert a formula from internal to user representation."
3498 (if (eq org-table-use-standard-references t)
3499 (org-table-convert-refs-to-an s)
3502 (defun org-table-formula-from-user (s)
3503 "Convert a formula from user to internal representation."
3504 (if org-table-use-standard-references
3505 (org-table-convert-refs-to-rc s)
3508 (defun org-table-convert-refs-to-rc (s)
3509 "Convert spreadsheet references from A7 to @7$28.
3510 Works for single references, but also for entire formulas and even the
3511 full TBLFM line."
3512 (let ((start 0))
3513 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
3514 (cond
3515 ((match-end 3)
3516 ;; format match, just advance
3517 (setq start (match-end 0)))
3518 ((and (> (match-beginning 0) 0)
3519 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3520 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3521 ;; 3.e5 or something like this.
3522 (setq start (match-end 0)))
3523 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3524 ;; (member (match-string 1 s)
3525 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3527 ;; function name, just advance
3528 (setq start (match-end 0)))
3530 (setq start (match-beginning 0)
3531 s (replace-match
3532 (if (equal (match-string 2 s) "&")
3533 (format "$%d" (org-letters-to-number (match-string 1 s)))
3534 (format "@%d$%d"
3535 (string-to-number (match-string 2 s))
3536 (org-letters-to-number (match-string 1 s))))
3537 t t s)))))
3540 (defun org-table-convert-refs-to-an (s)
3541 "Convert spreadsheet references from to @7$28 to AB7.
3542 Works for single references, but also for entire formulas and even the
3543 full TBLFM line."
3544 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3545 (setq s (replace-match
3546 (format "%s%d"
3547 (org-number-to-letters
3548 (string-to-number (match-string 2 s)))
3549 (string-to-number (match-string 1 s)))
3550 t t s)))
3551 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3552 (setq s (replace-match (concat "\\1"
3553 (org-number-to-letters
3554 (string-to-number (match-string 2 s))) "&")
3555 t nil s)))
3558 (defun org-letters-to-number (s)
3559 "Convert a base 26 number represented by letters into an integer.
3560 For example: AB -> 28."
3561 (let ((n 0))
3562 (setq s (upcase s))
3563 (while (> (length s) 0)
3564 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3565 s (substring s 1)))
3568 (defun org-number-to-letters (n)
3569 "Convert an integer into a base 26 number represented by letters.
3570 For example: 28 -> AB."
3571 (let ((s ""))
3572 (while (> n 0)
3573 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3574 n (/ (1- n) 26)))
3577 (defun org-table-time-string-to-seconds (s)
3578 "Convert a time string into numerical duration in seconds.
3579 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3580 If S is a string representing a number, keep this number."
3581 (if (equal s "")
3583 (let (hour minus min sec res)
3584 (cond
3585 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
3586 (setq minus (< 0 (length (match-string 1 s)))
3587 hour (string-to-number (match-string 2 s))
3588 min (string-to-number (match-string 3 s))
3589 sec (string-to-number (match-string 4 s)))
3590 (if minus
3591 (setq res (- (+ (* hour 3600) (* min 60) sec)))
3592 (setq res (+ (* hour 3600) (* min 60) sec))))
3593 ((and (not (string-match org-ts-regexp-both s))
3594 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
3595 (setq minus (< 0 (length (match-string 1 s)))
3596 hour (string-to-number (match-string 2 s))
3597 min (string-to-number (match-string 3 s)))
3598 (if minus
3599 (setq res (- (+ (* hour 3600) (* min 60))))
3600 (setq res (+ (* hour 3600) (* min 60)))))
3601 (t (setq res (string-to-number s))))
3602 (number-to-string res))))
3604 (defun org-table-time-seconds-to-string (secs &optional output-format)
3605 "Convert a number of seconds to a time string.
3606 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3607 minutes or seconds."
3608 (let* ((secs0 (abs secs))
3609 (res
3610 (cond ((eq output-format 'days)
3611 (format "%.3f" (/ (float secs0) 86400)))
3612 ((eq output-format 'hours)
3613 (format "%.2f" (/ (float secs0) 3600)))
3614 ((eq output-format 'minutes)
3615 (format "%.1f" (/ (float secs0) 60)))
3616 ((eq output-format 'seconds)
3617 (format "%d" secs0))
3618 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0)))))
3619 (if (< secs 0) (concat "-" res) res)))
3621 (defun org-table-fedit-convert-buffer (function)
3622 "Convert all references in this buffer, using FUNCTION."
3623 (let ((line (org-current-line)))
3624 (goto-char (point-min))
3625 (while (not (eobp))
3626 (insert (funcall function (buffer-substring (point) (point-at-eol))))
3627 (delete-region (point) (point-at-eol))
3628 (or (eobp) (forward-char 1)))
3629 (org-goto-line line)))
3631 (defun org-table-fedit-toggle-ref-type ()
3632 "Convert all references in the buffer from B3 to @3$2 and back."
3633 (interactive)
3634 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
3635 (org-table-fedit-convert-buffer
3636 (if org-table-buffer-is-an
3637 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3638 (message "Reference type switched to %s"
3639 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3641 (defun org-table-fedit-ref-up ()
3642 "Shift the reference at point one row/hline up."
3643 (interactive)
3644 (org-table-fedit-shift-reference 'up))
3645 (defun org-table-fedit-ref-down ()
3646 "Shift the reference at point one row/hline down."
3647 (interactive)
3648 (org-table-fedit-shift-reference 'down))
3649 (defun org-table-fedit-ref-left ()
3650 "Shift the reference at point one field to the left."
3651 (interactive)
3652 (org-table-fedit-shift-reference 'left))
3653 (defun org-table-fedit-ref-right ()
3654 "Shift the reference at point one field to the right."
3655 (interactive)
3656 (org-table-fedit-shift-reference 'right))
3658 (defun org-table-fedit-shift-reference (dir)
3659 (cond
3660 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3661 (if (memq dir '(left right))
3662 (org-rematch-and-replace 1 (eq dir 'left))
3663 (user-error "Cannot shift reference in this direction")))
3664 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3665 ;; A B3-like reference
3666 (if (memq dir '(up down))
3667 (org-rematch-and-replace 2 (eq dir 'up))
3668 (org-rematch-and-replace 1 (eq dir 'left))))
3669 ((org-at-regexp-p
3670 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3671 ;; An internal reference
3672 (if (memq dir '(up down))
3673 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3674 (org-rematch-and-replace 5 (eq dir 'left))))))
3676 (defun org-rematch-and-replace (n &optional decr hline)
3677 "Re-match the group N, and replace it with the shifted reference."
3678 (or (match-end n) (user-error "Cannot shift reference in this direction"))
3679 (goto-char (match-beginning n))
3680 (and (looking-at (regexp-quote (match-string n)))
3681 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3682 t t)))
3684 (defun org-table-shift-refpart (ref &optional decr hline)
3685 "Shift a reference part REF.
3686 If DECR is set, decrease the references row/column, else increase.
3687 If HLINE is set, this may be a hline reference, it certainly is not
3688 a translation reference."
3689 (save-match-data
3690 (let* ((sign (string-match "^[-+]" ref)) n)
3692 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3693 (cond
3694 ((and hline (string-match "^I+" ref))
3695 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3696 (setq n (+ n (if decr -1 1)))
3697 (if (= n 0) (setq n (+ n (if decr -1 1))))
3698 (if sign
3699 (setq sign (if (< n 0) "-" "+") n (abs n))
3700 (setq n (max 1 n)))
3701 (concat sign (make-string n ?I)))
3703 ((string-match "^[0-9]+" ref)
3704 (setq n (string-to-number (concat sign ref)))
3705 (setq n (+ n (if decr -1 1)))
3706 (if sign
3707 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3708 (number-to-string (max 1 n))))
3710 ((string-match "^[a-zA-Z]+" ref)
3711 (org-number-to-letters
3712 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3714 (t (user-error "Cannot shift reference"))))))
3716 (defun org-table-fedit-toggle-coordinates ()
3717 "Toggle the display of coordinates in the referenced table."
3718 (interactive)
3719 (let ((pos (marker-position org-pos)))
3720 (with-current-buffer (marker-buffer org-pos)
3721 (save-excursion
3722 (goto-char pos)
3723 (org-table-toggle-coordinate-overlays)))))
3725 (defun org-table-fedit-finish (&optional arg)
3726 "Parse the buffer for formula definitions and install them.
3727 With prefix ARG, apply the new formulas to the table."
3728 (interactive "P")
3729 (org-table-remove-rectangle-highlight)
3730 (if org-table-use-standard-references
3731 (progn
3732 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3733 (setq org-table-buffer-is-an nil)))
3734 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3735 (goto-char (point-min))
3736 (while (re-search-forward
3737 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3738 nil t)
3739 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3740 form (match-string 3))
3741 (setq form (org-trim form))
3742 (when (not (equal form ""))
3743 (while (string-match "[ \t]*\n[ \t]*" form)
3744 (setq form (replace-match " " t t form)))
3745 (when (assoc var eql)
3746 (user-error "Double formulas for %s" var))
3747 (push (cons var form) eql)))
3748 (setq org-pos nil)
3749 (set-window-configuration org-window-configuration)
3750 (select-window sel-win)
3751 (goto-char pos)
3752 (unless (org-at-table-p)
3753 (user-error "Lost table position - cannot install formulas"))
3754 (org-table-store-formulas eql)
3755 (move-marker pos nil)
3756 (kill-buffer "*Edit Formulas*")
3757 (if arg
3758 (org-table-recalculate 'all)
3759 (message "New formulas installed - press C-u C-c C-c to apply."))))
3761 (defun org-table-fedit-abort ()
3762 "Abort editing formulas, without installing the changes."
3763 (interactive)
3764 (org-table-remove-rectangle-highlight)
3765 (let ((pos org-pos) (sel-win org-selected-window))
3766 (set-window-configuration org-window-configuration)
3767 (select-window sel-win)
3768 (goto-char pos)
3769 (move-marker pos nil)
3770 (message "Formula editing aborted without installing changes")))
3772 (defun org-table-fedit-lisp-indent ()
3773 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3774 (interactive)
3775 (let ((pos (point)) beg end ind)
3776 (beginning-of-line 1)
3777 (cond
3778 ((looking-at "[ \t]")
3779 (goto-char pos)
3780 (call-interactively 'lisp-indent-line))
3781 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3782 ((not (fboundp 'pp-buffer))
3783 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3784 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3785 (goto-char (- (match-end 0) 2))
3786 (setq beg (point))
3787 (setq ind (make-string (current-column) ?\ ))
3788 (condition-case nil (forward-sexp 1)
3789 (error
3790 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3791 (setq end (point))
3792 (save-restriction
3793 (narrow-to-region beg end)
3794 (if (eq last-command this-command)
3795 (progn
3796 (goto-char (point-min))
3797 (setq this-command nil)
3798 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3799 (replace-match " ")))
3800 (pp-buffer)
3801 (untabify (point-min) (point-max))
3802 (goto-char (1+ (point-min)))
3803 (while (re-search-forward "^." nil t)
3804 (beginning-of-line 1)
3805 (insert ind))
3806 (goto-char (point-max))
3807 (org-delete-backward-char 1)))
3808 (goto-char beg))
3809 (t nil))))
3811 (defvar org-show-positions nil)
3813 (defun org-table-show-reference (&optional local)
3814 "Show the location/value of the $ expression at point."
3815 (interactive)
3816 (org-table-remove-rectangle-highlight)
3817 (catch 'exit
3818 (let ((pos (if local (point) org-pos))
3819 (face2 'highlight)
3820 (org-inhibit-highlight-removal t)
3821 (win (selected-window))
3822 (org-show-positions nil)
3823 var name e what match dest)
3824 (if local (org-table-get-specials))
3825 (setq what (cond
3826 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3827 (setq match (concat (substring (match-string 0) 0 -1)
3828 "$1.."
3829 (substring (match-string 0) 0 -1)
3830 "$100"))
3831 'range)
3832 ((or (org-at-regexp-p org-table-range-regexp2)
3833 (org-at-regexp-p org-table-translate-regexp)
3834 (org-at-regexp-p org-table-range-regexp))
3835 (setq match
3836 (save-match-data
3837 (org-table-convert-refs-to-rc (match-string 0))))
3838 'range)
3839 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3840 ((org-at-regexp-p "\\$[0-9]+") 'column)
3841 ((not local) nil)
3842 (t (user-error "No reference at point")))
3843 match (and what (or match (match-string 0))))
3844 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3845 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3846 'secondary-selection))
3847 (org-add-hook 'before-change-functions
3848 'org-table-remove-rectangle-highlight)
3849 (if (eq what 'name) (setq var (substring match 1)))
3850 (when (eq what 'range)
3851 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
3852 (setq match (org-table-formula-substitute-names match)))
3853 (unless local
3854 (save-excursion
3855 (end-of-line 1)
3856 (re-search-backward "^\\S-" nil t)
3857 (beginning-of-line 1)
3858 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3859 (setq dest
3860 (save-match-data
3861 (org-table-convert-refs-to-rc (match-string 1))))
3862 (org-table-add-rectangle-overlay
3863 (match-beginning 1) (match-end 1) face2))))
3864 (if (and (markerp pos) (marker-buffer pos))
3865 (if (get-buffer-window (marker-buffer pos))
3866 (select-window (get-buffer-window (marker-buffer pos)))
3867 (org-switch-to-buffer-other-window (get-buffer-window
3868 (marker-buffer pos)))))
3869 (goto-char pos)
3870 (org-table-force-dataline)
3871 (when dest
3872 (setq name (substring dest 1))
3873 (cond
3874 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3875 (setq e (assoc name org-table-named-field-locations))
3876 (org-goto-line (nth 1 e))
3877 (org-table-goto-column (nth 2 e)))
3878 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
3879 (let ((l (string-to-number (match-string 1 dest)))
3880 (c (string-to-number (match-string 2 dest))))
3881 (org-goto-line (aref org-table-dlines l))
3882 (org-table-goto-column c)))
3883 (t (org-table-goto-column (string-to-number name))))
3884 (move-marker pos (point))
3885 (org-table-highlight-rectangle nil nil face2))
3886 (cond
3887 ((equal dest match))
3888 ((not match))
3889 ((eq what 'range)
3890 (condition-case nil
3891 (save-excursion
3892 (org-table-get-range match nil nil 'highlight))
3893 (error nil)))
3894 ((setq e (assoc var org-table-named-field-locations))
3895 (org-goto-line (nth 1 e))
3896 (org-table-goto-column (nth 2 e))
3897 (org-table-highlight-rectangle (point) (point))
3898 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3899 ((setq e (assoc var org-table-column-names))
3900 (org-table-goto-column (string-to-number (cdr e)))
3901 (org-table-highlight-rectangle (point) (point))
3902 (goto-char (org-table-begin))
3903 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3904 (org-table-end) t)
3905 (progn
3906 (goto-char (match-beginning 1))
3907 (org-table-highlight-rectangle)
3908 (message "Named column (column %s)" (cdr e)))
3909 (user-error "Column name not found")))
3910 ((eq what 'column)
3911 ;; column number
3912 (org-table-goto-column (string-to-number (substring match 1)))
3913 (org-table-highlight-rectangle (point) (point))
3914 (message "Column %s" (substring match 1)))
3915 ((setq e (assoc var org-table-local-parameters))
3916 (goto-char (org-table-begin))
3917 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3918 (progn
3919 (goto-char (match-beginning 1))
3920 (org-table-highlight-rectangle)
3921 (message "Local parameter."))
3922 (user-error "Parameter not found")))
3924 (cond
3925 ((not var) (user-error "No reference at point"))
3926 ((setq e (assoc var org-table-formula-constants-local))
3927 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3928 var (cdr e)))
3929 ((setq e (assoc var org-table-formula-constants))
3930 (message "Constant: $%s=%s in `org-table-formula-constants'."
3931 var (cdr e)))
3932 ((setq e (and (fboundp 'constants-get) (constants-get var)))
3933 (message "Constant: $%s=%s, from `constants.el'%s."
3934 var e (format " (%s units)" constants-unit-system)))
3935 (t (user-error "Undefined name $%s" var)))))
3936 (goto-char pos)
3937 (when (and org-show-positions
3938 (not (memq this-command '(org-table-fedit-scroll
3939 org-table-fedit-scroll-down))))
3940 (push pos org-show-positions)
3941 (push org-table-current-begin-pos org-show-positions)
3942 (let ((min (apply 'min org-show-positions))
3943 (max (apply 'max org-show-positions)))
3944 (set-window-start (selected-window) min)
3945 (goto-char max)
3946 (or (pos-visible-in-window-p max)
3947 (set-window-start (selected-window) max))))
3948 (select-window win))))
3950 (defun org-table-force-dataline ()
3951 "Make sure the cursor is in a dataline in a table."
3952 (unless (save-excursion
3953 (beginning-of-line 1)
3954 (looking-at org-table-dataline-regexp))
3955 (let* ((re org-table-dataline-regexp)
3956 (p1 (save-excursion (re-search-forward re nil 'move)))
3957 (p2 (save-excursion (re-search-backward re nil 'move))))
3958 (cond ((and p1 p2)
3959 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
3960 p1 p2)))
3961 ((or p1 p2) (goto-char (or p1 p2)))
3962 (t (user-error "No table dataline around here"))))))
3964 (defun org-table-fedit-line-up ()
3965 "Move cursor one line up in the window showing the table."
3966 (interactive)
3967 (org-table-fedit-move 'previous-line))
3969 (defun org-table-fedit-line-down ()
3970 "Move cursor one line down in the window showing the table."
3971 (interactive)
3972 (org-table-fedit-move 'next-line))
3974 (defun org-table-fedit-move (command)
3975 "Move the cursor in the window showing the table.
3976 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3977 (let ((org-table-allow-automatic-line-recalculation nil)
3978 (pos org-pos) (win (selected-window)) p)
3979 (select-window (get-buffer-window (marker-buffer org-pos)))
3980 (setq p (point))
3981 (call-interactively command)
3982 (while (and (org-at-table-p)
3983 (org-at-table-hline-p))
3984 (call-interactively command))
3985 (or (org-at-table-p) (goto-char p))
3986 (move-marker pos (point))
3987 (select-window win)))
3989 (defun org-table-fedit-scroll (N)
3990 (interactive "p")
3991 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
3992 (scroll-other-window N)))
3994 (defun org-table-fedit-scroll-down (N)
3995 (interactive "p")
3996 (org-table-fedit-scroll (- N)))
3998 (defvar org-table-rectangle-overlays nil)
4000 (defun org-table-add-rectangle-overlay (beg end &optional face)
4001 "Add a new overlay."
4002 (let ((ov (make-overlay beg end)))
4003 (overlay-put ov 'face (or face 'secondary-selection))
4004 (push ov org-table-rectangle-overlays)))
4006 (defun org-table-highlight-rectangle (&optional beg end face)
4007 "Highlight rectangular region in a table."
4008 (setq beg (or beg (point)) end (or end (point)))
4009 (let ((b (min beg end))
4010 (e (max beg end))
4011 l1 c1 l2 c2 tmp)
4012 (and (boundp 'org-show-positions)
4013 (setq org-show-positions (cons b (cons e org-show-positions))))
4014 (goto-char (min beg end))
4015 (setq l1 (org-current-line)
4016 c1 (org-table-current-column))
4017 (goto-char (max beg end))
4018 (setq l2 (org-current-line)
4019 c2 (org-table-current-column))
4020 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
4021 (org-goto-line l1)
4022 (beginning-of-line 1)
4023 (loop for line from l1 to l2 do
4024 (when (looking-at org-table-dataline-regexp)
4025 (org-table-goto-column c1)
4026 (skip-chars-backward "^|\n") (setq beg (point))
4027 (org-table-goto-column c2)
4028 (skip-chars-forward "^|\n") (setq end (point))
4029 (org-table-add-rectangle-overlay beg end face))
4030 (beginning-of-line 2))
4031 (goto-char b))
4032 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
4034 (defun org-table-remove-rectangle-highlight (&rest ignore)
4035 "Remove the rectangle overlays."
4036 (unless org-inhibit-highlight-removal
4037 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
4038 (mapc 'delete-overlay org-table-rectangle-overlays)
4039 (setq org-table-rectangle-overlays nil)))
4041 (defvar org-table-coordinate-overlays nil
4042 "Collects the coordinate grid overlays, so that they can be removed.")
4043 (make-variable-buffer-local 'org-table-coordinate-overlays)
4045 (defun org-table-overlay-coordinates ()
4046 "Add overlays to the table at point, to show row/column coordinates."
4047 (interactive)
4048 (mapc 'delete-overlay org-table-coordinate-overlays)
4049 (setq org-table-coordinate-overlays nil)
4050 (save-excursion
4051 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
4052 (goto-char (org-table-begin))
4053 (while (org-at-table-p)
4054 (setq eol (point-at-eol))
4055 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
4056 (push ov org-table-coordinate-overlays)
4057 (setq hline (looking-at org-table-hline-regexp))
4058 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
4059 (format "%4d" (setq id (1+ id)))))
4060 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
4061 (when hline
4062 (setq ic 0)
4063 (while (re-search-forward "[+|]\\(-+\\)" eol t)
4064 (setq beg (1+ (match-beginning 0))
4065 ic (1+ ic)
4066 s1 (concat "$" (int-to-string ic))
4067 s2 (org-number-to-letters ic)
4068 str (if (eq org-table-use-standard-references t) s2 s1))
4069 (setq ov (make-overlay beg (+ beg (length str))))
4070 (push ov org-table-coordinate-overlays)
4071 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
4072 (beginning-of-line 2)))))
4074 ;;;###autoload
4075 (defun org-table-toggle-coordinate-overlays ()
4076 "Toggle the display of Row/Column numbers in tables."
4077 (interactive)
4078 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
4079 (message "Tables Row/Column numbers display turned %s"
4080 (if org-table-overlay-coordinates "on" "off"))
4081 (if (and (org-at-table-p) org-table-overlay-coordinates)
4082 (org-table-align))
4083 (unless org-table-overlay-coordinates
4084 (mapc 'delete-overlay org-table-coordinate-overlays)
4085 (setq org-table-coordinate-overlays nil)))
4087 ;;;###autoload
4088 (defun org-table-toggle-formula-debugger ()
4089 "Toggle the formula debugger in tables."
4090 (interactive)
4091 (setq org-table-formula-debug (not org-table-formula-debug))
4092 (message "Formula debugging has been turned %s"
4093 (if org-table-formula-debug "on" "off")))
4095 ;;; The orgtbl minor mode
4097 ;; Define a minor mode which can be used in other modes in order to
4098 ;; integrate the org-mode table editor.
4100 ;; This is really a hack, because the org-mode table editor uses several
4101 ;; keys which normally belong to the major mode, for example the TAB and
4102 ;; RET keys. Here is how it works: The minor mode defines all the keys
4103 ;; necessary to operate the table editor, but wraps the commands into a
4104 ;; function which tests if the cursor is currently inside a table. If that
4105 ;; is the case, the table editor command is executed. However, when any of
4106 ;; those keys is used outside a table, the function uses `key-binding' to
4107 ;; look up if the key has an associated command in another currently active
4108 ;; keymap (minor modes, major mode, global), and executes that command.
4109 ;; There might be problems if any of the keys used by the table editor is
4110 ;; otherwise used as a prefix key.
4112 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4113 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4114 ;; addresses this by checking explicitly for both bindings.
4116 ;; The optimized version (see variable `orgtbl-optimized') takes over
4117 ;; all keys which are bound to `self-insert-command' in the *global map*.
4118 ;; Some modes bind other commands to simple characters, for example
4119 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4120 ;; active, this binding is ignored inside tables and replaced with a
4121 ;; modified self-insert.
4124 (defvar orgtbl-mode-map (make-keymap)
4125 "Keymap for `orgtbl-mode'.")
4127 (defvar org-old-auto-fill-inhibit-regexp nil
4128 "Local variable used by `orgtbl-mode'.")
4130 (defconst orgtbl-line-start-regexp
4131 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4132 "Matches a line belonging to an orgtbl.")
4134 (defconst orgtbl-extra-font-lock-keywords
4135 (list (list (concat "^" orgtbl-line-start-regexp ".*")
4136 0 (quote 'org-table) 'prepend))
4137 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4139 ;; Install it as a minor mode.
4140 (put 'orgtbl-mode :included t)
4141 (put 'orgtbl-mode :menu-tag "Org Table Mode")
4143 ;;;###autoload
4144 (define-minor-mode orgtbl-mode
4145 "The `org-mode' table editor as a minor mode for use in other modes."
4146 :lighter " OrgTbl" :keymap orgtbl-mode-map
4147 (org-load-modules-maybe)
4148 (cond
4149 ((derived-mode-p 'org-mode)
4150 ;; Exit without error, in case some hook functions calls this
4151 ;; by accident in org-mode.
4152 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4153 (orgtbl-mode
4154 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
4155 ;; Make sure we are first in minor-mode-map-alist
4156 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
4157 ;; FIXME: maybe it should use emulation-mode-map-alists?
4158 (and c (setq minor-mode-map-alist
4159 (cons c (delq c minor-mode-map-alist)))))
4160 (org-set-local (quote org-table-may-need-update) t)
4161 (org-add-hook 'before-change-functions 'org-before-change-function
4162 nil 'local)
4163 (org-set-local 'org-old-auto-fill-inhibit-regexp
4164 auto-fill-inhibit-regexp)
4165 (org-set-local 'auto-fill-inhibit-regexp
4166 (if auto-fill-inhibit-regexp
4167 (concat orgtbl-line-start-regexp "\\|"
4168 auto-fill-inhibit-regexp)
4169 orgtbl-line-start-regexp))
4170 (add-to-invisibility-spec '(org-cwidth))
4171 (when (fboundp 'font-lock-add-keywords)
4172 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
4173 (org-restart-font-lock))
4174 (easy-menu-add orgtbl-mode-menu))
4176 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
4177 (org-table-cleanup-narrow-column-properties)
4178 (org-remove-from-invisibility-spec '(org-cwidth))
4179 (remove-hook 'before-change-functions 'org-before-change-function t)
4180 (when (fboundp 'font-lock-remove-keywords)
4181 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
4182 (org-restart-font-lock))
4183 (easy-menu-remove orgtbl-mode-menu)
4184 (force-mode-line-update 'all))))
4186 (defun org-table-cleanup-narrow-column-properties ()
4187 "Remove all properties related to narrow-column invisibility."
4188 (let ((s (point-min)))
4189 (while (setq s (text-property-any s (point-max)
4190 'display org-narrow-column-arrow))
4191 (remove-text-properties s (1+ s) '(display t)))
4192 (setq s (point-min))
4193 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
4194 (remove-text-properties s (1+ s) '(org-cwidth t)))
4195 (setq s (point-min))
4196 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
4197 (remove-text-properties s (1+ s) '(invisible t)))))
4199 (defun orgtbl-make-binding (fun n &rest keys)
4200 "Create a function for binding in the table minor mode.
4201 FUN is the command to call inside a table. N is used to create a unique
4202 command name. KEYS are keys that should be checked in for a command
4203 to execute outside of tables."
4204 (eval
4205 (list 'defun
4206 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
4207 '(arg)
4208 (concat "In tables, run `" (symbol-name fun) "'.\n"
4209 "Outside of tables, run the binding of `"
4210 (mapconcat #'key-description keys "' or `")
4211 "'.")
4212 '(interactive "p")
4213 (list 'if
4214 '(org-at-table-p)
4215 (list 'call-interactively (list 'quote fun))
4216 (list 'let '(orgtbl-mode)
4217 (list 'call-interactively
4218 (append '(or)
4219 (mapcar (lambda (k)
4220 (list 'key-binding k))
4221 keys)
4222 '('orgtbl-error))))))))
4224 (defun orgtbl-error ()
4225 "Error when there is no default binding for a table key."
4226 (interactive)
4227 (user-error "This key has no function outside tables"))
4229 (defun orgtbl-setup ()
4230 "Setup orgtbl keymaps."
4231 (let ((nfunc 0)
4232 (bindings
4233 '(([(meta shift left)] org-table-delete-column)
4234 ([(meta left)] org-table-move-column-left)
4235 ([(meta right)] org-table-move-column-right)
4236 ([(meta shift right)] org-table-insert-column)
4237 ([(meta shift up)] org-table-kill-row)
4238 ([(meta shift down)] org-table-insert-row)
4239 ([(meta up)] org-table-move-row-up)
4240 ([(meta down)] org-table-move-row-down)
4241 ("\C-c\C-w" org-table-cut-region)
4242 ("\C-c\M-w" org-table-copy-region)
4243 ("\C-c\C-y" org-table-paste-rectangle)
4244 ("\C-c\C-w" org-table-wrap-region)
4245 ("\C-c-" org-table-insert-hline)
4246 ("\C-c}" org-table-toggle-coordinate-overlays)
4247 ("\C-c{" org-table-toggle-formula-debugger)
4248 ("\C-m" org-table-next-row)
4249 ([(shift return)] org-table-copy-down)
4250 ("\C-c?" org-table-field-info)
4251 ("\C-c " org-table-blank-field)
4252 ("\C-c+" org-table-sum)
4253 ("\C-c=" org-table-eval-formula)
4254 ("\C-c'" org-table-edit-formulas)
4255 ("\C-c`" org-table-edit-field)
4256 ("\C-c*" org-table-recalculate)
4257 ("\C-c^" org-table-sort-lines)
4258 ("\M-a" org-table-beginning-of-field)
4259 ("\M-e" org-table-end-of-field)
4260 ([(control ?#)] org-table-rotate-recalc-marks)))
4261 elt key fun cmd)
4262 (while (setq elt (pop bindings))
4263 (setq nfunc (1+ nfunc))
4264 (setq key (org-key (car elt))
4265 fun (nth 1 elt)
4266 cmd (orgtbl-make-binding fun nfunc key))
4267 (org-defkey orgtbl-mode-map key cmd))
4269 ;; Special treatment needed for TAB and RET
4270 (org-defkey orgtbl-mode-map [(return)]
4271 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
4272 (org-defkey orgtbl-mode-map "\C-m"
4273 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
4275 (org-defkey orgtbl-mode-map [(tab)]
4276 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
4277 (org-defkey orgtbl-mode-map "\C-i"
4278 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
4280 (org-defkey orgtbl-mode-map [(shift tab)]
4281 (orgtbl-make-binding 'org-table-previous-field 104
4282 [(shift tab)] [(tab)] "\C-i"))
4285 (unless (featurep 'xemacs)
4286 (org-defkey orgtbl-mode-map [S-iso-lefttab]
4287 (orgtbl-make-binding 'org-table-previous-field 107
4288 [S-iso-lefttab] [backtab] [(shift tab)]
4289 [(tab)] "\C-i")))
4291 (org-defkey orgtbl-mode-map [backtab]
4292 (orgtbl-make-binding 'org-table-previous-field 108
4293 [backtab] [S-iso-lefttab] [(shift tab)]
4294 [(tab)] "\C-i"))
4296 (org-defkey orgtbl-mode-map "\M-\C-m"
4297 (orgtbl-make-binding 'org-table-wrap-region 105
4298 "\M-\C-m" [(meta return)]))
4299 (org-defkey orgtbl-mode-map [(meta return)]
4300 (orgtbl-make-binding 'org-table-wrap-region 106
4301 [(meta return)] "\M-\C-m"))
4303 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4304 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4306 (when orgtbl-optimized
4307 ;; If the user wants maximum table support, we need to hijack
4308 ;; some standard editing functions
4309 (org-remap orgtbl-mode-map
4310 'self-insert-command 'orgtbl-self-insert-command
4311 'delete-char 'org-delete-char
4312 'delete-backward-char 'org-delete-backward-char)
4313 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4314 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4315 '("OrgTbl"
4316 ["Create or convert" org-table-create-or-convert-from-region
4317 :active (not (org-at-table-p)) :keys "C-c |" ]
4318 "--"
4319 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4320 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4321 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4322 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4323 "--"
4324 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4325 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4326 ["Copy Field from Above"
4327 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4328 "--"
4329 ("Column"
4330 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4331 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4332 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4333 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4334 ("Row"
4335 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4336 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4337 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4338 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4339 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4340 "--"
4341 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4342 ("Rectangle"
4343 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4344 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4345 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4346 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4347 "--"
4348 ("Radio tables"
4349 ["Insert table template" orgtbl-insert-radio-table
4350 (assq major-mode orgtbl-radio-table-templates)]
4351 ["Comment/uncomment table" orgtbl-toggle-comment t])
4352 "--"
4353 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4354 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4355 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4356 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4357 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4358 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4359 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4360 ["Sum Column/Rectangle" org-table-sum
4361 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4362 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4363 ["Debug Formulas"
4364 org-table-toggle-formula-debugger :active (org-at-table-p)
4365 :keys "C-c {"
4366 :style toggle :selected org-table-formula-debug]
4367 ["Show Col/Row Numbers"
4368 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4369 :keys "C-c }"
4370 :style toggle :selected org-table-overlay-coordinates]
4371 "--"
4372 ("Plot"
4373 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4374 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4377 (defun orgtbl-ctrl-c-ctrl-c (arg)
4378 "If the cursor is inside a table, realign the table.
4379 If it is a table to be sent away to a receiver, do it.
4380 With prefix arg, also recompute table."
4381 (interactive "P")
4382 (let ((case-fold-search t) (pos (point)) action)
4383 (save-excursion
4384 (beginning-of-line 1)
4385 (setq action (cond
4386 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4387 ((looking-at "[ \t]*|") pos)
4388 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4389 (cond
4390 ((integerp action)
4391 (goto-char action)
4392 (org-table-maybe-eval-formula)
4393 (if arg
4394 (call-interactively 'org-table-recalculate)
4395 (org-table-maybe-recalculate-line))
4396 (call-interactively 'org-table-align)
4397 (when (orgtbl-send-table 'maybe)
4398 (run-hooks 'orgtbl-after-send-table-hook)))
4399 ((eq action 'recalc)
4400 (save-excursion
4401 (beginning-of-line 1)
4402 (skip-chars-backward " \r\n\t")
4403 (if (org-at-table-p)
4404 (org-call-with-arg 'org-table-recalculate t))))
4405 (t (let (orgtbl-mode)
4406 (call-interactively (key-binding "\C-c\C-c")))))))
4408 (defun orgtbl-create-or-convert-from-region (arg)
4409 "Create table or convert region to table, if no conflicting binding.
4410 This installs the table binding `C-c |', but only if there is no
4411 conflicting binding to this key outside orgtbl-mode."
4412 (interactive "P")
4413 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4414 (if cmd
4415 (call-interactively cmd)
4416 (call-interactively 'org-table-create-or-convert-from-region))))
4418 (defun orgtbl-tab (arg)
4419 "Justification and field motion for `orgtbl-mode'."
4420 (interactive "P")
4421 (if arg (org-table-edit-field t)
4422 (org-table-justify-field-maybe)
4423 (org-table-next-field)))
4425 (defun orgtbl-ret ()
4426 "Justification and field motion for `orgtbl-mode'."
4427 (interactive)
4428 (if (bobp)
4429 (newline)
4430 (org-table-justify-field-maybe)
4431 (org-table-next-row)))
4433 (defun orgtbl-self-insert-command (N)
4434 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4435 If the cursor is in a table looking at whitespace, the whitespace is
4436 overwritten, and the table is not marked as requiring realignment."
4437 (interactive "p")
4438 (if (and (org-at-table-p)
4440 (and org-table-auto-blank-field
4441 (member last-command
4442 '(orgtbl-hijacker-command-100
4443 orgtbl-hijacker-command-101
4444 orgtbl-hijacker-command-102
4445 orgtbl-hijacker-command-103
4446 orgtbl-hijacker-command-104
4447 orgtbl-hijacker-command-105
4448 yas/expand))
4449 (org-table-blank-field))
4451 (eq N 1)
4452 (looking-at "[^|\n]* +|"))
4453 (let (org-table-may-need-update)
4454 (goto-char (1- (match-end 0)))
4455 (org-delete-backward-char 1)
4456 (goto-char (match-beginning 0))
4457 (self-insert-command N))
4458 (setq org-table-may-need-update t)
4459 (let* (orgtbl-mode
4461 (cmd (or (key-binding
4462 (or (and (listp function-key-map)
4463 (setq a (assoc last-input-event function-key-map))
4464 (cdr a))
4465 (vector last-input-event)))
4466 'self-insert-command)))
4467 (call-interactively cmd)
4468 (if (and org-self-insert-cluster-for-undo
4469 (eq cmd 'self-insert-command))
4470 (if (not (eq last-command 'orgtbl-self-insert-command))
4471 (setq org-self-insert-command-undo-counter 1)
4472 (if (>= org-self-insert-command-undo-counter 20)
4473 (setq org-self-insert-command-undo-counter 1)
4474 (and (> org-self-insert-command-undo-counter 0)
4475 buffer-undo-list
4476 (not (cadr buffer-undo-list)) ; remove nil entry
4477 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4478 (setq org-self-insert-command-undo-counter
4479 (1+ org-self-insert-command-undo-counter))))))))
4481 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4482 "Regular expression matching exponentials as produced by calc.")
4484 (defun orgtbl-gather-send-defs ()
4485 "Gather a plist of :name, :transform, :params for each destination before
4486 a radio table."
4487 (save-excursion
4488 (goto-char (org-table-begin))
4489 (let (rtn)
4490 (beginning-of-line 0)
4491 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4492 (let ((name (org-no-properties (match-string 1)))
4493 (transform (intern (match-string 2)))
4494 (params (if (match-end 3)
4495 (read (concat "(" (match-string 3) ")")))))
4496 (push (list :name name :transform transform :params params)
4497 rtn)
4498 (beginning-of-line 0)))
4499 rtn)))
4501 (defun orgtbl-send-replace-tbl (name txt)
4502 "Find and replace table NAME with TXT."
4503 (save-excursion
4504 (goto-char (point-min))
4505 (unless (re-search-forward
4506 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4507 (user-error "Don't know where to insert translated table"))
4508 (let ((beg (line-beginning-position 2)))
4509 (unless (re-search-forward
4510 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4511 (user-error "Cannot find end of insertion region"))
4512 (beginning-of-line)
4513 (delete-region beg (point)))
4514 (insert txt "\n")))
4516 ;;;###autoload
4517 (defun org-table-to-lisp (&optional txt)
4518 "Convert the table at point to a Lisp structure.
4519 The structure will be a list. Each item is either the symbol `hline'
4520 for a horizontal separator line, or a list of field values as strings.
4521 The table is taken from the parameter TXT, or from the buffer at point."
4522 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4523 (let ((txt (or txt
4524 (buffer-substring-no-properties (org-table-begin)
4525 (org-table-end)))))
4526 (mapcar (lambda (x)
4527 (if (string-match org-table-hline-regexp x) 'hline
4528 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4529 (org-split-string txt "[ \t]*\n[ \t]*"))))
4531 (defun orgtbl-send-table (&optional maybe)
4532 "Send a transformed version of table at point to the receiver position.
4533 With argument MAYBE, fail quietly if no transformation is defined
4534 for this table."
4535 (interactive)
4536 (catch 'exit
4537 (unless (org-at-table-p) (user-error "Not at a table"))
4538 ;; when non-interactive, we assume align has just happened.
4539 (when (org-called-interactively-p 'any) (org-table-align))
4540 (let ((dests (orgtbl-gather-send-defs))
4541 (table (org-table-to-lisp
4542 (buffer-substring-no-properties (org-table-begin)
4543 (org-table-end))))
4544 (ntbl 0))
4545 (unless dests
4546 (if maybe (throw 'exit nil)
4547 (user-error "Don't know how to transform this table")))
4548 (dolist (dest dests)
4549 (let ((name (plist-get dest :name))
4550 (transform (plist-get dest :transform))
4551 (params (plist-get dest :params)))
4552 (unless (fboundp transform)
4553 (user-error "No such transformation function %s" transform))
4554 (orgtbl-send-replace-tbl name (funcall transform table params)))
4555 (incf ntbl))
4556 (message "Table converted and installed at %d receiver location%s"
4557 ntbl (if (> ntbl 1) "s" ""))
4558 (and (> ntbl 0) ntbl))))
4560 (defun org-remove-by-index (list indices &optional i0)
4561 "Remove the elements in LIST with indices in INDICES.
4562 First element has index 0, or I0 if given."
4563 (if (not indices)
4564 list
4565 (if (integerp indices) (setq indices (list indices)))
4566 (setq i0 (1- (or i0 0)))
4567 (delq :rm (mapcar (lambda (x)
4568 (setq i0 (1+ i0))
4569 (if (memq i0 indices) :rm x))
4570 list))))
4572 (defun orgtbl-toggle-comment ()
4573 "Comment or uncomment the orgtbl at point."
4574 (interactive)
4575 (let* ((case-fold-search t)
4576 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4577 (re2 (concat "^" orgtbl-line-start-regexp))
4578 (commented (save-excursion (beginning-of-line 1)
4579 (cond ((looking-at re1) t)
4580 ((looking-at re2) nil)
4581 (t (user-error "Not at an org table")))))
4582 (re (if commented re1 re2))
4583 beg end)
4584 (save-excursion
4585 (beginning-of-line 1)
4586 (while (looking-at re) (beginning-of-line 0))
4587 (beginning-of-line 2)
4588 (setq beg (point))
4589 (while (looking-at re) (beginning-of-line 2))
4590 (setq end (point)))
4591 (comment-region beg end (if commented '(4) nil))))
4593 (defun orgtbl-insert-radio-table ()
4594 "Insert a radio table template appropriate for this major mode."
4595 (interactive)
4596 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4597 (txt (nth 1 e))
4598 name pos)
4599 (unless e (user-error "No radio table setup defined for %s" major-mode))
4600 (setq name (read-string "Table name: "))
4601 (while (string-match "%n" txt)
4602 (setq txt (replace-match name t t txt)))
4603 (or (bolp) (insert "\n"))
4604 (setq pos (point))
4605 (insert txt)
4606 (goto-char pos)))
4608 ;;;###autoload
4609 (defun orgtbl-to-generic (table params)
4610 "Convert the orgtbl-mode TABLE to some other format.
4612 This generic routine can be used for many standard cases.
4614 TABLE is a list, each entry either the symbol `hline' for
4615 a horizontal separator line, or a list of fields for that
4616 line. PARAMS is a property list of parameters that can
4617 influence the conversion.
4619 Valid parameters are:
4621 :backend, :raw
4623 Export back-end used as a basis to transcode elements of the
4624 table, when no specific parameter applies to it. It is also
4625 used to translate cells contents. You can prevent this by
4626 setting :raw property to a non-nil value.
4628 :splice
4630 When non-nil, only convert rows, not the table itself. This is
4631 equivalent to setting to the empty string both :tstart
4632 and :tend, which see.
4634 :skip
4636 When set to an integer N, skip the first N lines of the table.
4637 Horizontal separation lines do count for this parameter!
4639 :skipcols
4641 List of columns that should be skipped. If the table has
4642 a column with calculation marks, that column is automatically
4643 discarded beforehand.
4645 :hline
4647 String to be inserted on horizontal separation lines. May be
4648 nil to ignore these lines altogether.
4650 :sep
4652 Separator between two fields, as a string.
4654 Each in the following group may be either a string or a function
4655 of no arguments returning a string:
4657 :tstart, :tend
4659 Strings to start and end the table. Ignored when :splice is t.
4661 :lstart, :lend
4663 Strings to start and end a new table line.
4665 :llstart, :llend
4667 Strings to start and end the last table line. Default,
4668 respectively, to :lstart and :lend.
4670 Each in the following group may be a string or a function of one
4671 argument (either the cells in the current row, as a list of
4672 strings, or the current cell) returning a string:
4674 :lfmt
4676 Format string for an entire row, with enough %s to capture all
4677 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4679 :llfmt
4681 Format for the entire last line, defaults to :lfmt.
4683 :fmt
4685 A format to be used to wrap the field, should contain %s for
4686 the original field value. For example, to wrap everything in
4687 dollars, you could use :fmt \"$%s$\". This may also be
4688 a property list with column numbers and format strings, or
4689 functions, e.g.,
4691 \(:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4693 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4695 Same as above, specific for the header lines in the table.
4696 All lines before the first hline are treated as header. If
4697 any of these is not present, the data line value is used.
4699 This may be either a string or a function of two arguments:
4701 :efmt
4703 Use this format to print numbers with exponential. The format
4704 should have %s twice for inserting mantissa and exponent, for
4705 example \"%s\\\\times10^{%s}\". This may also be a property
4706 list with column numbers and format strings or functions.
4707 :fmt will still be applied after :efmt."
4708 (let ((backend (plist-get params :backend)))
4709 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4710 (user-error "Unknown :backend value"))
4711 (when (or (not backend) (plist-get params :raw)) (require 'ox-org))
4712 (org-trim
4713 (org-export-string-as
4714 ;; Return TABLE as Org syntax. Tolerate non-string cells.
4715 (with-output-to-string
4716 (dolist (e table)
4717 (cond ((eq e 'hline) (princ "|--\n"))
4718 ((consp e)
4719 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4720 (princ "\n")))))
4721 ;; Build a custom back-end according to PARAMS. Before defining
4722 ;; a translator, check if there is anything to do. When there
4723 ;; isn't, let BACKEND handle the element.
4724 (org-export-create-backend
4725 :parent (or backend 'org)
4726 :filters
4727 '((:filter-parse-tree
4728 ;; Handle :skip parameter.
4729 (lambda (tree backend info)
4730 (let ((skip (plist-get info :skip)))
4731 (when skip
4732 (unless (wholenump skip) (user-error "Wrong :skip value"))
4733 (let ((n 0))
4734 (org-element-map tree 'table-row
4735 (lambda (row)
4736 (if (>= n skip) t
4737 (org-element-extract-element row)
4738 (incf n)
4739 nil))
4740 info t))
4741 tree)))
4742 ;; Handle :skipcols parameter.
4743 (lambda (tree backend info)
4744 (let ((skipcols (plist-get info :skipcols)))
4745 (when skipcols
4746 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4747 (org-element-map tree 'table
4748 (lambda (table)
4749 (let ((specialp
4750 (org-export-table-has-special-column-p table)))
4751 (dolist (row (org-element-contents table))
4752 (when (eq (org-element-property :type row) 'standard)
4753 (let ((c 1))
4754 (dolist (cell (nthcdr (if specialp 1 0)
4755 (org-element-contents row)))
4756 (when (memq c skipcols)
4757 (org-element-extract-element cell))
4758 (incf c)))))))
4759 info)
4760 tree)))))
4761 :transcoders
4762 `((table . ,(org-table--to-generic-table params))
4763 (table-row . ,(org-table--to-generic-row params))
4764 (table-cell . ,(org-table--to-generic-cell params))
4765 ;; Section. Return contents to avoid garbage around table.
4766 (section . (lambda (s c i) c))))
4767 'body-only (org-combine-plists params '(:with-tables t))))))
4769 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4770 (cond ((null value) nil)
4771 ((functionp value) `(funcall ',value ,@args))
4772 ((stringp value)
4773 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4774 (args `(format ,value ,@args))
4775 (t value)))
4776 ((and with-cons (consp value))
4777 `(let ((val (cadr (memq column ',value))))
4778 (cond ((null val) contents)
4779 ((stringp val) (format val ,@args))
4780 ((functionp val) (funcall val ,@args))
4781 (t (user-error "Wrong %s value" ,name)))))
4782 (t (user-error "Wrong %s value" name))))
4784 (defun org-table--to-generic-table (params)
4785 "Return custom table transcoder according to PARAMS.
4786 PARAMS is a plist. See `orgtbl-to-generic' for more
4787 information."
4788 (let ((backend (plist-get params :backend))
4789 (splice (plist-get params :splice))
4790 (tstart (plist-get params :tstart))
4791 (tend (plist-get params :tend)))
4792 `(lambda (table contents info)
4793 (concat
4794 ,(and tstart (not splice)
4795 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
4796 ,(if (or (not backend) tstart tend splice) 'contents
4797 `(org-export-with-backend ',backend table contents info))
4798 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
4800 (defun org-table--to-generic-row (params)
4801 "Return custom table row transcoder according to PARAMS.
4802 PARAMS is a plist. See `orgtbl-to-generic' for more
4803 information."
4804 (let* ((backend (plist-get params :backend))
4805 (lstart (plist-get params :lstart))
4806 (llstart (plist-get params :llstart))
4807 (hlstart (plist-get params :hlstart))
4808 (hllstart (plist-get params :hllstart))
4809 (lend (plist-get params :lend))
4810 (llend (plist-get params :llend))
4811 (hlend (plist-get params :hlend))
4812 (hllend (plist-get params :hllend))
4813 (lfmt (plist-get params :lfmt))
4814 (llfmt (plist-get params :llfmt))
4815 (hlfmt (plist-get params :hlfmt))
4816 (hllfmt (plist-get params :hllfmt)))
4817 `(lambda (row contents info)
4818 (if (eq (org-element-property :type row) 'rule)
4819 ,(cond
4820 ((plist-member params :hline)
4821 (org-table--generic-apply (plist-get params :hline) ":hline"))
4822 (backend `(org-export-with-backend ',backend row nil info)))
4823 (let ((headerp (org-export-table-row-in-header-p row info))
4824 (lastp (not (org-export-get-next-element row info)))
4825 (last-header-p (org-export-table-row-ends-header-p row info)))
4826 (when contents
4827 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
4828 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
4829 ;; `:lstart', `:lend' and their relatives.
4830 ,(let ((cells
4831 '(org-element-map row 'table-cell
4832 (lambda (cell)
4833 ;; Export all cells, without separators.
4835 ;; Use `org-export-data-with-backend'
4836 ;; instead of `org-export-data' to eschew
4837 ;; cached values, which
4838 ;; ignore :orgtbl-ignore-sep parameter.
4839 (org-export-data-with-backend
4840 cell
4841 (plist-get info :back-end)
4842 (org-combine-plists info '(:orgtbl-ignore-sep t))))
4843 info)))
4844 `(cond
4845 ,(and hllfmt
4846 `(last-header-p ,(org-table--generic-apply
4847 hllfmt ":hllfmt" nil cells)))
4848 ,(and hlfmt
4849 `(headerp ,(org-table--generic-apply
4850 hlfmt ":hlfmt" nil cells)))
4851 ,(and llfmt
4852 `(lastp ,(org-table--generic-apply
4853 llfmt ":llfmt" nil cells)))
4855 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
4856 `(concat
4857 (cond
4858 ,(and
4859 (or hllstart hllend)
4860 `(last-header-p
4861 (concat
4862 ,(org-table--generic-apply hllstart ":hllstart")
4863 contents
4864 ,(org-table--generic-apply hllend ":hllend"))))
4865 ,(and
4866 (or hlstart hlend)
4867 `(headerp
4868 (concat
4869 ,(org-table--generic-apply hlstart ":hlstart")
4870 contents
4871 ,(org-table--generic-apply hlend ":hlend"))))
4872 ,(and
4873 (or llstart llend)
4874 `(lastp
4875 (concat
4876 ,(org-table--generic-apply llstart ":llstart")
4877 contents
4878 ,(org-table--generic-apply llend ":llend"))))
4880 ,(cond
4881 ((or lstart lend)
4882 `(concat
4883 ,(org-table--generic-apply lstart ":lstart")
4884 contents
4885 ,(org-table--generic-apply lend ":lend")))
4886 (backend
4887 `(org-export-with-backend
4888 ',backend row contents info))
4889 (t 'contents)))))))))))))))
4891 (defun org-table--to-generic-cell (params)
4892 "Return custom table cell transcoder according to PARAMS.
4893 PARAMS is a plist. See `orgtbl-to-generic' for more
4894 information."
4895 (let* ((backend (plist-get params :backend))
4896 (efmt (plist-get params :efmt))
4897 (fmt (plist-get params :fmt))
4898 (hfmt (plist-get params :hfmt))
4899 (sep (plist-get params :sep))
4900 (hsep (plist-get params :hsep)))
4901 `(lambda (cell contents info)
4902 (let ((headerp (org-export-table-row-in-header-p
4903 (org-export-get-parent-element cell) info))
4904 (column (1+ (cdr (org-export-table-cell-address cell info)))))
4905 ;; Make sure that contents are exported as Org data when :raw
4906 ;; parameter is non-nil.
4907 ,(when (and backend (plist-get params :raw))
4908 `(setq contents
4909 ;; Since we don't know what are the pseudo object
4910 ;; types defined in backend, we cannot pass them to
4911 ;; `org-element-interpret-data'. As a consequence,
4912 ;; they will be treated as pseudo elements, and
4913 ;; will have newlines appended instead of spaces.
4914 ;; Therefore, we must make sure :post-blank value
4915 ;; is really turned into spaces.
4916 (replace-regexp-in-string
4917 "\n" " "
4918 (org-trim
4919 (org-element-interpret-data
4920 (org-element-contents cell))))))
4921 (when contents
4922 ;; Check if we can apply `:efmt' on CONTENTS.
4923 ,(when efmt
4924 `(when (string-match orgtbl-exp-regexp contents)
4925 (let ((mantissa (match-string 1 contents))
4926 (exponent (match-string 2 contents)))
4927 (setq contents ,(org-table--generic-apply
4928 efmt ":efmt" t 'mantissa 'exponent)))))
4929 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
4930 (cond
4931 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
4932 hfmt ":hfmt" t 'contents))))
4933 ,(and fmt `(t (setq contents ,(org-table--generic-apply
4934 fmt ":fmt" t 'contents))))))
4935 ;; If a separator is provided, use it instead of BACKEND's.
4936 ;; Separators are ignored when LFMT (or equivalent) is
4937 ;; provided.
4938 ,(cond
4939 ((or hsep sep)
4940 `(if (or ,(and (not sep) '(not headerp))
4941 (plist-get info :orgtbl-ignore-sep)
4942 (not (org-export-get-next-element cell info)))
4943 ,(if (not backend) 'contents
4944 `(org-export-with-backend ',backend cell contents info))
4945 (concat contents
4946 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
4947 (or hsep sep)))))
4948 (backend `(org-export-with-backend ',backend cell contents info))
4949 (t 'contents))))))
4951 ;;;###autoload
4952 (defun orgtbl-to-tsv (table params)
4953 "Convert the orgtbl-mode table to TAB separated material."
4954 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4956 ;;;###autoload
4957 (defun orgtbl-to-csv (table params)
4958 "Convert the orgtbl-mode table to CSV material.
4959 This does take care of the proper quoting of fields with comma or quotes."
4960 (orgtbl-to-generic table
4961 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
4962 params)))
4964 ;;;###autoload
4965 (defun orgtbl-to-latex (table params)
4966 "Convert the orgtbl-mode TABLE to LaTeX.
4968 TABLE is a list, each entry either the symbol `hline' for
4969 a horizontal separator line, or a list of fields for that line.
4970 PARAMS is a property list of parameters that can influence the
4971 conversion. All parameters from `orgtbl-to-generic' are
4972 supported. It is also possible to use the following ones:
4974 :booktabs
4976 When non-nil, use formal \"booktabs\" style.
4978 :environment
4980 Specify environment to use, as a string. If you use
4981 \"longtable\", you may also want to specify :language property,
4982 as a string, to get proper continuation strings."
4983 (require 'ox-latex)
4984 (orgtbl-to-generic
4985 table
4986 (org-combine-plists
4987 ;; Provide sane default values.
4988 (list :backend 'latex
4989 :latex-default-table-mode 'table
4990 :latex-tables-centered nil
4991 :latex-tables-booktabs (plist-get params :booktabs)
4992 :latex-table-scientific-notation nil
4993 :latex-default-table-environment
4994 (or (plist-get params :environment) "tabular"))
4995 params)))
4997 ;;;###autoload
4998 (defun orgtbl-to-html (table params)
4999 "Convert the orgtbl-mode TABLE to HTML.
5001 TABLE is a list, each entry either the symbol `hline' for
5002 a horizontal separator line, or a list of fields for that line.
5003 PARAMS is a property list of parameters that can influence the
5004 conversion. All parameters from `orgtbl-to-generic' are
5005 supported. It is also possible to use the following one:
5007 :attributes
5009 Attributes and values, as a plist, which will be used in
5010 <table> tag."
5011 (require 'ox-html)
5012 (orgtbl-to-generic
5013 table
5014 (org-combine-plists
5015 ;; Provide sane default values.
5016 (list :backend 'html
5017 :html-table-data-tags '("<td%s>" . "</td>")
5018 :html-table-use-header-tags-for-first-column nil
5019 :html-table-align-individual-fields t
5020 :html-table-row-tags '("<tr>" . "</tr>")
5021 :html-table-attributes
5022 (if (plist-member params :attributes)
5023 (plist-get params :attributes)
5024 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5025 :frame "hsides")))
5026 params)))
5028 ;;;###autoload
5029 (defun orgtbl-to-texinfo (table params)
5030 "Convert the orgtbl-mode TABLE to Texinfo.
5032 TABLE is a list, each entry either the symbol `hline' for
5033 a horizontal separator line, or a list of fields for that line.
5034 PARAMS is a property list of parameters that can influence the
5035 conversion. All parameters from `orgtbl-to-generic' are
5036 supported. It is also possible to use the following one:
5038 :columns
5040 Column widths, as a string. When providing column fractions,
5041 \"@columnfractions\" command can be omitted."
5042 (require 'ox-texinfo)
5043 (let ((output
5044 (orgtbl-to-generic
5045 table
5046 (org-combine-plists
5047 (list :backend 'texinfo
5048 :texinfo-tables-verbatim nil
5049 :texinfo-table-scientific-notation nil)
5050 params)))
5051 (columns (let ((w (plist-get params :columns)))
5052 (cond ((not w) nil)
5053 ((org-string-match-p "{\\|@columnfractions " w) w)
5054 (t (concat "@columnfractions " w))))))
5055 (if (not columns) output
5056 (replace-regexp-in-string
5057 "@multitable \\(.*\\)" columns output t nil 1))))
5059 ;;;###autoload
5060 (defun orgtbl-to-orgtbl (table params)
5061 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5063 TABLE is a list, each entry either the symbol `hline' for
5064 a horizontal separator line, or a list of fields for that line.
5065 PARAMS is a property list of parameters that can influence the
5066 conversion. All parameters from `orgtbl-to-generic' are
5067 supported.
5069 Useful when slicing one table into many. The :hline, :sep,
5070 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5071 be set to provide ORGTBL directives for the generated table."
5072 (require 'ox-org)
5073 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5075 (defun orgtbl-to-table.el (table params)
5076 "Convert the orgtbl-mode TABLE into a table.el table.
5077 TABLE is a list, each entry either the symbol `hline' for
5078 a horizontal separator line, or a list of fields for that line.
5079 PARAMS is a property list of parameters that can influence the
5080 conversion. All parameters from `orgtbl-to-generic' are
5081 supported."
5082 (with-temp-buffer
5083 (insert (orgtbl-to-orgtbl table params))
5084 (org-table-align)
5085 (replace-regexp-in-string
5086 "-|" "-+"
5087 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5089 (defun orgtbl-to-unicode (table params)
5090 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5092 TABLE is a list, each entry either the symbol `hline' for
5093 a horizontal separator line, or a list of fields for that line.
5094 PARAMS is a property list of parameters that can influence the
5095 conversion. All parameters from `orgtbl-to-generic' are
5096 supported. It is also possible to use the following ones:
5098 :ascii-art
5100 When non-nil, use \"ascii-art-to-unicode\" package to translate
5101 the table. You can download it here:
5102 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5104 :narrow
5106 When non-nil, narrow columns width than provided width cookie,
5107 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5108 (require 'ox-ascii)
5109 (orgtbl-to-generic
5110 table
5111 (org-combine-plists
5112 (list :backend 'ascii
5113 :ascii-charset 'utf-8
5114 :ascii-table-keep-all-vertical-lines (plist-get params :)
5115 :ascii-table-widen-columns (not (plist-get params :narrow))
5116 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5117 params)))
5119 ;; Put the cursor in a column containing numerical values
5120 ;; of an Org-Mode table,
5121 ;; type C-c " a
5122 ;; A new column is added with a bar plot.
5123 ;; When the table is refreshed (C-u C-c *),
5124 ;; the plot is updated to reflect the new values.
5126 (defun orgtbl-ascii-draw (value min max &optional width characters)
5127 "Draw an ascii bar in a table.
5128 VALUE is a the value to plot, the width of the bar to draw. A
5129 value equal to MIN will be displayed as empty (zero width bar).
5130 A value equal to MAX will draw a bar filling all the WIDTH.
5131 WIDTH is the expected width in characters of the column.
5132 CHARACTERS is a string that will compose the bar, with shades of
5133 grey from pure white to pure black. It defaults to a 10
5134 characters string of regular ascii characters."
5135 (let* ((characters (or characters " .:;c!lhVHW"))
5136 (width (or width 12))
5137 (value (if (numberp value) value (string-to-number value)))
5138 (value (* (/ (- (+ value 0.0) min) (- max min)) width)))
5139 (cond
5140 ((< value 0) "too small")
5141 ((> value width) "too large")
5143 (let ((len (1- (length characters))))
5144 (concat
5145 (make-string (floor value) (elt characters len))
5146 (string (elt characters
5147 (floor (* (- value (floor value)) len))))))))))
5149 ;;;###autoload
5150 (defun orgtbl-ascii-plot (&optional ask)
5151 "Draw an ascii bar plot in a column.
5152 With cursor in a column containing numerical values, this
5153 function will draw a plot in a new column.
5154 ASK, if given, is a numeric prefix to override the default 12
5155 characters width of the plot. ASK may also be the
5156 \\[universal-argument] prefix, which will prompt for the width."
5157 (interactive "P")
5158 (let ((col (org-table-current-column))
5159 (min 1e999) ; 1e999 will be converted to infinity
5160 (max -1e999) ; which is the desired result
5161 (table (org-table-to-lisp))
5162 (length
5163 (cond ((consp ask)
5164 (read-number "Length of column " 12))
5165 ((numberp ask) ask)
5166 (t 12))))
5167 ;; Skip any hline a the top of table.
5168 (while (eq (car table) 'hline) (setq table (cdr table)))
5169 ;; Skip table header if any.
5170 (dolist (x (or (cdr (memq 'hline table)) table))
5171 (when (consp x)
5172 (setq x (nth (1- col) x))
5173 (when (string-match
5174 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5176 (setq x (string-to-number x))
5177 (when (> min x) (setq min x))
5178 (when (< max x) (setq max x)))))
5179 (org-table-insert-column)
5180 (org-table-move-column-right)
5181 (org-table-store-formulas
5182 (cons
5183 (cons
5184 (number-to-string (1+ col))
5185 (format "'(%s $%s %s %s %s)"
5186 "orgtbl-ascii-draw" col min max length))
5187 (org-table-get-stored-formulas)))
5188 (org-table-recalculate t)))
5190 ;; Example of extension: unicode characters
5191 ;; Here are two examples of different styles.
5193 ;; Unicode block characters are used to give a smooth effect.
5194 ;; See http://en.wikipedia.org/wiki/Block_Elements
5195 ;; Use one of those drawing functions
5196 ;; - orgtbl-ascii-draw (the default ascii)
5197 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5198 ;; - orgtbl-uc-draw-cont (smooth unicode)
5200 ;; This is best viewed with the "DejaVu Sans Mono" font
5201 ;; (use M-x set-default-font).
5203 (defun orgtbl-uc-draw-grid (value min max &optional width)
5204 "Draw a bar in a table using block unicode characters.
5205 It is a variant of orgtbl-ascii-draw with Unicode block
5206 characters, for a smooth display. Bars appear as grids (to the
5207 extent the font allows)."
5208 ;; http://en.wikipedia.org/wiki/Block_Elements
5209 ;; best viewed with the "DejaVu Sans Mono" font.
5210 (orgtbl-ascii-draw value min max width
5211 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5213 (defun orgtbl-uc-draw-cont (value min max &optional width)
5214 "Draw a bar in a table using block unicode characters.
5215 It is a variant of orgtbl-ascii-draw with Unicode block
5216 characters, for a smooth display. Bars are solid (to the extent
5217 the font allows)."
5218 (orgtbl-ascii-draw value min max width
5219 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5221 (defun org-table-get-remote-range (name-or-id form)
5222 "Get a field value or a list of values in a range from table at ID.
5224 NAME-OR-ID may be the name of a table in the current file as set
5225 by a \"#+NAME:\" directive. The first table following this line
5226 will then be used. Alternatively, it may be an ID referring to
5227 any entry, also in a different file. In this case, the first
5228 table in that entry will be referenced.
5229 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5230 \"@I$2..@II$2\". All the references must be absolute, not relative.
5232 The return value is either a single string for a single field, or a
5233 list of the fields in the rectangle."
5234 (save-match-data
5235 (let ((case-fold-search t) (id-loc nil)
5236 ;; Protect a bunch of variables from being overwritten
5237 ;; by the context of the remote table
5238 org-table-column-names org-table-column-name-regexp
5239 org-table-local-parameters org-table-named-field-locations
5240 org-table-current-line-types org-table-current-begin-line
5241 org-table-current-begin-pos org-table-dlines
5242 org-table-current-ncol
5243 org-table-hlines org-table-last-alignment
5244 org-table-last-column-widths org-table-last-alignment
5245 org-table-last-column-widths tbeg
5246 buffer loc)
5247 (setq form (org-table-convert-refs-to-rc form))
5248 (save-excursion
5249 (save-restriction
5250 (widen)
5251 (save-excursion
5252 (goto-char (point-min))
5253 (if (re-search-forward
5254 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5255 (regexp-quote name-or-id) "[ \t]*$")
5256 nil t)
5257 (setq buffer (current-buffer) loc (match-beginning 0))
5258 (setq id-loc (org-id-find name-or-id 'marker))
5259 (unless (and id-loc (markerp id-loc))
5260 (user-error "Can't find remote table \"%s\"" name-or-id))
5261 (setq buffer (marker-buffer id-loc)
5262 loc (marker-position id-loc))
5263 (move-marker id-loc nil)))
5264 (with-current-buffer buffer
5265 (save-excursion
5266 (save-restriction
5267 (widen)
5268 (goto-char loc)
5269 (forward-char 1)
5270 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5271 (not (match-beginning 1)))
5272 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5273 (setq tbeg (point-at-bol))
5274 (org-table-get-specials)
5275 (setq form (org-table-formula-substitute-names
5276 (org-table-formula-handle-first/last-rc form)))
5277 (if (and (string-match org-table-range-regexp form)
5278 (> (length (match-string 0 form)) 1))
5279 (save-match-data
5280 (org-table-get-range (match-string 0 form) tbeg 1))
5281 form)))))))))
5283 (defun org-table-remote-reference-indirection (form)
5284 "Return formula with table remote references substituted by indirection.
5285 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5286 This indirection works only with the format @ROW$COLUMN. The
5287 format \"B3\" is not supported because it can not be
5288 distinguished from a plain table name or ID."
5289 (let ((start 0))
5290 (while (string-match (concat
5291 ;; Same as in `org-table-eval-formula'.
5292 "\\<remote([ \t]*\\("
5293 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5294 "[@$][^ \t,]+"
5295 ;; Same as in `org-table-eval-formula'.
5296 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")
5297 form
5298 start)
5299 ;; The position of the character as far as possible to the right
5300 ;; that will not be replaced and particularly not be shifted by
5301 ;; `replace-match'.
5302 (setq start (match-beginning 1))
5303 ;; Substitute the remote reference with the value found in the
5304 ;; field.
5305 (setq form
5306 (replace-match
5307 (save-match-data
5308 (org-table-get-range (org-table-formula-handle-first/last-rc
5309 (match-string 1 form))))
5310 t t form 1))))
5311 form)
5313 (defmacro org-define-lookup-function (mode)
5314 (let ((mode-str (symbol-name mode))
5315 (first-p (equal mode 'first))
5316 (all-p (equal mode 'all)))
5317 (let ((plural-str (if all-p "s" "")))
5318 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5319 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5320 If R-LIST is nil, return matching element%s of S-LIST.
5321 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5322 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5323 This function is generated by a call to the macro `org-define-lookup-function'."
5324 mode-str plural-str plural-str plural-str)
5325 (let ,(let ((lvars '((p (or predicate 'equal))
5326 (sl s-list)
5327 (rl (or r-list s-list))
5328 (ret nil))))
5329 (if first-p (add-to-list 'lvars '(match-p nil)))
5330 lvars)
5331 (while ,(if first-p '(and (not match-p) sl) 'sl)
5332 (progn
5333 (if (funcall p val (car sl))
5334 (progn
5335 ,(if first-p '(setq match-p t))
5336 (let ((rval (car rl)))
5337 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
5338 (setq sl (cdr sl) rl (cdr rl))))
5339 ret)))))
5341 (org-define-lookup-function first)
5342 (org-define-lookup-function last)
5343 (org-define-lookup-function all)
5345 (provide 'org-table)
5347 ;; Local variables:
5348 ;; generated-autoload-file: "org-loaddefs.el"
5349 ;; End:
5351 ;;; org-table.el ends here