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