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