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