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