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