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