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