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