Release 6.36c
[org-mode/org-jambu.git] / lisp / org-table.el
blobaddc740b475b68bd6226c41db227364b40318942
1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.36c
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; This file contains the table editor and spreadsheet for Org-mode.
31 ;; Watch out: Here we are talking about two different kind of tables.
32 ;; Most of the code is for the tables created with the Org-mode table editor.
33 ;; Sometimes, we talk about tables created and edited with the table.el
34 ;; Emacs package. We call the former org-type tables, and the latter
35 ;; table.el-type tables.
37 ;;; Code:
39 (eval-when-compile
40 (require 'cl))
41 (require 'org)
43 (declare-function org-table-clean-before-export "org-exp"
44 (lines &optional maybe-quoted))
45 (declare-function org-format-org-table-html "org-html" (lines &optional splice))
46 (defvar orgtbl-mode) ; defined below
47 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
48 (defvar org-export-html-table-tag) ; defined in org-exp.el
49 (defvar constants-unit-system)
51 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
52 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
53 In the optimized version, the table editor takes over all simple keys that
54 normally just insert a character. In tables, the characters are inserted
55 in a way to minimize disturbing the table structure (i.e. in overwrite mode
56 for empty fields). Outside tables, the correct binding of the keys is
57 restored.
59 The default for this option is t if the optimized version is also used in
60 Org-mode. See the variable `org-enable-table-editor' for details. Changing
61 this variable requires a restart of Emacs to become effective."
62 :group 'org-table
63 :type 'boolean)
65 (defcustom orgtbl-radio-table-templates
66 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
67 % END RECEIVE ORGTBL %n
68 \\begin{comment}
69 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
70 | | |
71 \\end{comment}\n")
72 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
73 @c END RECEIVE ORGTBL %n
74 @ignore
75 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
76 | | |
77 @end ignore\n")
78 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
79 <!-- END RECEIVE ORGTBL %n -->
80 <!--
81 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
82 | | |
83 -->\n"))
84 "Templates for radio tables in different major modes.
85 All occurrences of %n in a template will be replaced with the name of the
86 table, obtained by prompting the user."
87 :group 'org-table
88 :type '(repeat
89 (list (symbol :tag "Major mode")
90 (string :tag "Format"))))
92 (defgroup org-table-settings nil
93 "Settings for tables in Org-mode."
94 :tag "Org Table Settings"
95 :group 'org-table)
97 (defcustom org-table-default-size "5x2"
98 "The default size for newly created tables, Columns x Rows."
99 :group 'org-table-settings
100 :type 'string)
102 (defcustom org-table-number-regexp
103 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
104 "Regular expression for recognizing numbers in table columns.
105 If a table column contains mostly numbers, it will be aligned to the
106 right. If not, it will be aligned to the left.
108 The default value of this option is a regular expression which allows
109 anything which looks remotely like a number as used in scientific
110 context. For example, all of the following will be considered a
111 number:
112 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
114 Other options offered by the customize interface are more restrictive."
115 :group 'org-table-settings
116 :type '(choice
117 (const :tag "Positive Integers"
118 "^[0-9]+$")
119 (const :tag "Integers"
120 "^[-+]?[0-9]+$")
121 (const :tag "Floating Point Numbers"
122 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
123 (const :tag "Floating Point Number or Integer"
124 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
125 (const :tag "Exponential, Floating point, Integer"
126 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
127 (const :tag "Very General Number-Like, including hex"
128 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
129 (string :tag "Regexp:")))
131 (defcustom org-table-number-fraction 0.5
132 "Fraction of numbers in a column required to make the column align right.
133 In a column all non-white fields are considered. If at least this
134 fraction of fields is matched by `org-table-number-fraction',
135 alignment to the right border applies."
136 :group 'org-table-settings
137 :type 'number)
139 (defgroup org-table-editing nil
140 "Behavior of tables during editing in Org-mode."
141 :tag "Org Table Editing"
142 :group 'org-table)
144 (defcustom org-table-automatic-realign t
145 "Non-nil means automatically re-align table when pressing TAB or RETURN.
146 When nil, aligning is only done with \\[org-table-align], or after column
147 removal/insertion."
148 :group 'org-table-editing
149 :type 'boolean)
151 (defcustom org-table-auto-blank-field t
152 "Non-nil means automatically blank table field when starting to type into it.
153 This only happens when typing immediately after a field motion
154 command (TAB, S-TAB or RET).
155 Only relevant when `org-enable-table-editor' is equal to `optimized'."
156 :group 'org-table-editing
157 :type 'boolean)
159 (defcustom org-table-tab-jumps-over-hlines t
160 "Non-nil means tab in the last column of a table with jump over a hline.
161 If a horizontal separator line is following the current line,
162 `org-table-next-field' can either create a new row before that line, or jump
163 over the line. When this option is nil, a new line will be created before
164 this line."
165 :group 'org-table-editing
166 :type 'boolean)
168 (defgroup org-table-calculation nil
169 "Options concerning tables in Org-mode."
170 :tag "Org Table Calculation"
171 :group 'org-table)
173 (defcustom org-table-use-standard-references t
174 "Should org-mode work with table references like B3 instead of @3$2?
175 Possible values are:
176 nil never use them
177 from accept as input, do not present for editing
178 t: accept as input and present for editing"
179 :group 'org-table-calculation
180 :type '(choice
181 (const :tag "Never, don't even check user input for them" nil)
182 (const :tag "Always, both as user input, and when editing" t)
183 (const :tag "Convert user input, don't offer during editing" 'from)))
185 (defcustom org-table-copy-increment t
186 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
187 :group 'org-table-calculation
188 :type 'boolean)
190 (defcustom org-calc-default-modes
191 '(calc-internal-prec 12
192 calc-float-format (float 8)
193 calc-angle-mode deg
194 calc-prefer-frac nil
195 calc-symbolic-mode nil
196 calc-date-format (YYYY "-" MM "-" DD " " Www (" " hh ":" mm))
197 calc-display-working-message t
199 "List with Calc mode settings for use in calc-eval for table formulas.
200 The list must contain alternating symbols (Calc modes variables and values).
201 Don't remove any of the default settings, just change the values. Org-mode
202 relies on the variables to be present in the list."
203 :group 'org-table-calculation
204 :type 'plist)
206 (defcustom org-table-formula-evaluate-inline t
207 "Non-nil means TAB and RET evaluate a formula in current table field.
208 If the current field starts with an equal sign, it is assumed to be a formula
209 which should be evaluated as described in the manual and in the documentation
210 string of the command `org-table-eval-formula'. This feature requires the
211 Emacs calc package.
212 When this variable is nil, formula calculation is only available through
213 the command \\[org-table-eval-formula]."
214 :group 'org-table-calculation
215 :type 'boolean)
217 (defcustom org-table-formula-use-constants t
218 "Non-nil means interpret constants in formulas in tables.
219 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
220 by the value given in `org-table-formula-constants', or by a value obtained
221 from the `constants.el' package."
222 :group 'org-table-calculation
223 :type 'boolean)
225 (defcustom org-table-formula-constants nil
226 "Alist with constant names and values, for use in table formulas.
227 The car of each element is a name of a constant, without the `$' before it.
228 The cdr is the value as a string. For example, if you'd like to use the
229 speed of light in a formula, you would configure
231 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
233 and then use it in an equation like `$1*$c'.
235 Constants can also be defined on a per-file basis using a line like
237 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
238 :group 'org-table-calculation
239 :type '(repeat
240 (cons (string :tag "name")
241 (string :tag "value"))))
243 (defcustom org-table-allow-automatic-line-recalculation t
244 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
245 Automatically means when TAB or RET or C-c C-c are pressed in the line."
246 :group 'org-table-calculation
247 :type 'boolean)
249 (defcustom org-table-error-on-row-ref-crossing-hline t
250 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
251 :group 'org-table
252 :type 'boolean)
254 (defcustom org-table-relative-ref-may-cross-hline t
255 "Non-nil means relative formula references may cross hlines.
256 Here are the allowed values:
258 nil Relative references may not cross hlines. They will reference the
259 field next to the hline instead. Coming from below, the reference
260 will be to the field below the hline. Coming from above, it will be
261 to the field above.
262 t Relative references may cross hlines.
263 error An attempt to cross a hline will throw an error.
265 It is probably good to never set this variable to nil, for the sake of
266 portability of tables."
267 :group 'org-table-calculation
268 :type '(choice
269 (const :tag "Allow to cross" t)
270 (const :tag "Stick to hline" nil)
271 (const :tag "Error on attempt to cross" error)))
273 (defgroup org-table-import-export nil
274 "Options concerning table import and export in Org-mode."
275 :tag "Org Table Import Export"
276 :group 'org-table)
278 (defcustom org-table-export-default-format "orgtbl-to-tsv"
279 "Default export parameters for org-table-export. These can be
280 overridden on for a specific table by setting the TABLE_EXPORT_FORMAT
281 property. See the manual section on orgtbl radio tables for the different
282 export transformations and available parameters."
283 :group 'org-table-import-export
284 :type 'string)
286 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
287 "Detects a table line marked for automatic recalculation.")
288 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
289 "Detects a table line marked for automatic recalculation.")
290 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
291 "Detects a table line marked for automatic recalculation.")
292 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
293 "Searching from within a table (any type) this finds the first line
294 outside the table.")
295 (defvar org-table-last-highlighted-reference nil)
296 (defvar org-table-formula-history nil)
298 (defvar org-table-column-names nil
299 "Alist with column names, derived from the `!' line.")
300 (defvar org-table-column-name-regexp nil
301 "Regular expression matching the current column names.")
302 (defvar org-table-local-parameters nil
303 "Alist with parameter names, derived from the `$' line.")
304 (defvar org-table-named-field-locations nil
305 "Alist with locations of named fields.")
307 (defvar org-table-current-line-types nil
308 "Table row types, non-nil only for the duration of a comand.")
309 (defvar org-table-current-begin-line nil
310 "Table begin line, non-nil only for the duration of a comand.")
311 (defvar org-table-current-begin-pos nil
312 "Table begin position, non-nil only for the duration of a comand.")
313 (defvar org-table-dlines nil
314 "Vector of data line line numbers in the current table.")
315 (defvar org-table-hlines nil
316 "Vector of hline line numbers in the current table.")
318 (defconst org-table-range-regexp
319 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
320 ;; 1 2 3 4 5
321 "Regular expression for matching ranges in formulas.")
323 (defconst org-table-range-regexp2
324 (concat
325 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
326 "\\.\\."
327 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
328 "Match a range for reference display.")
330 (defun org-table-colgroup-line-p (line)
331 "Is this a table line colgroup information?"
332 (save-match-data
333 (and (string-match "[<>]\\|&[lg]t;" line)
334 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
335 line)
336 (not (delq
338 (mapcar
339 (lambda (s)
340 (not (member s '("" "<" ">" "<>" "&lt;" "&gt;" "&lt;&gt;"))))
341 (org-split-string (match-string 1 line) "[ \t]*|[ \t]*")))))))
343 (defun org-table-cookie-line-p (line)
344 "Is this a table line with only alignment/width cookies?"
346 (save-match-data
347 (and (string-match "[<>]\\|&[lg]t;" line)
348 (or (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'" line)
349 (string-match "\\(\\`[ \t<>lr0-9|gt&;]+\\'\\)" line))
350 (not (delq nil (mapcar
351 (lambda (s)
352 (not (or (equal s "")
353 (string-match "\\`<\\([lr]?[0-9]+\\|[lr]\\)>\\'" s)
354 (string-match "\\`&lt;\\([lr]?[0-9]+\\|[lr]\\)&gt;\\'" s))))
355 (org-split-string (match-string 1 line) "[ \t]*|[ \t]*")))))))
357 (defconst org-table-translate-regexp
358 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
359 "Match a reference that needs translation, for reference display.")
361 (defun org-table-create-with-table.el ()
362 "Use the table.el package to insert a new table.
363 If there is already a table at point, convert between Org-mode tables
364 and table.el tables."
365 (interactive)
366 (require 'table)
367 (cond
368 ((org-at-table.el-p)
369 (if (y-or-n-p "Convert table to Org-mode table? ")
370 (org-table-convert)))
371 ((org-at-table-p)
372 (if (y-or-n-p "Convert table to table.el table? ")
373 (org-table-convert)))
374 (t (call-interactively 'table-insert))))
376 (defun org-table-create-or-convert-from-region (arg)
377 "Convert region to table, or create an empty table.
378 If there is an active region, convert it to a table, using the function
379 `org-table-convert-region'. See the documentation of that function
380 to learn how the prefix argument is interpreted to determine the field
381 separator.
382 If there is no such region, create an empty table with `org-table-create'."
383 (interactive "P")
384 (if (org-region-active-p)
385 (org-table-convert-region (region-beginning) (region-end) arg)
386 (org-table-create arg)))
388 (defun org-table-create (&optional size)
389 "Query for a size and insert a table skeleton.
390 SIZE is a string Columns x Rows like for example \"3x2\"."
391 (interactive "P")
392 (unless size
393 (setq size (read-string
394 (concat "Table size Columns x Rows [e.g. "
395 org-table-default-size "]: ")
396 "" nil org-table-default-size)))
398 (let* ((pos (point))
399 (indent (make-string (current-column) ?\ ))
400 (split (org-split-string size " *x *"))
401 (rows (string-to-number (nth 1 split)))
402 (columns (string-to-number (car split)))
403 (line (concat (apply 'concat indent "|" (make-list columns " |"))
404 "\n")))
405 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
406 (point-at-bol) (point)))
407 (beginning-of-line 1)
408 (newline))
409 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
410 (dotimes (i rows) (insert line))
411 (goto-char pos)
412 (if (> rows 1)
413 ;; Insert a hline after the first row.
414 (progn
415 (end-of-line 1)
416 (insert "\n|-")
417 (goto-char pos)))
418 (org-table-align)))
420 (defun org-table-convert-region (beg0 end0 &optional separator)
421 "Convert region to a table.
422 The region goes from BEG0 to END0, but these borders will be moved
423 slightly, to make sure a beginning of line in the first line is included.
425 SEPARATOR specifies the field separator in the lines. It can have the
426 following values:
428 '(4) Use the comma as a field separator
429 '(16) Use a TAB as field separator
430 integer When a number, use that many spaces as field separator
431 nil When nil, the command tries to be smart and figure out the
432 separator in the following way:
433 - when each line contains a TAB, assume TAB-separated material
434 - when each line contains a comma, assume CSV material
435 - else, assume one or more SPACE characters as separator."
436 (interactive "rP")
437 (let* ((beg (min beg0 end0))
438 (end (max beg0 end0))
440 (goto-char beg)
441 (beginning-of-line 1)
442 (setq beg (move-marker (make-marker) (point)))
443 (goto-char end)
444 (if (bolp) (backward-char 1) (end-of-line 1))
445 (setq end (move-marker (make-marker) (point)))
446 ;; Get the right field separator
447 (unless separator
448 (goto-char beg)
449 (setq separator
450 (cond
451 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
452 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
453 (t 1))))
454 (goto-char beg)
455 (if (equal separator '(4))
456 (while (<= (point) end)
457 ;; parse the csv stuff
458 (cond
459 ((looking-at "^") (insert "| "))
460 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
461 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
462 (replace-match "\\1")
463 (if (looking-at "\"") (insert "\"")))
464 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
465 ((looking-at "[ \t]*,") (replace-match " | "))
466 (t (beginning-of-line 2))))
467 (setq re (cond
468 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
469 ((equal separator '(16)) "^\\|\t")
470 ((integerp separator)
471 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
472 (t (error "This should not happen"))))
473 (while (re-search-forward re end t)
474 (replace-match "| " t t)))
475 (goto-char beg)
476 (org-table-align)))
478 (defun org-table-import (file arg)
479 "Import FILE as a table.
480 The file is assumed to be tab-separated. Such files can be produced by most
481 spreadsheet and database applications. If no tabs (at least one per line)
482 are found, lines will be split on whitespace into fields."
483 (interactive "f\nP")
484 (or (bolp) (newline))
485 (let ((beg (point))
486 (pm (point-max)))
487 (insert-file-contents file)
488 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
491 (defvar org-table-last-alignment)
492 (defvar org-table-last-column-widths)
493 (defun org-table-export (&optional file format)
494 "Export table to a file, with configurable format.
495 Such a file can be imported into a spreadsheet program like Excel.
496 FILE can be the output file name. If not given, it will be taken from
497 a TABLE_EXPORT_FILE property in the current entry or higher up in the
498 hierarchy, or the user will be prompted for a file name.
499 FORMAT can be an export format, of the same kind as it used when
500 orgtbl-mode sends a table in a different format. The default format can
501 be found in the variable `org-table-export-default-format', but the function
502 first checks if there is an export format specified in a TABLE_EXPORT_FORMAT
503 property, locally or anywhere up in the hierarchy."
504 (interactive)
505 (unless (org-at-table-p)
506 (error "No table at point"))
507 (require 'org-exp)
508 (org-table-align) ;; make sure we have everything we need
509 (let* ((beg (org-table-begin))
510 (end (org-table-end))
511 (txt (buffer-substring-no-properties beg end))
512 (file (or file
513 (condition-case nil
514 (org-entry-get beg "TABLE_EXPORT_FILE" t)
515 (error nil))))
516 (format (or format
517 (condition-case nil
518 (org-entry-get beg "TABLE_EXPORT_FORMAT" t)
519 (error nil))))
520 buf deffmt-readable)
521 (unless file
522 (setq file (read-file-name "Export table to: "))
523 (unless (or (not (file-exists-p file))
524 (y-or-n-p (format "Overwrite file %s? " file)))
525 (error "Abort")))
526 (if (file-directory-p file)
527 (error "This is a directory path, not a file"))
528 (if (and (buffer-file-name)
529 (equal (file-truename file)
530 (file-truename (buffer-file-name))))
531 (error "Please specify a file name that is different from current"))
532 (unless format
533 (setq deffmt-readable org-table-export-default-format)
534 (while (string-match "\t" deffmt-readable)
535 (setq deffmt-readable (replace-match "\\t" t t deffmt-readable)))
536 (while (string-match "\n" deffmt-readable)
537 (setq deffmt-readable (replace-match "\\n" t t deffmt-readable)))
538 (setq format (org-completing-read
539 "Format: "
540 '("orgtbl-to-tsv" "orgtbl-to-csv"
541 "orgtbl-to-latex" "orgtbl-to-html"
542 "orgtbl-to-generic" "orgtbl-to-texinfo"
543 "orgtbl-to-orgtbl") nil nil
544 deffmt-readable)))
545 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format)
546 (let* ((transform (intern (match-string 1 format)))
547 (params (if (match-end 2)
548 (read (concat "(" (match-string 2 format) ")"))))
549 (skip (plist-get params :skip))
550 (skipcols (plist-get params :skipcols))
551 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
552 (lines (org-table-clean-before-export lines))
553 (i0 (if org-table-clean-did-remove-column 2 1))
554 (table (mapcar
555 (lambda (x)
556 (if (string-match org-table-hline-regexp x)
557 'hline
558 (org-remove-by-index
559 (org-split-string (org-trim x) "\\s-*|\\s-*")
560 skipcols i0)))
561 lines))
562 (fun (if (= i0 2) 'cdr 'identity))
563 (org-table-last-alignment
564 (org-remove-by-index (funcall fun org-table-last-alignment)
565 skipcols i0))
566 (org-table-last-column-widths
567 (org-remove-by-index (funcall fun org-table-last-column-widths)
568 skipcols i0)))
570 (unless (fboundp transform)
571 (error "No such transformation function %s" transform))
572 (setq txt (funcall transform table params))
574 (with-current-buffer (find-file-noselect file)
575 (setq buf (current-buffer))
576 (erase-buffer)
577 (fundamental-mode)
578 (insert txt "\n")
579 (save-buffer))
580 (kill-buffer buf)
581 (message "Export done."))
582 (error "TABLE_EXPORT_FORMAT invalid"))))
584 (defvar org-table-aligned-begin-marker (make-marker)
585 "Marker at the beginning of the table last aligned.
586 Used to check if cursor still is in that table, to minimize realignment.")
587 (defvar org-table-aligned-end-marker (make-marker)
588 "Marker at the end of the table last aligned.
589 Used to check if cursor still is in that table, to minimize realignment.")
590 (defvar org-table-last-alignment nil
591 "List of flags for flushright alignment, from the last re-alignment.
592 This is being used to correctly align a single field after TAB or RET.")
593 (defvar org-table-last-column-widths nil
594 "List of max width of fields in each column.
595 This is being used to correctly align a single field after TAB or RET.")
596 (defvar org-table-formula-debug nil
597 "Non-nil means debug table formulas.
598 When nil, simply write \"#ERROR\" in corrupted fields.")
599 (make-variable-buffer-local 'org-table-formula-debug)
600 (defvar org-table-overlay-coordinates nil
601 "Overlay coordinates after each align of a table.")
602 (make-variable-buffer-local 'org-table-overlay-coordinates)
604 (defvar org-last-recalc-line nil)
605 (defvar org-table-do-narrow t) ; for dynamic scoping
606 (defconst org-narrow-column-arrow "=>"
607 "Used as display property in narrowed table columns.")
609 (defun org-table-align ()
610 "Align the table at point by aligning all vertical bars."
611 (interactive)
612 (let* (
613 ;; Limits of table
614 (beg (org-table-begin))
615 (end (org-table-end))
616 ;; Current cursor position
617 (linepos (org-current-line))
618 (colpos (org-table-current-column))
619 (winstart (window-start))
620 (winstartline (org-current-line (min winstart (1- (point-max)))))
621 lines (new "") lengths l typenums ty fields maxfields i
622 column
623 (indent "") cnt frac
624 rfmt hfmt
625 (spaces '(1 . 1))
626 (sp1 (car spaces))
627 (sp2 (cdr spaces))
628 (rfmt1 (concat
629 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
630 (hfmt1 (concat
631 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
632 emptystrings links dates emph narrow falign falign1 fmax f1 len c e)
633 (untabify beg end)
634 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
635 ;; Check if we have links or dates
636 (goto-char beg)
637 (setq links (re-search-forward org-bracket-link-regexp end t))
638 (goto-char beg)
639 (setq emph (and org-hide-emphasis-markers
640 (re-search-forward org-emph-re end t)))
641 (goto-char beg)
642 (setq dates (and org-display-custom-times
643 (re-search-forward org-ts-regexp-both end t)))
644 ;; Make sure the link properties are right
645 (when links (goto-char beg) (while (org-activate-bracket-links end)))
646 ;; Make sure the date properties are right
647 (when dates (goto-char beg) (while (org-activate-dates end)))
648 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
650 ;; Check if we are narrowing any columns
651 (goto-char beg)
652 (setq narrow (and org-table-do-narrow
653 org-format-transports-properties-p
654 (re-search-forward "<[rl]?[0-9]+>" end t)))
655 (goto-char beg)
656 (setq falign (re-search-forward "<[rl][0-9]*>" end t))
657 (goto-char beg)
658 ;; Get the rows
659 (setq lines (org-split-string
660 (buffer-substring beg end) "\n"))
661 ;; Store the indentation of the first line
662 (if (string-match "^ *" (car lines))
663 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
664 ;; Mark the hlines by setting the corresponding element to nil
665 ;; At the same time, we remove trailing space.
666 (setq lines (mapcar (lambda (l)
667 (if (string-match "^ *|-" l)
669 (if (string-match "[ \t]+$" l)
670 (substring l 0 (match-beginning 0))
671 l)))
672 lines))
673 ;; Get the data fields by splitting the lines.
674 (setq fields (mapcar
675 (lambda (l)
676 (org-split-string l " *| *"))
677 (delq nil (copy-sequence lines))))
678 ;; How many fields in the longest line?
679 (condition-case nil
680 (setq maxfields (apply 'max (mapcar 'length fields)))
681 (error
682 (kill-region beg end)
683 (org-table-create org-table-default-size)
684 (error "Empty table - created default table")))
685 ;; A list of empty strings to fill any short rows on output
686 (setq emptystrings (make-list maxfields ""))
687 ;; Check for special formatting.
688 (setq i -1)
689 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
690 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
691 ;; Check if there is an explicit width specified
692 (setq fmax nil)
693 (when (or narrow falign)
694 (setq c column fmax nil falign1 nil)
695 (while c
696 (setq e (pop c))
697 (when (and (stringp e) (string-match "^<\\([rl]\\)?\\([0-9]+\\)?>$" e))
698 (if (match-end 1) (setq falign1 (match-string 1 e)))
699 (if (and org-table-do-narrow (match-end 2))
700 (setq fmax (string-to-number (match-string 2 e)) c nil))))
701 ;; Find fields that are wider than fmax, and shorten them
702 (when fmax
703 (loop for xx in column do
704 (when (and (stringp xx)
705 (> (org-string-width xx) fmax))
706 (org-add-props xx nil
707 'help-echo
708 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
709 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
710 (unless (> f1 1)
711 (error "Cannot narrow field starting with wide link \"%s\""
712 (match-string 0 xx)))
713 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
714 (add-text-properties (- f1 2) f1
715 (list 'display org-narrow-column-arrow)
716 xx)))))
717 ;; Get the maximum width for each column
718 (push (apply 'max (or fmax 1) 1 (mapcar 'org-string-width column))
719 lengths)
720 ;; Get the fraction of numbers, to decide about alignment of the column
721 (if falign1
722 (push (equal (downcase falign1) "r") typenums)
723 (setq cnt 0 frac 0.0)
724 (loop for x in column do
725 (if (equal x "")
727 (setq frac ( / (+ (* frac cnt)
728 (if (string-match org-table-number-regexp x) 1 0))
729 (setq cnt (1+ cnt))))))
730 (push (>= frac org-table-number-fraction) typenums)))
731 (setq lengths (nreverse lengths) typenums (nreverse typenums))
733 ;; Store the alignment of this table, for later editing of single fields
734 (setq org-table-last-alignment typenums
735 org-table-last-column-widths lengths)
737 ;; With invisible characters, `format' does not get the field width right
738 ;; So we need to make these fields wide by hand.
739 (when (or links emph)
740 (loop for i from 0 upto (1- maxfields) do
741 (setq len (nth i lengths))
742 (loop for j from 0 upto (1- (length fields)) do
743 (setq c (nthcdr i (car (nthcdr j fields))))
744 (if (and (stringp (car c))
745 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
746 ; (string-match org-bracket-link-regexp (car c))
747 (< (org-string-width (car c)) len))
748 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
750 ;; Compute the formats needed for output of the table
751 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
752 (while (setq l (pop lengths))
753 (setq ty (if (pop typenums) "" "-")) ; number types flushright
754 (setq rfmt (concat rfmt (format rfmt1 ty l))
755 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
756 (setq rfmt (concat rfmt "\n")
757 hfmt (concat (substring hfmt 0 -1) "|\n"))
759 (setq new (mapconcat
760 (lambda (l)
761 (if l (apply 'format rfmt
762 (append (pop fields) emptystrings))
763 hfmt))
764 lines ""))
765 (if (equal (char-before) ?\n)
766 ;; This hack is for org-indent, to force redisplay of the
767 ;; line prefix of the first line. Apparently the redisplay
768 ;; is tied to the newline, which is, I think, a bug.
769 ;; To force this redisplay, we remove and re-insert the
770 ;; newline, so that the redisplay engine thinks it belongs
771 ;; to the changed text.
772 (progn
773 (backward-delete-char 1)
774 (insert "\n")))
775 (move-marker org-table-aligned-begin-marker (point))
776 (insert new)
777 ;; Replace the old one
778 (delete-region (point) end)
779 (move-marker end nil)
780 (move-marker org-table-aligned-end-marker (point))
781 (when (and orgtbl-mode (not (org-mode-p)))
782 (goto-char org-table-aligned-begin-marker)
783 (while (org-hide-wide-columns org-table-aligned-end-marker)))
784 ;; Try to move to the old location
785 (org-goto-line winstartline)
786 (setq winstart (point-at-bol))
787 (org-goto-line linepos)
788 (set-window-start (selected-window) winstart 'noforce)
789 (org-table-goto-column colpos)
790 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
791 (setq org-table-may-need-update nil)
794 (defun org-table-begin (&optional table-type)
795 "Find the beginning of the table and return its position.
796 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
797 (save-excursion
798 (if (not (re-search-backward
799 (if table-type org-table-any-border-regexp
800 org-table-border-regexp)
801 nil t))
802 (progn (goto-char (point-min)) (point))
803 (goto-char (match-beginning 0))
804 (beginning-of-line 2)
805 (point))))
807 (defun org-table-end (&optional table-type)
808 "Find the end of the table and return its position.
809 With argument TABLE-TYPE, go to the end of a table.el-type table."
810 (save-excursion
811 (if (not (re-search-forward
812 (if table-type org-table-any-border-regexp
813 org-table-border-regexp)
814 nil t))
815 (goto-char (point-max))
816 (goto-char (match-beginning 0)))
817 (point-marker)))
819 (defun org-table-justify-field-maybe (&optional new)
820 "Justify the current field, text to left, number to right.
821 Optional argument NEW may specify text to replace the current field content."
822 (cond
823 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
824 ((org-at-table-hline-p))
825 ((and (not new)
826 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
827 (current-buffer)))
828 (< (point) org-table-aligned-begin-marker)
829 (>= (point) org-table-aligned-end-marker)))
830 ;; This is not the same table, force a full re-align
831 (setq org-table-may-need-update t))
832 (t ;; realign the current field, based on previous full realign
833 (let* ((pos (point)) s
834 (col (org-table-current-column))
835 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
836 l f n o e)
837 (when (> col 0)
838 (skip-chars-backward "^|\n")
839 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
840 (progn
841 (setq s (match-string 1)
842 o (match-string 0)
843 l (max 1 (- (match-end 0) (match-beginning 0) 3))
844 e (not (= (match-beginning 2) (match-end 2))))
845 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
846 l (if e "|" (setq org-table-may-need-update t) ""))
847 n (format f s))
848 (if new
849 (if (<= (length new) l) ;; FIXME: length -> str-width?
850 (setq n (format f new))
851 (setq n (concat new "|") org-table-may-need-update t)))
852 (if (equal (string-to-char n) ?-) (setq n (concat " " n)))
853 (or (equal n o)
854 (let (org-table-may-need-update)
855 (replace-match n t t))))
856 (setq org-table-may-need-update t))
857 (goto-char pos))))))
859 (defun org-table-next-field ()
860 "Go to the next field in the current table, creating new lines as needed.
861 Before doing so, re-align the table if necessary."
862 (interactive)
863 (org-table-maybe-eval-formula)
864 (org-table-maybe-recalculate-line)
865 (if (and org-table-automatic-realign
866 org-table-may-need-update)
867 (org-table-align))
868 (let ((end (org-table-end)))
869 (if (org-at-table-hline-p)
870 (end-of-line 1))
871 (condition-case nil
872 (progn
873 (re-search-forward "|" end)
874 (if (looking-at "[ \t]*$")
875 (re-search-forward "|" end))
876 (if (and (looking-at "-")
877 org-table-tab-jumps-over-hlines
878 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
879 (goto-char (match-beginning 1)))
880 (if (looking-at "-")
881 (progn
882 (beginning-of-line 0)
883 (org-table-insert-row 'below))
884 (if (looking-at " ") (forward-char 1))))
885 (error
886 (org-table-insert-row 'below)))))
888 (defun org-table-previous-field ()
889 "Go to the previous field in the table.
890 Before doing so, re-align the table if necessary."
891 (interactive)
892 (org-table-justify-field-maybe)
893 (org-table-maybe-recalculate-line)
894 (if (and org-table-automatic-realign
895 org-table-may-need-update)
896 (org-table-align))
897 (if (org-at-table-hline-p)
898 (end-of-line 1))
899 (condition-case nil
900 (progn
901 (re-search-backward "|" (org-table-begin))
902 (re-search-backward "|" (org-table-begin)))
903 (error (error "Cannot move to previous table field")))
904 (while (looking-at "|\\(-\\|[ \t]*$\\)")
905 (re-search-backward "|" (org-table-begin)))
906 (if (looking-at "| ?")
907 (goto-char (match-end 0))))
909 (defun org-table-beginning-of-field (&optional n)
910 "Move to the end of the current table field.
911 If already at or after the end, move to the end of the next table field.
912 With numeric argument N, move N-1 fields forward first."
913 (interactive "p")
914 (let ((pos (point)))
915 (while (> n 1)
916 (setq n (1- n))
917 (org-table-previous-field))
918 (if (not (re-search-backward "|" (point-at-bol 0) t))
919 (error "No more table fields before the current")
920 (goto-char (match-end 0))
921 (and (looking-at " ") (forward-char 1)))
922 (if (>= (point) pos) (org-table-beginning-of-field 2))))
924 (defun org-table-end-of-field (&optional n)
925 "Move to the beginning of the current table field.
926 If already at or before the beginning, move to the beginning of the
927 previous field.
928 With numeric argument N, move N-1 fields backward first."
929 (interactive "p")
930 (let ((pos (point)))
931 (while (> n 1)
932 (setq n (1- n))
933 (org-table-next-field))
934 (when (re-search-forward "|" (point-at-eol 1) t)
935 (backward-char 1)
936 (skip-chars-backward " ")
937 (if (and (equal (char-before (point)) ?|) (looking-at " "))
938 (forward-char 1)))
939 (if (<= (point) pos) (org-table-end-of-field 2))))
941 (defun org-table-next-row ()
942 "Go to the next row (same column) in the current table.
943 Before doing so, re-align the table if necessary."
944 (interactive)
945 (org-table-maybe-eval-formula)
946 (org-table-maybe-recalculate-line)
947 (if (or (looking-at "[ \t]*$")
948 (save-excursion (skip-chars-backward " \t") (bolp)))
949 (newline)
950 (if (and org-table-automatic-realign
951 org-table-may-need-update)
952 (org-table-align))
953 (let ((col (org-table-current-column)))
954 (beginning-of-line 2)
955 (if (or (not (org-at-table-p))
956 (org-at-table-hline-p))
957 (progn
958 (beginning-of-line 0)
959 (org-table-insert-row 'below)))
960 (org-table-goto-column col)
961 (skip-chars-backward "^|\n\r")
962 (if (looking-at " ") (forward-char 1)))))
964 (defun org-table-copy-down (n)
965 "Copy a field down in the current column.
966 If the field at the cursor is empty, copy into it the content of the nearest
967 non-empty field above. With argument N, use the Nth non-empty field.
968 If the current field is not empty, it is copied down to the next row, and
969 the cursor is moved with it. Therefore, repeating this command causes the
970 column to be filled row-by-row.
971 If the variable `org-table-copy-increment' is non-nil and the field is an
972 integer or a timestamp, it will be incremented while copying. In the case of
973 a timestamp, if the cursor is on the year, change the year. If it is on the
974 month or the day, change that. Point will stay on the current date field
975 in order to easily repeat the interval."
976 (interactive "p")
977 (let* ((colpos (org-table-current-column))
978 (col (current-column))
979 (field (org-table-get-field))
980 (non-empty (string-match "[^ \t]" field))
981 (beg (org-table-begin))
982 (orig-n n)
983 txt)
984 (org-table-check-inside-data-field)
985 (if non-empty
986 (progn
987 (setq txt (org-trim field))
988 (org-table-next-row)
989 (org-table-blank-field))
990 (save-excursion
991 (setq txt
992 (catch 'exit
993 (while (progn (beginning-of-line 1)
994 (re-search-backward org-table-dataline-regexp
995 beg t))
996 (org-table-goto-column colpos t)
997 (if (and (looking-at
998 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
999 (<= (setq n (1- n)) 0))
1000 (throw 'exit (match-string 1))))))))
1001 (if txt
1002 (progn
1003 (if (and org-table-copy-increment
1004 (not (equal orig-n 0))
1005 (string-match "^[0-9]+$" txt)
1006 (< (string-to-number txt) 100000000))
1007 (setq txt (format "%d" (+ (string-to-number txt) 1))))
1008 (insert txt)
1009 (org-move-to-column col)
1010 (if (and org-table-copy-increment (org-at-timestamp-p t))
1011 (org-timestamp-up-day)
1012 (org-table-maybe-recalculate-line))
1013 (org-table-align)
1014 (org-move-to-column col))
1015 (error "No non-empty field found"))))
1017 (defun org-table-check-inside-data-field ()
1018 "Is point inside a table data field?
1019 I.e. not on a hline or before the first or after the last column?
1020 This actually throws an error, so it aborts the current command."
1021 (if (or (not (org-at-table-p))
1022 (= (org-table-current-column) 0)
1023 (org-at-table-hline-p)
1024 (looking-at "[ \t]*$"))
1025 (error "Not in table data field")))
1027 (defvar org-table-clip nil
1028 "Clipboard for table regions.")
1030 (defun org-table-get (line column)
1031 "Get the field in table line LINE, column COLUMN.
1032 If LINE is larger than the number of data lines in the table, the function
1033 returns nil. However, if COLUMN is too large, we will simply return an
1034 empty string.
1035 If LINE is nil, use the current line.
1036 If column is nil, use the current column."
1037 (setq column (or column (org-table-current-column)))
1038 (save-excursion
1039 (and (or (not line) (org-table-goto-line line))
1040 (org-trim (org-table-get-field column)))))
1042 (defun org-table-put (line column value &optional align)
1043 "Put VALUE into line LINE, column COLUMN.
1044 When ALIGN is set, als realign the table."
1045 (setq column (or column (org-table-current-column)))
1046 (prog1 (save-excursion
1047 (and (or (not line) (org-table-goto-line line))
1048 (progn (org-table-goto-column column nil 'force) t)
1049 (org-table-get-field column value)))
1050 (and align (org-table-align))))
1052 (defun org-table-current-line ()
1053 "Return the index of the current data line."
1054 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1055 (save-excursion
1056 (goto-char (org-table-begin))
1057 (while (and (re-search-forward org-table-dataline-regexp end t)
1058 (setq cnt (1+ cnt))
1059 (< (point-at-eol) pos))))
1060 cnt))
1062 (defun org-table-goto-line (N)
1063 "Go to the Nth data line in the current table.
1064 Return t when the line exists, nil if it does not exist."
1065 (goto-char (org-table-begin))
1066 (let ((end (org-table-end)) (cnt 0))
1067 (while (and (re-search-forward org-table-dataline-regexp end t)
1068 (< (setq cnt (1+ cnt)) N)))
1069 (= cnt N)))
1071 (defun org-table-blank-field ()
1072 "Blank the current table field or active region."
1073 (interactive)
1074 (org-table-check-inside-data-field)
1075 (if (and (interactive-p) (org-region-active-p))
1076 (let (org-table-clip)
1077 (org-table-cut-region (region-beginning) (region-end)))
1078 (skip-chars-backward "^|")
1079 (backward-char 1)
1080 (if (looking-at "|[^|\n]+")
1081 (let* ((pos (match-beginning 0))
1082 (match (match-string 0))
1083 (len (org-string-width match)))
1084 (replace-match (concat "|" (make-string (1- len) ?\ )))
1085 (goto-char (+ 2 pos))
1086 (substring match 1)))))
1088 (defun org-table-get-field (&optional n replace)
1089 "Return the value of the field in column N of current row.
1090 N defaults to current field.
1091 If REPLACE is a string, replace field with this value. The return value
1092 is always the old value."
1093 (and n (org-table-goto-column n))
1094 (skip-chars-backward "^|\n")
1095 (backward-char 1)
1096 (if (looking-at "|[^|\r\n]*")
1097 (let* ((pos (match-beginning 0))
1098 (val (buffer-substring (1+ pos) (match-end 0))))
1099 (if replace
1100 (replace-match (concat "|" replace) t t))
1101 (goto-char (min (point-at-eol) (+ 2 pos)))
1102 val)
1103 (forward-char 1) ""))
1105 (defun org-table-field-info (arg)
1106 "Show info about the current field, and highlight any reference at point."
1107 (interactive "P")
1108 (org-table-get-specials)
1109 (save-excursion
1110 (let* ((pos (point))
1111 (col (org-table-current-column))
1112 (cname (car (rassoc (int-to-string col) org-table-column-names)))
1113 (name (car (rassoc (list (org-current-line) col)
1114 org-table-named-field-locations)))
1115 (eql (org-table-get-stored-formulas))
1116 (dline (org-table-current-dline))
1117 (ref (format "@%d$%d" dline col))
1118 (ref1 (org-table-convert-refs-to-an ref))
1119 (fequation (or (assoc name eql) (assoc ref eql)))
1120 (cequation (assoc (int-to-string col) eql))
1121 (eqn (or fequation cequation)))
1122 (goto-char pos)
1123 (condition-case nil
1124 (org-table-show-reference 'local)
1125 (error nil))
1126 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1127 dline col
1128 (if cname (concat " or $" cname) "")
1129 dline col ref1
1130 (if name (concat " or $" name) "")
1131 ;; FIXME: formula info not correct if special table line
1132 (if eqn
1133 (concat ", formula: "
1134 (org-table-formula-to-user
1135 (concat
1136 (if (string-match "^[$@]"(car eqn)) "" "$")
1137 (car eqn) "=" (cdr eqn))))
1138 "")))))
1140 (defun org-table-current-column ()
1141 "Find out which column we are in."
1142 (save-excursion
1143 (let ((cnt 0) (pos (point)))
1144 (beginning-of-line 1)
1145 (while (search-forward "|" pos t)
1146 (setq cnt (1+ cnt)))
1147 cnt)))
1149 (defun org-table-current-dline ()
1150 "Find out what table data line we are in.
1151 Only datalines count for this."
1152 (interactive)
1153 (if (interactive-p) (org-table-check-inside-data-field))
1154 (save-excursion
1155 (let ((cnt 0) (pos (point)))
1156 (goto-char (org-table-begin))
1157 (while (<= (point) pos)
1158 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
1159 (beginning-of-line 2))
1160 (if (interactive-p) (message "This is table line %d" cnt))
1161 cnt)))
1163 (defun org-table-goto-column (n &optional on-delim force)
1164 "Move the cursor to the Nth column in the current table line.
1165 With optional argument ON-DELIM, stop with point before the left delimiter
1166 of the field.
1167 If there are less than N fields, just go to after the last delimiter.
1168 However, when FORCE is non-nil, create new columns if necessary."
1169 (interactive "p")
1170 (beginning-of-line 1)
1171 (when (> n 0)
1172 (while (and (> (setq n (1- n)) -1)
1173 (or (search-forward "|" (point-at-eol) t)
1174 (and force
1175 (progn (end-of-line 1)
1176 (skip-chars-backward "^|")
1177 (insert " | ")
1178 t)))))
1179 (when (and force (not (looking-at ".*|")))
1180 (save-excursion (end-of-line 1) (insert " | ")))
1181 (if on-delim
1182 (backward-char 1)
1183 (if (looking-at " ") (forward-char 1)))))
1185 (defun org-table-insert-column ()
1186 "Insert a new column into the table."
1187 (interactive)
1188 (if (not (org-at-table-p))
1189 (error "Not at a table"))
1190 (org-table-find-dataline)
1191 (let* ((col (max 1 (org-table-current-column)))
1192 (beg (org-table-begin))
1193 (end (org-table-end))
1194 ;; Current cursor position
1195 (linepos (org-current-line))
1196 (colpos col))
1197 (goto-char beg)
1198 (while (< (point) end)
1199 (if (org-at-table-hline-p)
1201 (org-table-goto-column col t)
1202 (insert "| "))
1203 (beginning-of-line 2))
1204 (move-marker end nil)
1205 (org-goto-line linepos)
1206 (org-table-goto-column colpos)
1207 (org-table-align)
1208 (org-table-fix-formulas "$" nil (1- col) 1)
1209 (org-table-fix-formulas "$LR" nil (1- col) 1)))
1211 (defun org-table-find-dataline ()
1212 "Find a dataline in the current table, which is needed for column commands."
1213 (if (and (org-at-table-p)
1214 (not (org-at-table-hline-p)))
1216 (let ((col (current-column))
1217 (end (org-table-end)))
1218 (org-move-to-column col)
1219 (while (and (< (point) end)
1220 (or (not (= (current-column) col))
1221 (org-at-table-hline-p)))
1222 (beginning-of-line 2)
1223 (org-move-to-column col))
1224 (if (and (org-at-table-p)
1225 (not (org-at-table-hline-p)))
1227 (error
1228 "Please position cursor in a data line for column operations")))))
1230 (defun org-table-delete-column ()
1231 "Delete a column from the table."
1232 (interactive)
1233 (if (not (org-at-table-p))
1234 (error "Not at a table"))
1235 (org-table-find-dataline)
1236 (org-table-check-inside-data-field)
1237 (let* ((col (org-table-current-column))
1238 (beg (org-table-begin))
1239 (end (org-table-end))
1240 ;; Current cursor position
1241 (linepos (org-current-line))
1242 (colpos col))
1243 (goto-char beg)
1244 (while (< (point) end)
1245 (if (org-at-table-hline-p)
1247 (org-table-goto-column col t)
1248 (and (looking-at "|[^|\n]+|")
1249 (replace-match "|")))
1250 (beginning-of-line 2))
1251 (move-marker end nil)
1252 (org-goto-line linepos)
1253 (org-table-goto-column colpos)
1254 (org-table-align)
1255 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
1256 col -1 col)
1257 (org-table-fix-formulas "$LR" (list (cons (number-to-string col) "INVALID"))
1258 col -1 col)))
1260 (defun org-table-move-column-right ()
1261 "Move column to the right."
1262 (interactive)
1263 (org-table-move-column nil))
1264 (defun org-table-move-column-left ()
1265 "Move column to the left."
1266 (interactive)
1267 (org-table-move-column 'left))
1269 (defun org-table-move-column (&optional left)
1270 "Move the current column to the right. With arg LEFT, move to the left."
1271 (interactive "P")
1272 (if (not (org-at-table-p))
1273 (error "Not at a table"))
1274 (org-table-find-dataline)
1275 (org-table-check-inside-data-field)
1276 (let* ((col (org-table-current-column))
1277 (col1 (if left (1- col) col))
1278 (beg (org-table-begin))
1279 (end (org-table-end))
1280 ;; Current cursor position
1281 (linepos (org-current-line))
1282 (colpos (if left (1- col) (1+ col))))
1283 (if (and left (= col 1))
1284 (error "Cannot move column further left"))
1285 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
1286 (error "Cannot move column further right"))
1287 (goto-char beg)
1288 (while (< (point) end)
1289 (if (org-at-table-hline-p)
1291 (org-table-goto-column col1 t)
1292 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1293 (replace-match "|\\2|\\1|")))
1294 (beginning-of-line 2))
1295 (move-marker end nil)
1296 (org-goto-line linepos)
1297 (org-table-goto-column colpos)
1298 (org-table-align)
1299 (org-table-fix-formulas
1300 "$" (list (cons (number-to-string col) (number-to-string colpos))
1301 (cons (number-to-string colpos) (number-to-string col))))
1302 (org-table-fix-formulas
1303 "$LR" (list (cons (number-to-string col) (number-to-string colpos))
1304 (cons (number-to-string colpos) (number-to-string col))))))
1306 (defun org-table-move-row-down ()
1307 "Move table row down."
1308 (interactive)
1309 (org-table-move-row nil))
1310 (defun org-table-move-row-up ()
1311 "Move table row up."
1312 (interactive)
1313 (org-table-move-row 'up))
1315 (defun org-table-move-row (&optional up)
1316 "Move the current table line down. With arg UP, move it up."
1317 (interactive "P")
1318 (let* ((col (current-column))
1319 (pos (point))
1320 (hline1p (save-excursion (beginning-of-line 1)
1321 (looking-at org-table-hline-regexp)))
1322 (dline1 (org-table-current-dline))
1323 (dline2 (+ dline1 (if up -1 1)))
1324 (tonew (if up 0 2))
1325 txt hline2p)
1326 (beginning-of-line tonew)
1327 (unless (org-at-table-p)
1328 (goto-char pos)
1329 (error "Cannot move row further"))
1330 (setq hline2p (looking-at org-table-hline-regexp))
1331 (goto-char pos)
1332 (beginning-of-line 1)
1333 (setq pos (point))
1334 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
1335 (delete-region (point) (1+ (point-at-eol)))
1336 (beginning-of-line tonew)
1337 (insert txt)
1338 (beginning-of-line 0)
1339 (org-move-to-column col)
1340 (unless (or hline1p hline2p)
1341 (org-table-fix-formulas
1342 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
1343 (cons (number-to-string dline2) (number-to-string dline1)))))))
1345 (defun org-table-insert-row (&optional arg)
1346 "Insert a new row above the current line into the table.
1347 With prefix ARG, insert below the current line."
1348 (interactive "P")
1349 (if (not (org-at-table-p))
1350 (error "Not at a table"))
1351 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1352 (new (org-table-clean-line line)))
1353 ;; Fix the first field if necessary
1354 (if (string-match "^[ \t]*| *[#$] *|" line)
1355 (setq new (replace-match (match-string 0 line) t t new)))
1356 (beginning-of-line (if arg 2 1))
1357 (let (org-table-may-need-update) (insert-before-markers new "\n"))
1358 (beginning-of-line 0)
1359 (re-search-forward "| ?" (point-at-eol) t)
1360 (and (or org-table-may-need-update org-table-overlay-coordinates)
1361 (org-table-align))
1362 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
1364 (defun org-table-insert-hline (&optional above)
1365 "Insert a horizontal-line below the current line into the table.
1366 With prefix ABOVE, insert above the current line."
1367 (interactive "P")
1368 (if (not (org-at-table-p))
1369 (error "Not at a table"))
1370 (when (eobp) (insert "\n") (backward-char 1))
1371 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1372 (org-table-align))
1373 (let ((line (org-table-clean-line
1374 (buffer-substring (point-at-bol) (point-at-eol))))
1375 (col (current-column)))
1376 (while (string-match "|\\( +\\)|" line)
1377 (setq line (replace-match
1378 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1379 ?-) "|") t t line)))
1380 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
1381 (beginning-of-line (if above 1 2))
1382 (insert line "\n")
1383 (beginning-of-line (if above 1 -1))
1384 (org-move-to-column col)
1385 (and org-table-overlay-coordinates (org-table-align))))
1387 (defun org-table-hline-and-move (&optional same-column)
1388 "Insert a hline and move to the row below that line."
1389 (interactive "P")
1390 (let ((col (org-table-current-column)))
1391 (org-table-maybe-eval-formula)
1392 (org-table-maybe-recalculate-line)
1393 (org-table-insert-hline)
1394 (end-of-line 2)
1395 (if (looking-at "\n[ \t]*|-")
1396 (progn (insert "\n|") (org-table-align))
1397 (org-table-next-field))
1398 (if same-column (org-table-goto-column col))))
1400 (defun org-table-clean-line (s)
1401 "Convert a table line S into a string with only \"|\" and space.
1402 In particular, this does handle wide and invisible characters."
1403 (if (string-match "^[ \t]*|-" s)
1404 ;; It's a hline, just map the characters
1405 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
1406 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
1407 (setq s (replace-match
1408 (concat "|" (make-string (org-string-width (match-string 1 s))
1409 ?\ ) "|")
1410 t t s)))
1413 (defun org-table-kill-row ()
1414 "Delete the current row or horizontal line from the table."
1415 (interactive)
1416 (if (not (org-at-table-p))
1417 (error "Not at a table"))
1418 (let ((col (current-column))
1419 (dline (org-table-current-dline)))
1420 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1421 (if (not (org-at-table-p)) (beginning-of-line 0))
1422 (org-move-to-column col)
1423 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
1424 dline -1 dline)))
1426 (defun org-table-sort-lines (with-case &optional sorting-type)
1427 "Sort table lines according to the column at point.
1429 The position of point indicates the column to be used for
1430 sorting, and the range of lines is the range between the nearest
1431 horizontal separator lines, or the entire table of no such lines
1432 exist. If point is before the first column, you will be prompted
1433 for the sorting column. If there is an active region, the mark
1434 specifies the first line and the sorting column, while point
1435 should be in the last line to be included into the sorting.
1437 The command then prompts for the sorting type which can be
1438 alphabetically, numerically, or by time (as given in a time stamp
1439 in the field). Sorting in reverse order is also possible.
1441 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1443 If SORTING-TYPE is specified when this function is called from a Lisp
1444 program, no prompting will take place. SORTING-TYPE must be a character,
1445 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1446 should be done in reverse order."
1447 (interactive "P")
1448 (let* ((thisline (org-current-line))
1449 (thiscol (org-table-current-column))
1450 beg end bcol ecol tend tbeg column lns pos)
1451 (when (equal thiscol 0)
1452 (if (interactive-p)
1453 (setq thiscol
1454 (string-to-number
1455 (read-string "Use column N for sorting: ")))
1456 (setq thiscol 1))
1457 (org-table-goto-column thiscol))
1458 (org-table-check-inside-data-field)
1459 (if (org-region-active-p)
1460 (progn
1461 (setq beg (region-beginning) end (region-end))
1462 (goto-char beg)
1463 (setq column (org-table-current-column)
1464 beg (point-at-bol))
1465 (goto-char end)
1466 (setq end (point-at-bol 2)))
1467 (setq column (org-table-current-column)
1468 pos (point)
1469 tbeg (org-table-begin)
1470 tend (org-table-end))
1471 (if (re-search-backward org-table-hline-regexp tbeg t)
1472 (setq beg (point-at-bol 2))
1473 (goto-char tbeg)
1474 (setq beg (point-at-bol 1)))
1475 (goto-char pos)
1476 (if (re-search-forward org-table-hline-regexp tend t)
1477 (setq end (point-at-bol 1))
1478 (goto-char tend)
1479 (setq end (point-at-bol))))
1480 (setq beg (move-marker (make-marker) beg)
1481 end (move-marker (make-marker) end))
1482 (untabify beg end)
1483 (goto-char beg)
1484 (org-table-goto-column column)
1485 (skip-chars-backward "^|")
1486 (setq bcol (current-column))
1487 (org-table-goto-column (1+ column))
1488 (skip-chars-backward "^|")
1489 (setq ecol (1- (current-column)))
1490 (org-table-goto-column column)
1491 (setq lns (mapcar (lambda(x) (cons
1492 (org-sort-remove-invisible
1493 (nth (1- column)
1494 (org-split-string x "[ \t]*|[ \t]*")))
1496 (org-split-string (buffer-substring beg end) "\n")))
1497 (setq lns (org-do-sort lns "Table" with-case sorting-type))
1498 (delete-region beg end)
1499 (move-marker beg nil)
1500 (move-marker end nil)
1501 (insert (mapconcat 'cdr lns "\n") "\n")
1502 (org-goto-line thisline)
1503 (org-table-goto-column thiscol)
1504 (message "%d lines sorted, based on column %d" (length lns) column)))
1507 (defun org-table-cut-region (beg end)
1508 "Copy region in table to the clipboard and blank all relevant fields.
1509 If there is no active region, use just the field at point."
1510 (interactive (list
1511 (if (org-region-active-p) (region-beginning) (point))
1512 (if (org-region-active-p) (region-end) (point))))
1513 (org-table-copy-region beg end 'cut))
1515 (defun org-table-copy-region (beg end &optional cut)
1516 "Copy rectangular region in table to clipboard.
1517 A special clipboard is used which can only be accessed
1518 with `org-table-paste-rectangle'."
1519 (interactive (list
1520 (if (org-region-active-p) (region-beginning) (point))
1521 (if (org-region-active-p) (region-end) (point))
1522 current-prefix-arg))
1523 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1524 region cols
1525 (rpl (if cut " " nil)))
1526 (goto-char beg)
1527 (org-table-check-inside-data-field)
1528 (setq l01 (org-current-line)
1529 c01 (org-table-current-column))
1530 (goto-char end)
1531 (org-table-check-inside-data-field)
1532 (setq l02 (org-current-line)
1533 c02 (org-table-current-column))
1534 (setq l1 (min l01 l02) l2 (max l01 l02)
1535 c1 (min c01 c02) c2 (max c01 c02))
1536 (catch 'exit
1537 (while t
1538 (catch 'nextline
1539 (if (> l1 l2) (throw 'exit t))
1540 (org-goto-line l1)
1541 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
1542 (setq cols nil ic1 c1 ic2 c2)
1543 (while (< ic1 (1+ ic2))
1544 (push (org-table-get-field ic1 rpl) cols)
1545 (setq ic1 (1+ ic1)))
1546 (push (nreverse cols) region)
1547 (setq l1 (1+ l1)))))
1548 (setq org-table-clip (nreverse region))
1549 (if cut (org-table-align))
1550 org-table-clip))
1552 (defun org-table-paste-rectangle ()
1553 "Paste a rectangular region into a table.
1554 The upper right corner ends up in the current field. All involved fields
1555 will be overwritten. If the rectangle does not fit into the present table,
1556 the table is enlarged as needed. The process ignores horizontal separator
1557 lines."
1558 (interactive)
1559 (unless (and org-table-clip (listp org-table-clip))
1560 (error "First cut/copy a region to paste!"))
1561 (org-table-check-inside-data-field)
1562 (let* ((clip org-table-clip)
1563 (line (org-current-line))
1564 (col (org-table-current-column))
1565 (org-enable-table-editor t)
1566 (org-table-automatic-realign nil)
1567 c cols field)
1568 (while (setq cols (pop clip))
1569 (while (org-at-table-hline-p) (beginning-of-line 2))
1570 (if (not (org-at-table-p))
1571 (progn (end-of-line 0) (org-table-next-field)))
1572 (setq c col)
1573 (while (setq field (pop cols))
1574 (org-table-goto-column c nil 'force)
1575 (org-table-get-field nil field)
1576 (setq c (1+ c)))
1577 (beginning-of-line 2))
1578 (org-goto-line line)
1579 (org-table-goto-column col)
1580 (org-table-align)))
1582 (defun org-table-convert ()
1583 "Convert from `org-mode' table to table.el and back.
1584 Obviously, this only works within limits. When an Org-mode table is
1585 converted to table.el, all horizontal separator lines get lost, because
1586 table.el uses these as cell boundaries and has no notion of horizontal lines.
1587 A table.el table can be converted to an Org-mode table only if it does not
1588 do row or column spanning. Multiline cells will become multiple cells.
1589 Beware, Org-mode does not test if the table can be successfully converted - it
1590 blindly applies a recipe that works for simple tables."
1591 (interactive)
1592 (require 'table)
1593 (if (org-at-table.el-p)
1594 ;; convert to Org-mode table
1595 (let ((beg (move-marker (make-marker) (org-table-begin t)))
1596 (end (move-marker (make-marker) (org-table-end t))))
1597 (table-unrecognize-region beg end)
1598 (goto-char beg)
1599 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
1600 (replace-match ""))
1601 (goto-char beg))
1602 (if (org-at-table-p)
1603 ;; convert to table.el table
1604 (let ((beg (move-marker (make-marker) (org-table-begin)))
1605 (end (move-marker (make-marker) (org-table-end))))
1606 ;; first, get rid of all horizontal lines
1607 (goto-char beg)
1608 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
1609 (replace-match ""))
1610 ;; insert a hline before first
1611 (goto-char beg)
1612 (org-table-insert-hline 'above)
1613 (beginning-of-line -1)
1614 ;; insert a hline after each line
1615 (while (progn (beginning-of-line 3) (< (point) end))
1616 (org-table-insert-hline))
1617 (goto-char beg)
1618 (setq end (move-marker end (org-table-end)))
1619 ;; replace "+" at beginning and ending of hlines
1620 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
1621 (replace-match "\\1+-"))
1622 (goto-char beg)
1623 (while (re-search-forward "-|[ \t]*$" end t)
1624 (replace-match "-+"))
1625 (goto-char beg)))))
1627 (defun org-table-wrap-region (arg)
1628 "Wrap several fields in a column like a paragraph.
1629 This is useful if you'd like to spread the contents of a field over several
1630 lines, in order to keep the table compact.
1632 If there is an active region, and both point and mark are in the same column,
1633 the text in the column is wrapped to minimum width for the given number of
1634 lines. Generally, this makes the table more compact. A prefix ARG may be
1635 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1636 formats the selected text to two lines. If the region was longer than two
1637 lines, the remaining lines remain empty. A negative prefix argument reduces
1638 the current number of lines by that amount. The wrapped text is pasted back
1639 into the table. If you formatted it to more lines than it was before, fields
1640 further down in the table get overwritten - so you might need to make space in
1641 the table first.
1643 If there is no region, the current field is split at the cursor position and
1644 the text fragment to the right of the cursor is prepended to the field one
1645 line down.
1647 If there is no region, but you specify a prefix ARG, the current field gets
1648 blank, and the content is appended to the field above."
1649 (interactive "P")
1650 (org-table-check-inside-data-field)
1651 (if (org-region-active-p)
1652 ;; There is a region: fill as a paragraph
1653 (let* ((beg (region-beginning))
1654 (cline (save-excursion (goto-char beg) (org-current-line)))
1655 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
1656 nlines)
1657 (org-table-cut-region (region-beginning) (region-end))
1658 (if (> (length (car org-table-clip)) 1)
1659 (error "Region must be limited to single column"))
1660 (setq nlines (if arg
1661 (if (< arg 1)
1662 (+ (length org-table-clip) arg)
1663 arg)
1664 (length org-table-clip)))
1665 (setq org-table-clip
1666 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
1667 nil nlines)))
1668 (org-goto-line cline)
1669 (org-table-goto-column ccol)
1670 (org-table-paste-rectangle))
1671 ;; No region, split the current field at point
1672 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
1673 (skip-chars-forward "^\r\n|"))
1674 (if arg
1675 ;; combine with field above
1676 (let ((s (org-table-blank-field))
1677 (col (org-table-current-column)))
1678 (beginning-of-line 0)
1679 (while (org-at-table-hline-p) (beginning-of-line 0))
1680 (org-table-goto-column col)
1681 (skip-chars-forward "^|")
1682 (skip-chars-backward " ")
1683 (insert " " (org-trim s))
1684 (org-table-align))
1685 ;; split field
1686 (if (looking-at "\\([^|]+\\)+|")
1687 (let ((s (match-string 1)))
1688 (replace-match " |")
1689 (goto-char (match-beginning 0))
1690 (org-table-next-row)
1691 (insert (org-trim s) " ")
1692 (org-table-align))
1693 (org-table-next-row)))))
1695 (defvar org-field-marker nil)
1697 (defun org-table-edit-field (arg)
1698 "Edit table field in a different window.
1699 This is mainly useful for fields that contain hidden parts.
1700 When called with a \\[universal-argument] prefix, just make the full field visible so that
1701 it can be edited in place."
1702 (interactive "P")
1703 (if arg
1704 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1705 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1706 (remove-text-properties b e '(org-cwidth t invisible t
1707 display t intangible t))
1708 (if (and (boundp 'font-lock-mode) font-lock-mode)
1709 (font-lock-fontify-block)))
1710 (let ((pos (move-marker (make-marker) (point)))
1711 (field (org-table-get-field))
1712 (cw (current-window-configuration))
1714 (org-switch-to-buffer-other-window "*Org tmp*")
1715 (erase-buffer)
1716 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
1717 (let ((org-inhibit-startup t)) (org-mode))
1718 (goto-char (setq p (point-max)))
1719 (insert (org-trim field))
1720 (remove-text-properties p (point-max)
1721 '(invisible t org-cwidth t display t
1722 intangible t))
1723 (goto-char p)
1724 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
1725 (org-set-local 'org-window-configuration cw)
1726 (org-set-local 'org-field-marker pos)
1727 (message "Edit and finish with C-c C-c"))))
1729 (defun org-table-finish-edit-field ()
1730 "Finish editing a table data field.
1731 Remove all newline characters, insert the result into the table, realign
1732 the table and kill the editing buffer."
1733 (let ((pos org-field-marker)
1734 (cw org-window-configuration)
1735 (cb (current-buffer))
1736 text)
1737 (goto-char (point-min))
1738 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
1739 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
1740 (replace-match " "))
1741 (setq text (org-trim (buffer-string)))
1742 (set-window-configuration cw)
1743 (kill-buffer cb)
1744 (select-window (get-buffer-window (marker-buffer pos)))
1745 (goto-char pos)
1746 (move-marker pos nil)
1747 (org-table-check-inside-data-field)
1748 (org-table-get-field nil text)
1749 (org-table-align)
1750 (message "New field value inserted")))
1752 (defvar org-timecnt) ; dynamically scoped parameter
1754 (defun org-table-sum (&optional beg end nlast)
1755 "Sum numbers in region of current table column.
1756 The result will be displayed in the echo area, and will be available
1757 as kill to be inserted with \\[yank].
1759 If there is an active region, it is interpreted as a rectangle and all
1760 numbers in that rectangle will be summed. If there is no active
1761 region and point is located in a table column, sum all numbers in that
1762 column.
1764 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1765 numbers are assumed to be times as well (in decimal hours) and the
1766 numbers are added as such.
1768 If NLAST is a number, only the NLAST fields will actually be summed."
1769 (interactive)
1770 (save-excursion
1771 (let (col (org-timecnt 0) diff h m s org-table-clip)
1772 (cond
1773 ((and beg end)) ; beg and end given explicitly
1774 ((org-region-active-p)
1775 (setq beg (region-beginning) end (region-end)))
1777 (setq col (org-table-current-column))
1778 (goto-char (org-table-begin))
1779 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
1780 (error "No table data"))
1781 (org-table-goto-column col)
1782 (setq beg (point))
1783 (goto-char (org-table-end))
1784 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
1785 (error "No table data"))
1786 (org-table-goto-column col)
1787 (setq end (point))))
1788 (let* ((items (apply 'append (org-table-copy-region beg end)))
1789 (items1 (cond ((not nlast) items)
1790 ((>= nlast (length items)) items)
1791 (t (setq items (reverse items))
1792 (setcdr (nthcdr (1- nlast) items) nil)
1793 (nreverse items))))
1794 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
1795 items1)))
1796 (res (apply '+ numbers))
1797 (sres (if (= org-timecnt 0)
1798 (number-to-string res)
1799 (setq diff (* 3600 res)
1800 h (floor (/ diff 3600)) diff (mod diff 3600)
1801 m (floor (/ diff 60)) diff (mod diff 60)
1802 s diff)
1803 (format "%d:%02d:%02d" h m s))))
1804 (kill-new sres)
1805 (if (interactive-p)
1806 (message "%s"
1807 (substitute-command-keys
1808 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
1809 (length numbers) sres))))
1810 sres))))
1812 (defun org-table-get-number-for-summing (s)
1813 (let (n)
1814 (if (string-match "^ *|? *" s)
1815 (setq s (replace-match "" nil nil s)))
1816 (if (string-match " *|? *$" s)
1817 (setq s (replace-match "" nil nil s)))
1818 (setq n (string-to-number s))
1819 (cond
1820 ((and (string-match "0" s)
1821 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
1822 ((string-match "\\`[ \t]+\\'" s) nil)
1823 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
1824 (let ((h (string-to-number (or (match-string 1 s) "0")))
1825 (m (string-to-number (or (match-string 2 s) "0")))
1826 (s (string-to-number (or (match-string 4 s) "0"))))
1827 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
1828 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
1829 ((equal n 0) nil)
1830 (t n))))
1832 (defun org-table-current-field-formula (&optional key noerror)
1833 "Return the formula active for the current field.
1834 Assumes that specials are in place.
1835 If KEY is given, return the key to this formula.
1836 Otherwise return the formula preceeded with \"=\" or \":=\"."
1837 (let* ((name (car (rassoc (list (org-current-line)
1838 (org-table-current-column))
1839 org-table-named-field-locations)))
1840 (col (org-table-current-column))
1841 (scol (int-to-string col))
1842 (ref (format "@%d$%d" (org-table-current-dline) col))
1843 (stored-list (org-table-get-stored-formulas noerror))
1844 (ass (or (assoc name stored-list)
1845 (assoc ref stored-list)
1846 (assoc scol stored-list))))
1847 (if key
1848 (car ass)
1849 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
1850 (cdr ass))))))
1852 (defun org-table-get-formula (&optional equation named)
1853 "Read a formula from the minibuffer, offer stored formula as default.
1854 When NAMED is non-nil, look for a named equation."
1855 (let* ((stored-list (org-table-get-stored-formulas))
1856 (name (car (rassoc (list (org-current-line)
1857 (org-table-current-column))
1858 org-table-named-field-locations)))
1859 (ref (format "@%d$%d" (org-table-current-dline)
1860 (org-table-current-column)))
1861 (refass (assoc ref stored-list))
1862 (nameass (assoc name stored-list))
1863 (scol (if named
1864 (if (and name (not (string-match "^LR[0-9]+$" name)))
1865 name
1866 ref)
1867 (int-to-string (org-table-current-column))))
1868 (dummy (and (or nameass refass) (not named)
1869 (not (y-or-n-p "Replace existing field formula with column formula? " ))
1870 (error "Abort")))
1871 (name (or name ref))
1872 (org-table-may-need-update nil)
1873 (stored (cdr (assoc scol stored-list)))
1874 (eq (cond
1875 ((and stored equation (string-match "^ *=? *$" equation))
1876 stored)
1877 ((stringp equation)
1878 equation)
1879 (t (org-table-formula-from-user
1880 (read-string
1881 (org-table-formula-to-user
1882 (format "%s formula %s%s="
1883 (if named "Field" "Column")
1884 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
1885 scol))
1886 (if stored (org-table-formula-to-user stored) "")
1887 'org-table-formula-history
1888 )))))
1889 mustsave)
1890 (when (not (string-match "\\S-" eq))
1891 ;; remove formula
1892 (setq stored-list (delq (assoc scol stored-list) stored-list))
1893 (org-table-store-formulas stored-list)
1894 (error "Formula removed"))
1895 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
1896 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
1897 (if (and name (not named))
1898 ;; We set the column equation, delete the named one.
1899 (setq stored-list (delq (assoc name stored-list) stored-list)
1900 mustsave t))
1901 (if stored
1902 (setcdr (assoc scol stored-list) eq)
1903 (setq stored-list (cons (cons scol eq) stored-list)))
1904 (if (or mustsave (not (equal stored eq)))
1905 (org-table-store-formulas stored-list))
1906 eq))
1908 (defun org-table-store-formulas (alist)
1909 "Store the list of formulas below the current table."
1910 (setq alist (sort alist 'org-table-formula-less-p))
1911 (save-excursion
1912 (goto-char (org-table-end))
1913 (if (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM:\\(.*\n?\\)")
1914 (progn
1915 ;; don't overwrite TBLFM, we might use text properties to store stuff
1916 (goto-char (match-beginning 2))
1917 (delete-region (match-beginning 2) (match-end 0)))
1918 (org-indent-line-function)
1919 (insert "#+TBLFM:"))
1920 (insert " "
1921 (mapconcat (lambda (x)
1922 (concat
1923 (if (equal (string-to-char (car x)) ?@) "" "$")
1924 (car x) "=" (cdr x)))
1925 alist "::")
1926 "\n")))
1928 (defsubst org-table-formula-make-cmp-string (a)
1929 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
1930 (concat
1931 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
1932 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
1933 (if (match-end 5) (concat "@@" (match-string 5 a))))))
1935 (defun org-table-formula-less-p (a b)
1936 "Compare two formulas for sorting."
1937 (let ((as (org-table-formula-make-cmp-string (car a)))
1938 (bs (org-table-formula-make-cmp-string (car b))))
1939 (and as bs (string< as bs))))
1941 (defun org-table-get-stored-formulas (&optional noerror)
1942 "Return an alist with the stored formulas directly after current table."
1943 (interactive)
1944 (let (scol eq eq-alist strings string seen)
1945 (save-excursion
1946 (goto-char (org-table-end))
1947 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
1948 (setq strings (org-split-string (match-string 2) " *:: *"))
1949 (while (setq string (pop strings))
1950 (when (string-match "\\`\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
1951 (setq scol (if (match-end 2)
1952 (match-string 2 string)
1953 (match-string 1 string))
1954 eq (match-string 3 string)
1955 eq-alist (cons (cons scol eq) eq-alist))
1956 (if (member scol seen)
1957 (if noerror
1958 (progn
1959 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
1960 (ding)
1961 (sit-for 2))
1962 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
1963 (push scol seen))))))
1964 (nreverse eq-alist)))
1966 (defun org-table-fix-formulas (key replace &optional limit delta remove)
1967 "Modify the equations after the table structure has been edited.
1968 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
1969 For all numbers larger than LIMIT, shift them by DELTA."
1970 (save-excursion
1971 (goto-char (org-table-end))
1972 (when (looking-at "[ \t]*#\\+TBLFM:")
1973 (let ((re (concat key "\\([0-9]+\\)"))
1974 (re2
1975 (when remove
1976 (if (or (equal key "$") (equal key "$LR"))
1977 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
1978 (regexp-quote key) remove)
1979 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
1980 s n a)
1981 (when remove
1982 (while (re-search-forward re2 (point-at-eol) t)
1983 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
1984 (replace-match ""))))
1985 (while (re-search-forward re (point-at-eol) t)
1986 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
1987 (setq s (match-string 1) n (string-to-number s))
1988 (cond
1989 ((setq a (assoc s replace))
1990 (replace-match (concat key (cdr a)) t t))
1991 ((and limit (> n limit))
1992 (replace-match (concat key (int-to-string (+ n delta)))
1993 t t)))))))))
1995 (defun org-table-get-specials ()
1996 "Get the column names and local parameters for this table."
1997 (save-excursion
1998 (let ((beg (org-table-begin)) (end (org-table-end))
1999 names name fields fields1 field cnt
2000 c v l line col types dlines hlines last-dline)
2001 (setq org-table-column-names nil
2002 org-table-local-parameters nil
2003 org-table-named-field-locations nil
2004 org-table-current-begin-line nil
2005 org-table-current-begin-pos nil
2006 org-table-current-line-types nil)
2007 (goto-char beg)
2008 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
2009 (setq names (org-split-string (match-string 1) " *| *")
2010 cnt 1)
2011 (while (setq name (pop names))
2012 (setq cnt (1+ cnt))
2013 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
2014 (push (cons name (int-to-string cnt)) org-table-column-names))))
2015 (setq org-table-column-names (nreverse org-table-column-names))
2016 (setq org-table-column-name-regexp
2017 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
2018 (goto-char beg)
2019 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
2020 (setq fields (org-split-string (match-string 1) " *| *"))
2021 (while (setq field (pop fields))
2022 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
2023 (push (cons (match-string 1 field) (match-string 2 field))
2024 org-table-local-parameters))))
2025 (goto-char beg)
2026 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
2027 (setq c (match-string 1)
2028 fields (org-split-string (match-string 2) " *| *"))
2029 (save-excursion
2030 (beginning-of-line (if (equal c "_") 2 0))
2031 (setq line (org-current-line) col 1)
2032 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2033 (setq fields1 (org-split-string (match-string 1) " *| *"))))
2034 (while (and fields1 (setq field (pop fields)))
2035 (setq v (pop fields1) col (1+ col))
2036 (when (and (stringp field) (stringp v)
2037 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
2038 (push (cons field v) org-table-local-parameters)
2039 (push (list field line col) org-table-named-field-locations))))
2040 ;; Analyse the line types
2041 (goto-char beg)
2042 (setq org-table-current-begin-line (org-current-line)
2043 org-table-current-begin-pos (point)
2044 l org-table-current-begin-line)
2045 (while (looking-at "[ \t]*|\\(-\\)?")
2046 (push (if (match-end 1) 'hline 'dline) types)
2047 (if (match-end 1) (push l hlines) (push l dlines))
2048 (beginning-of-line 2)
2049 (setq l (1+ l)))
2050 (push 'hline types) ;; add an imaginary extra hline to the end
2051 (setq org-table-current-line-types (apply 'vector (nreverse types))
2052 last-dline (car dlines)
2053 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
2054 org-table-hlines (apply 'vector (cons nil (nreverse hlines))))
2055 (org-goto-line last-dline)
2056 (let* ((l last-dline)
2057 (fields (org-split-string
2058 (buffer-substring (point-at-bol) (point-at-eol))
2059 "[ \t]*|[ \t]*"))
2060 (nfields (length fields))
2061 al al2)
2062 (loop for i from 1 to nfields do
2063 (push (list (format "LR%d" i) l i) al)
2064 (push (cons (format "LR%d" i) (nth (1- i) fields)) al2))
2065 (setq org-table-named-field-locations
2066 (append org-table-named-field-locations al))
2067 (setq org-table-local-parameters
2068 (append org-table-local-parameters al2))))))
2071 (defun org-table-maybe-eval-formula ()
2072 "Check if the current field starts with \"=\" or \":=\".
2073 If yes, store the formula and apply it."
2074 ;; We already know we are in a table. Get field will only return a formula
2075 ;; when appropriate. It might return a separator line, but no problem.
2076 (when org-table-formula-evaluate-inline
2077 (let* ((field (org-trim (or (org-table-get-field) "")))
2078 named eq)
2079 (when (string-match "^:?=\\(.*\\)" field)
2080 (setq named (equal (string-to-char field) ?:)
2081 eq (match-string 1 field))
2082 (if (or (fboundp 'calc-eval)
2083 (equal (substring eq 0 (min 2 (length eq))) "'("))
2084 (org-table-eval-formula (if named '(4) nil)
2085 (org-table-formula-from-user eq))
2086 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2088 (defvar org-recalc-commands nil
2089 "List of commands triggering the recalculation of a line.
2090 Will be filled automatically during use.")
2092 (defvar org-recalc-marks
2093 '((" " . "Unmarked: no special line, no automatic recalculation")
2094 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2095 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
2096 ("!" . "Column name definition line. Reference in formula as $name.")
2097 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
2098 ("_" . "Names for values in row below this one.")
2099 ("^" . "Names for values in row above this one.")))
2101 (defun org-table-rotate-recalc-marks (&optional newchar)
2102 "Rotate the recalculation mark in the first column.
2103 If in any row, the first field is not consistent with a mark,
2104 insert a new column for the markers.
2105 When there is an active region, change all the lines in the region,
2106 after prompting for the marking character.
2107 After each change, a message will be displayed indicating the meaning
2108 of the new mark."
2109 (interactive)
2110 (unless (org-at-table-p) (error "Not at a table"))
2111 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
2112 (beg (org-table-begin))
2113 (end (org-table-end))
2114 (l (org-current-line))
2115 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2116 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2117 (have-col
2118 (save-excursion
2119 (goto-char beg)
2120 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
2121 (col (org-table-current-column))
2122 (forcenew (car (assoc newchar org-recalc-marks)))
2123 epos new)
2124 (when l1
2125 (message "Change region to what mark? Type # * ! $ or SPC: ")
2126 (setq newchar (char-to-string (read-char-exclusive))
2127 forcenew (car (assoc newchar org-recalc-marks))))
2128 (if (and newchar (not forcenew))
2129 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2130 newchar))
2131 (if l1 (org-goto-line l1))
2132 (save-excursion
2133 (beginning-of-line 1)
2134 (unless (looking-at org-table-dataline-regexp)
2135 (error "Not at a table data line")))
2136 (unless have-col
2137 (org-table-goto-column 1)
2138 (org-table-insert-column)
2139 (org-table-goto-column (1+ col)))
2140 (setq epos (point-at-eol))
2141 (save-excursion
2142 (beginning-of-line 1)
2143 (org-table-get-field
2144 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2145 (concat " "
2146 (setq new (or forcenew
2147 (cadr (member (match-string 1) marks))))
2148 " ")
2149 " # ")))
2150 (if (and l1 l2)
2151 (progn
2152 (org-goto-line l1)
2153 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
2154 (and (looking-at org-table-dataline-regexp)
2155 (org-table-get-field 1 (concat " " new " "))))
2156 (org-goto-line l1)))
2157 (if (not (= epos (point-at-eol))) (org-table-align))
2158 (org-goto-line l)
2159 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
2161 (defun org-table-maybe-recalculate-line ()
2162 "Recompute the current line if marked for it, and if we haven't just done it."
2163 (interactive)
2164 (and org-table-allow-automatic-line-recalculation
2165 (not (and (memq last-command org-recalc-commands)
2166 (equal org-last-recalc-line (org-current-line))))
2167 (save-excursion (beginning-of-line 1)
2168 (looking-at org-table-auto-recalculate-regexp))
2169 (org-table-recalculate) t))
2171 (defvar modes)
2172 (defsubst org-set-calc-mode (var &optional value)
2173 (if (stringp var)
2174 (setq var (assoc var '(("D" calc-angle-mode deg)
2175 ("R" calc-angle-mode rad)
2176 ("F" calc-prefer-frac t)
2177 ("S" calc-symbolic-mode t)))
2178 value (nth 2 var) var (nth 1 var)))
2179 (if (memq var modes)
2180 (setcar (cdr (memq var modes)) value)
2181 (cons var (cons value modes)))
2182 modes)
2184 (defun org-table-eval-formula (&optional arg equation
2185 suppress-align suppress-const
2186 suppress-store suppress-analysis)
2187 "Replace the table field value at the cursor by the result of a calculation.
2189 This function makes use of Dave Gillespie's Calc package, in my view the
2190 most exciting program ever written for GNU Emacs. So you need to have Calc
2191 installed in order to use this function.
2193 In a table, this command replaces the value in the current field with the
2194 result of a formula. It also installs the formula as the \"current\" column
2195 formula, by storing it in a special line below the table. When called
2196 with a `C-u' prefix, the current field must be a named field, and the
2197 formula is installed as valid in only this specific field.
2199 When called with two `C-u' prefixes, insert the active equation
2200 for the field back into the current field, so that it can be
2201 edited there. This is useful in order to use \\[org-table-show-reference]
2202 to check the referenced fields.
2204 When called, the command first prompts for a formula, which is read in
2205 the minibuffer. Previously entered formulas are available through the
2206 history list, and the last used formula is offered as a default.
2207 These stored formulas are adapted correctly when moving, inserting, or
2208 deleting columns with the corresponding commands.
2210 The formula can be any algebraic expression understood by the Calc package.
2211 For details, see the Org-mode manual.
2213 This function can also be called from Lisp programs and offers
2214 additional arguments: EQUATION can be the formula to apply. If this
2215 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2216 used to speed-up recursive calls by by-passing unnecessary aligns.
2217 SUPPRESS-CONST suppresses the interpretation of constants in the
2218 formula, assuming that this has been done already outside the function.
2219 SUPPRESS-STORE means the formula should not be stored, either because
2220 it is already stored, or because it is a modified equation that should
2221 not overwrite the stored one."
2222 (interactive "P")
2223 (org-table-check-inside-data-field)
2224 (or suppress-analysis (org-table-get-specials))
2225 (if (equal arg '(16))
2226 (let ((eq (org-table-current-field-formula)))
2227 (or eq (error "No equation active for current field"))
2228 (org-table-get-field nil eq)
2229 (org-table-align)
2230 (setq org-table-may-need-update t))
2231 (let* (fields
2232 (ndown (if (integerp arg) arg 1))
2233 (org-table-automatic-realign nil)
2234 (case-fold-search nil)
2235 (down (> ndown 1))
2236 (formula (if (and equation suppress-store)
2237 equation
2238 (org-table-get-formula equation (equal arg '(4)))))
2239 (n0 (org-table-current-column))
2240 (modes (copy-sequence org-calc-default-modes))
2241 (numbers nil) ; was a variable, now fixed default
2242 (keep-empty nil)
2243 n form form0 bw fmt x ev orig c lispp literal)
2244 ;; Parse the format string. Since we have a lot of modes, this is
2245 ;; a lot of work. However, I think calc still uses most of the time.
2246 (if (string-match ";" formula)
2247 (let ((tmp (org-split-string formula ";")))
2248 (setq formula (car tmp)
2249 fmt (concat (cdr (assoc "%" org-table-local-parameters))
2250 (nth 1 tmp)))
2251 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
2252 (setq c (string-to-char (match-string 1 fmt))
2253 n (string-to-number (match-string 2 fmt)))
2254 (if (= c ?p)
2255 (setq modes (org-set-calc-mode 'calc-internal-prec n))
2256 (setq modes (org-set-calc-mode
2257 'calc-float-format
2258 (list (cdr (assoc c '((?n . float) (?f . fix)
2259 (?s . sci) (?e . eng))))
2260 n))))
2261 (setq fmt (replace-match "" t t fmt)))
2262 (if (string-match "[NT]" fmt)
2263 (setq numbers (equal (match-string 0 fmt) "N")
2264 fmt (replace-match "" t t fmt)))
2265 (if (string-match "L" fmt)
2266 (setq literal t
2267 fmt (replace-match "" t t fmt)))
2268 (if (string-match "E" fmt)
2269 (setq keep-empty t
2270 fmt (replace-match "" t t fmt)))
2271 (while (string-match "[DRFS]" fmt)
2272 (setq modes (org-set-calc-mode (match-string 0 fmt)))
2273 (setq fmt (replace-match "" t t fmt)))
2274 (unless (string-match "\\S-" fmt)
2275 (setq fmt nil))))
2276 (if (and (not suppress-const) org-table-formula-use-constants)
2277 (setq formula (org-table-formula-substitute-names formula)))
2278 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
2279 (while (> ndown 0)
2280 (setq fields (org-split-string
2281 (org-no-properties
2282 (buffer-substring (point-at-bol) (point-at-eol)))
2283 " *| *"))
2284 (if (eq numbers t)
2285 (setq fields (mapcar
2286 (lambda (x) (number-to-string (string-to-number x)))
2287 fields)))
2288 (setq ndown (1- ndown))
2289 (setq form (copy-sequence formula)
2290 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
2291 (if (and lispp literal) (setq lispp 'literal))
2293 ;; Insert row and column number of formula result field
2294 (while (string-match "[@$]#" form)
2295 (setq form
2296 (replace-match
2297 (format "%d"
2298 (save-match-data
2299 (if (equal (substring form (match-beginning 0)
2300 (1+ (match-beginning 0)))
2301 "@")
2302 (org-table-current-dline)
2303 (org-table-current-column))))
2304 t t form)))
2306 ;; Check for old vertical references
2307 (setq form (org-table-rewrite-old-row-references form))
2308 ;; Insert remote references
2309 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
2310 (setq form
2311 (replace-match
2312 (save-match-data
2313 (org-table-make-reference
2314 (org-table-get-remote-range
2315 (match-string 1 form) (match-string 2 form))
2316 keep-empty numbers lispp))
2317 t t form)))
2318 ;; Insert complex ranges
2319 (while (and (string-match org-table-range-regexp form)
2320 (> (length (match-string 0 form)) 1))
2321 (setq form
2322 (replace-match
2323 (save-match-data
2324 (org-table-make-reference
2325 (org-table-get-range (match-string 0 form) nil n0)
2326 keep-empty numbers lispp))
2327 t t form)))
2328 ;; Insert simple ranges
2329 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
2330 (setq form
2331 (replace-match
2332 (save-match-data
2333 (org-table-make-reference
2334 (org-sublist
2335 fields (string-to-number (match-string 1 form))
2336 (string-to-number (match-string 2 form)))
2337 keep-empty numbers lispp))
2338 t t form)))
2339 (setq form0 form)
2340 ;; Insert the references to fields in same row
2341 (while (string-match "\\$\\([0-9]+\\)" form)
2342 (setq n (string-to-number (match-string 1 form))
2343 x (nth (1- (if (= n 0) n0 n)) fields))
2344 (unless x (error "Invalid field specifier \"%s\""
2345 (match-string 0 form)))
2346 (setq form (replace-match
2347 (save-match-data
2348 (org-table-make-reference x nil numbers lispp))
2349 t t form)))
2351 (if lispp
2352 (setq ev (condition-case nil
2353 (eval (eval (read form)))
2354 (error "#ERROR"))
2355 ev (if (numberp ev) (number-to-string ev) ev))
2356 (or (fboundp 'calc-eval)
2357 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2358 (setq ev (calc-eval (cons form modes)
2359 (if numbers 'num))))
2361 (when org-table-formula-debug
2362 (with-output-to-temp-buffer "*Substitution History*"
2363 (princ (format "Substitution history of formula
2364 Orig: %s
2365 $xyz-> %s
2366 @r$c-> %s
2367 $1-> %s\n" orig formula form0 form))
2368 (if (listp ev)
2369 (princ (format " %s^\nError: %s"
2370 (make-string (car ev) ?\-) (nth 1 ev)))
2371 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2372 ev (or fmt "NONE")
2373 (if fmt (format fmt (string-to-number ev)) ev)))))
2374 (setq bw (get-buffer-window "*Substitution History*"))
2375 (org-fit-window-to-buffer bw)
2376 (unless (and (interactive-p) (not ndown))
2377 (unless (let (inhibit-redisplay)
2378 (y-or-n-p "Debugging Formula. Continue to next? "))
2379 (org-table-align)
2380 (error "Abort"))
2381 (delete-window bw)
2382 (message "")))
2383 (if (listp ev) (setq fmt nil ev "#ERROR"))
2384 (org-table-justify-field-maybe
2385 (if fmt (format fmt (string-to-number ev)) ev))
2386 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2387 (call-interactively 'org-return)
2388 (setq ndown 0)))
2389 (and down (org-table-maybe-recalculate-line))
2390 (or suppress-align (and org-table-may-need-update
2391 (org-table-align))))))
2393 (defun org-table-put-field-property (prop value)
2394 (save-excursion
2395 (put-text-property (progn (skip-chars-backward "^|") (point))
2396 (progn (skip-chars-forward "^|") (point))
2397 prop value)))
2399 (defun org-table-get-range (desc &optional tbeg col highlight)
2400 "Get a calc vector from a column, according to descriptor DESC.
2401 Optional arguments TBEG and COL can give the beginning of the table and
2402 the current column, to avoid unnecessary parsing.
2403 HIGHLIGHT means just highlight the range."
2404 (if (not (equal (string-to-char desc) ?@))
2405 (setq desc (concat "@" desc)))
2406 (save-excursion
2407 (or tbeg (setq tbeg (org-table-begin)))
2408 (or col (setq col (org-table-current-column)))
2409 (let ((thisline (org-current-line))
2410 beg end c1 c2 r1 r2 rangep tmp)
2411 (unless (string-match org-table-range-regexp desc)
2412 (error "Invalid table range specifier `%s'" desc))
2413 (setq rangep (match-end 3)
2414 r1 (and (match-end 1) (match-string 1 desc))
2415 r2 (and (match-end 4) (match-string 4 desc))
2416 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
2417 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
2419 (and c1 (setq c1 (+ (string-to-number c1)
2420 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
2421 (and c2 (setq c2 (+ (string-to-number c2)
2422 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
2423 (if (equal r1 "") (setq r1 nil))
2424 (if (equal r2 "") (setq r2 nil))
2425 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
2426 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
2427 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2428 (if (not r1) (setq r1 thisline))
2429 (if (not r2) (setq r2 thisline))
2430 (if (not c1) (setq c1 col))
2431 (if (not c2) (setq c2 col))
2432 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
2433 ;; just one field
2434 (progn
2435 (org-goto-line r1)
2436 (while (not (looking-at org-table-dataline-regexp))
2437 (beginning-of-line 2))
2438 (prog1 (org-trim (org-table-get-field c1))
2439 (if highlight (org-table-highlight-rectangle (point) (point)))))
2440 ;; A range, return a vector
2441 ;; First sort the numbers to get a regular ractangle
2442 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
2443 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
2444 (org-goto-line r1)
2445 (while (not (looking-at org-table-dataline-regexp))
2446 (beginning-of-line 2))
2447 (org-table-goto-column c1)
2448 (setq beg (point))
2449 (org-goto-line r2)
2450 (while (not (looking-at org-table-dataline-regexp))
2451 (beginning-of-line 0))
2452 (org-table-goto-column c2)
2453 (setq end (point))
2454 (if highlight
2455 (org-table-highlight-rectangle
2456 beg (progn (skip-chars-forward "^|\n") (point))))
2457 ;; return string representation of calc vector
2458 (mapcar 'org-trim
2459 (apply 'append (org-table-copy-region beg end)))))))
2461 (defun org-table-get-descriptor-line (desc &optional cline bline table)
2462 "Analyze descriptor DESC and retrieve the corresponding line number.
2463 The cursor is currently in line CLINE, the table begins in line BLINE,
2464 and TABLE is a vector with line types."
2465 (if (string-match "^[0-9]+$" desc)
2466 (aref org-table-dlines (string-to-number desc))
2467 (setq cline (or cline (org-current-line))
2468 bline (or bline org-table-current-begin-line)
2469 table (or table org-table-current-line-types))
2470 (if (or
2471 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
2472 ;; 1 2 3 4 5 6
2473 (and (not (match-end 3)) (not (match-end 6)))
2474 (and (match-end 3) (match-end 6) (not (match-end 5))))
2475 (error "invalid row descriptor `%s'" desc))
2476 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
2477 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
2478 (odir (and (match-end 5) (match-string 5 desc)))
2479 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
2480 (i (- cline bline))
2481 (rel (and (match-end 6)
2482 (or (and (match-end 1) (not (match-end 3)))
2483 (match-end 5)))))
2484 (if (and hn (not hdir))
2485 (progn
2486 (setq i 0 hdir "+")
2487 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
2488 (if (and (not hn) on (not odir))
2489 (error "should never happen");;(aref org-table-dlines on)
2490 (if (and hn (> hn 0))
2491 (setq i (org-table-find-row-type table i 'hline (equal hdir "-")
2492 nil hn cline desc)))
2493 (if on
2494 (setq i (org-table-find-row-type table i 'dline (equal odir "-")
2495 rel on cline desc)))
2496 (+ bline i)))))
2498 (defun org-table-find-row-type (table i type backwards relative n cline desc)
2499 "FIXME: Needs more documentation."
2500 (let ((l (length table)))
2501 (while (> n 0)
2502 (while (and (setq i (+ i (if backwards -1 1)))
2503 (>= i 0) (< i l)
2504 (not (eq (aref table i) type))
2505 (if (and relative (eq (aref table i) 'hline))
2506 (cond
2507 ((eq org-table-relative-ref-may-cross-hline t) t)
2508 ((eq org-table-relative-ref-may-cross-hline 'error)
2509 (error "Row descriptor %s used in line %d crosses hline" desc cline))
2510 (t (setq i (- i (if backwards -1 1))
2511 n 1)
2512 nil))
2513 t)))
2514 (setq n (1- n)))
2515 (if (or (< i 0) (>= i l))
2516 (error "Row descriptor %s used in line %d leads outside table"
2517 desc cline)
2518 i)))
2520 (defun org-table-rewrite-old-row-references (s)
2521 (if (string-match "&[-+0-9I]" s)
2522 (error "Formula contains old &row reference, please rewrite using @-syntax")
2525 (defun org-table-make-reference (elements keep-empty numbers lispp)
2526 "Convert list ELEMENTS to something appropriate to insert into formula.
2527 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2528 NUMBERS indicates that everything should be converted to numbers.
2529 LISPP means to return something appropriate for a Lisp list."
2530 (if (stringp elements) ; just a single val
2531 (if lispp
2532 (if (eq lispp 'literal)
2533 elements
2534 (prin1-to-string (if numbers (string-to-number elements) elements)))
2535 (if (equal elements "") (setq elements "0"))
2536 (if numbers (setq elements (number-to-string (string-to-number elements))))
2537 (concat "(" elements ")"))
2538 (unless keep-empty
2539 (setq elements
2540 (delq nil
2541 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
2542 elements))))
2543 (setq elements (or elements '("0")))
2544 (if lispp
2545 (mapconcat
2546 (lambda (x)
2547 (if (eq lispp 'literal)
2549 (prin1-to-string (if numbers (string-to-number x) x))))
2550 elements " ")
2551 (concat "[" (mapconcat
2552 (lambda (x)
2553 (if numbers (number-to-string (string-to-number x)) x))
2554 elements
2555 ",") "]"))))
2557 (defun org-table-recalculate (&optional all noalign)
2558 "Recalculate the current table line by applying all stored formulas.
2559 With prefix arg ALL, do this for all lines in the table.
2560 With the prefix argument ALL is `(16)' (a double `C-c C-u' prefix), or if
2561 it is the symbol `iterate', recompute the table until it no longer changes.
2562 If NOALIGN is not nil, do not re-align the table after the computations
2563 are done. This is typically used internally to save time, if it is
2564 known that the table will be realigned a little later anyway."
2565 (interactive "P")
2566 (or (memq this-command org-recalc-commands)
2567 (setq org-recalc-commands (cons this-command org-recalc-commands)))
2568 (unless (org-at-table-p) (error "Not at a table"))
2569 (if (or (eq all 'iterate) (equal all '(16)))
2570 (org-table-iterate)
2571 (org-table-get-specials)
2572 (let* ((eqlist (sort (org-table-get-stored-formulas)
2573 (lambda (a b) (string< (car a) (car b)))))
2574 (inhibit-redisplay (not debug-on-error))
2575 (line-re org-table-dataline-regexp)
2576 (thisline (org-current-line))
2577 (thiscol (org-table-current-column))
2578 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
2579 ;; Insert constants in all formulas
2580 (setq eqlist
2581 (mapcar (lambda (x)
2582 (setcdr x (org-table-formula-substitute-names (cdr x)))
2584 eqlist))
2585 ;; Split the equation list
2586 (while (setq eq (pop eqlist))
2587 (if (<= (string-to-char (car eq)) ?9)
2588 (push eq eqlnum)
2589 (push eq eqlname)))
2590 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
2591 (if all
2592 (progn
2593 (setq end (move-marker (make-marker) (1+ (org-table-end))))
2594 (goto-char (setq beg (org-table-begin)))
2595 (if (re-search-forward org-table-calculate-mark-regexp end t)
2596 ;; This is a table with marked lines, compute selected lines
2597 (setq line-re org-table-recalculate-regexp)
2598 ;; Move forward to the first non-header line
2599 (if (and (re-search-forward org-table-dataline-regexp end t)
2600 (re-search-forward org-table-hline-regexp end t)
2601 (re-search-forward org-table-dataline-regexp end t))
2602 (setq beg (match-beginning 0))
2603 nil))) ;; just leave beg where it is
2604 (setq beg (point-at-bol)
2605 end (move-marker (make-marker) (1+ (point-at-eol)))))
2606 (goto-char beg)
2607 (and all (message "Re-applying formulas to full table..."))
2609 ;; First find the named fields, and mark them untouchable
2610 (remove-text-properties beg end '(org-untouchable t))
2611 (while (setq eq (pop eqlname))
2612 (setq name (car eq)
2613 a (assoc name org-table-named-field-locations))
2614 (and (not a)
2615 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
2616 (setq a (list name
2617 (condition-case nil
2618 (aref org-table-dlines
2619 (string-to-number (match-string 1 name)))
2620 (error (error "Invalid row number in %s"
2621 name)))
2622 (string-to-number (match-string 2 name)))))
2623 (when (and a (or all (equal (nth 1 a) thisline)))
2624 (message "Re-applying formula to field: %s" name)
2625 (org-goto-line (nth 1 a))
2626 (org-table-goto-column (nth 2 a))
2627 (push (append a (list (cdr eq))) eqlname1)
2628 (org-table-put-field-property :org-untouchable t)))
2630 ;; Now evaluate the column formulas, but skip fields covered by
2631 ;; field formulas
2632 (goto-char beg)
2633 (while (re-search-forward line-re end t)
2634 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2635 ;; Unprotected line, recalculate
2636 (and all (message "Re-applying formulas to full table...(line %d)"
2637 (setq cnt (1+ cnt))))
2638 (setq org-last-recalc-line (org-current-line))
2639 (setq eql eqlnum)
2640 (while (setq entry (pop eql))
2641 (org-goto-line org-last-recalc-line)
2642 (org-table-goto-column (string-to-number (car entry)) nil 'force)
2643 (unless (get-text-property (point) :org-untouchable)
2644 (org-table-eval-formula nil (cdr entry)
2645 'noalign 'nocst 'nostore 'noanalysis)))))
2647 ;; Now evaluate the field formulas
2648 (while (setq eq (pop eqlname1))
2649 (message "Re-applying formula to field: %s" (car eq))
2650 (org-goto-line (nth 1 eq))
2651 (org-table-goto-column (nth 2 eq))
2652 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
2653 'nostore 'noanalysis))
2655 (org-goto-line thisline)
2656 (org-table-goto-column thiscol)
2657 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
2658 (or noalign (and org-table-may-need-update (org-table-align))
2659 (and all (message "Re-applying formulas to %d lines...done" cnt)))
2661 ;; back to initial position
2662 (message "Re-applying formulas...done")
2663 (org-goto-line thisline)
2664 (org-table-goto-column thiscol)
2665 (or noalign (and org-table-may-need-update (org-table-align))
2666 (and all (message "Re-applying formulas...done"))))))
2668 (defun org-table-iterate (&optional arg)
2669 "Recalculate the table until it does not change anymore."
2670 (interactive "P")
2671 (let ((imax (if arg (prefix-numeric-value arg) 10))
2672 (i 0)
2673 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2674 thistbl)
2675 (catch 'exit
2676 (while (< i imax)
2677 (setq i (1+ i))
2678 (org-table-recalculate 'all)
2679 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
2680 (if (not (string= lasttbl thistbl))
2681 (setq lasttbl thistbl)
2682 (if (> i 1)
2683 (message "Convergence after %d iterations" i)
2684 (message "Table was already stable"))
2685 (throw 'exit t)))
2686 (error "No convergence after %d iterations" i))))
2688 (defun org-table-recalculate-buffer-tables ()
2689 "Recalculate all tables in the current buffer."
2690 (interactive)
2691 (save-excursion
2692 (save-restriction
2693 (widen)
2694 (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
2696 (defun org-table-iterate-buffer-tables ()
2697 "Iterate all tables in the buffer, to converge inter-table dependencies."
2698 (interactive)
2699 (let* ((imax 10)
2700 (checksum (md5 (buffer-string)))
2703 (i imax))
2704 (save-excursion
2705 (save-restriction
2706 (widen)
2707 (catch 'exit
2708 (while (> i 0)
2709 (setq i (1- i))
2710 (org-table-map-tables (lambda () (org-table-recalculate t)) t)
2711 (if (equal checksum (setq c1 (md5 (buffer-string))))
2712 (progn
2713 (message "Convergence after %d iterations" (- imax i))
2714 (throw 'exit t))
2715 (setq checksum c1)))
2716 (error "No convergence after %d iterations" imax))))))
2718 (defun org-table-formula-substitute-names (f)
2719 "Replace $const with values in string F."
2720 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
2721 ;; First, check for column names
2722 (while (setq start (string-match org-table-column-name-regexp f start))
2723 (setq start (1+ start))
2724 (setq a (assoc (match-string 1 f) org-table-column-names))
2725 (setq f (replace-match (concat "$" (cdr a)) t t f)))
2726 ;; Parameters and constants
2727 (setq start 0)
2728 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start))
2729 (if (match-end 2)
2730 (setq start (match-end 2))
2731 (setq start (1+ start))
2732 (if (setq a (save-match-data
2733 (org-table-get-constant (match-string 1 f))))
2734 (setq f (replace-match
2735 (concat (if pp "(") a (if pp ")")) t t f)))))
2736 (if org-table-formula-debug
2737 (put-text-property 0 (length f) :orig-formula f1 f))
2740 (defun org-table-get-constant (const)
2741 "Find the value for a parameter or constant in a formula.
2742 Parameters get priority."
2743 (or (cdr (assoc const org-table-local-parameters))
2744 (cdr (assoc const org-table-formula-constants-local))
2745 (cdr (assoc const org-table-formula-constants))
2746 (and (fboundp 'constants-get) (constants-get const))
2747 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
2748 (org-entry-get nil (substring const 5) 'inherit))
2749 "#UNDEFINED_NAME"))
2751 (defvar org-table-fedit-map
2752 (let ((map (make-sparse-keymap)))
2753 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
2754 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
2755 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
2756 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
2757 (org-defkey map "\C-c?" 'org-table-show-reference)
2758 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
2759 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
2760 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
2761 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
2762 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
2763 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
2764 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
2765 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
2766 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
2767 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
2768 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
2769 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
2770 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
2771 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
2772 map))
2774 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
2775 '("Edit-Formulas"
2776 ["Finish and Install" org-table-fedit-finish t]
2777 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
2778 ["Abort" org-table-fedit-abort t]
2779 "--"
2780 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
2781 ["Complete Lisp Symbol" lisp-complete-symbol t]
2782 "--"
2783 "Shift Reference at Point"
2784 ["Up" org-table-fedit-ref-up t]
2785 ["Down" org-table-fedit-ref-down t]
2786 ["Left" org-table-fedit-ref-left t]
2787 ["Right" org-table-fedit-ref-right t]
2789 "Change Test Row for Column Formulas"
2790 ["Up" org-table-fedit-line-up t]
2791 ["Down" org-table-fedit-line-down t]
2792 "--"
2793 ["Scroll Table Window" org-table-fedit-scroll t]
2794 ["Scroll Table Window down" org-table-fedit-scroll-down t]
2795 ["Show Table Grid" org-table-fedit-toggle-coordinates
2796 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
2797 org-table-overlay-coordinates)]
2798 "--"
2799 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
2800 :style toggle :selected org-table-buffer-is-an]))
2802 (defvar org-pos)
2804 (defun org-table-edit-formulas ()
2805 "Edit the formulas of the current table in a separate buffer."
2806 (interactive)
2807 (when (save-excursion (beginning-of-line 1) (looking-at "[ \t]*#\\+TBLFM"))
2808 (beginning-of-line 0))
2809 (unless (org-at-table-p) (error "Not at a table"))
2810 (org-table-get-specials)
2811 (let ((key (org-table-current-field-formula 'key 'noerror))
2812 (eql (sort (org-table-get-stored-formulas 'noerror)
2813 'org-table-formula-less-p))
2814 (pos (move-marker (make-marker) (point)))
2815 (startline 1)
2816 (wc (current-window-configuration))
2817 (sel-win (selected-window))
2818 (titles '((column . "# Column Formulas\n")
2819 (field . "# Field Formulas\n")
2820 (named . "# Named Field Formulas\n")))
2821 entry s type title)
2822 (org-switch-to-buffer-other-window "*Edit Formulas*")
2823 (erase-buffer)
2824 ;; Keep global-font-lock-mode from turning on font-lock-mode
2825 (let ((font-lock-global-modes '(not fundamental-mode)))
2826 (fundamental-mode))
2827 (org-set-local 'font-lock-global-modes (list 'not major-mode))
2828 (org-set-local 'org-pos pos)
2829 (org-set-local 'org-window-configuration wc)
2830 (org-set-local 'org-selected-window sel-win)
2831 (use-local-map org-table-fedit-map)
2832 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
2833 (easy-menu-add org-table-fedit-menu)
2834 (setq startline (org-current-line))
2835 (while (setq entry (pop eql))
2836 (setq type (cond
2837 ((equal (string-to-char (car entry)) ?@) 'field)
2838 ((string-match "^[0-9]" (car entry)) 'column)
2839 (t 'named)))
2840 (when (setq title (assq type titles))
2841 (or (bobp) (insert "\n"))
2842 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
2843 (setq titles (delq title titles)))
2844 (if (equal key (car entry)) (setq startline (org-current-line)))
2845 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
2846 (car entry) " = " (cdr entry) "\n"))
2847 (remove-text-properties 0 (length s) '(face nil) s)
2848 (insert s))
2849 (if (eq org-table-use-standard-references t)
2850 (org-table-fedit-toggle-ref-type))
2851 (org-goto-line startline)
2852 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
2854 (defun org-table-fedit-post-command ()
2855 (when (not (memq this-command '(lisp-complete-symbol)))
2856 (let ((win (selected-window)))
2857 (save-excursion
2858 (condition-case nil
2859 (org-table-show-reference)
2860 (error nil))
2861 (select-window win)))))
2863 (defun org-table-formula-to-user (s)
2864 "Convert a formula from internal to user representation."
2865 (if (eq org-table-use-standard-references t)
2866 (org-table-convert-refs-to-an s)
2869 (defun org-table-formula-from-user (s)
2870 "Convert a formula from user to internal representation."
2871 (if org-table-use-standard-references
2872 (org-table-convert-refs-to-rc s)
2875 (defun org-table-convert-refs-to-rc (s)
2876 "Convert spreadsheet references from AB7 to @7$28.
2877 Works for single references, but also for entire formulas and even the
2878 full TBLFM line."
2879 (let ((start 0))
2880 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^)]*)\\)" s start)
2881 (cond
2882 ((match-end 3)
2883 ;; format match, just advance
2884 (setq start (match-end 0)))
2885 ((and (> (match-beginning 0) 0)
2886 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
2887 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
2888 ;; 3.e5 or something like this.
2889 (setq start (match-end 0)))
2890 ((or (> (- (match-end 1) (match-beginning 1)) 2)
2891 ;; (member (match-string 1 s)
2892 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
2894 ;; function name, just advance
2895 (setq start (match-end 0)))
2897 (setq start (match-beginning 0)
2898 s (replace-match
2899 (if (equal (match-string 2 s) "&")
2900 (format "$%d" (org-letters-to-number (match-string 1 s)))
2901 (format "@%d$%d"
2902 (string-to-number (match-string 2 s))
2903 (org-letters-to-number (match-string 1 s))))
2904 t t s)))))
2907 (defun org-table-convert-refs-to-an (s)
2908 "Convert spreadsheet references from to @7$28 to AB7.
2909 Works for single references, but also for entire formulas and even the
2910 full TBLFM line."
2911 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
2912 (setq s (replace-match
2913 (format "%s%d"
2914 (org-number-to-letters
2915 (string-to-number (match-string 2 s)))
2916 (string-to-number (match-string 1 s)))
2917 t t s)))
2918 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
2919 (setq s (replace-match (concat "\\1"
2920 (org-number-to-letters
2921 (string-to-number (match-string 2 s))) "&")
2922 t nil s)))
2925 (defun org-letters-to-number (s)
2926 "Convert a base 26 number represented by letters into an integer.
2927 For example: AB -> 28."
2928 (let ((n 0))
2929 (setq s (upcase s))
2930 (while (> (length s) 0)
2931 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
2932 s (substring s 1)))
2935 (defun org-number-to-letters (n)
2936 "Convert an integer into a base 26 number represented by letters.
2937 For example: 28 -> AB."
2938 (let ((s ""))
2939 (while (> n 0)
2940 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
2941 n (/ (1- n) 26)))
2944 (defun org-table-fedit-convert-buffer (function)
2945 "Convert all references in this buffer, using FUNCTION."
2946 (let ((line (org-current-line)))
2947 (goto-char (point-min))
2948 (while (not (eobp))
2949 (insert (funcall function (buffer-substring (point) (point-at-eol))))
2950 (delete-region (point) (point-at-eol))
2951 (or (eobp) (forward-char 1)))
2952 (org-goto-line line)))
2954 (defun org-table-fedit-toggle-ref-type ()
2955 "Convert all references in the buffer from B3 to @3$2 and back."
2956 (interactive)
2957 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
2958 (org-table-fedit-convert-buffer
2959 (if org-table-buffer-is-an
2960 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
2961 (message "Reference type switched to %s"
2962 (if org-table-buffer-is-an "A1 etc" "@row$column")))
2964 (defun org-table-fedit-ref-up ()
2965 "Shift the reference at point one row/hline up."
2966 (interactive)
2967 (org-table-fedit-shift-reference 'up))
2968 (defun org-table-fedit-ref-down ()
2969 "Shift the reference at point one row/hline down."
2970 (interactive)
2971 (org-table-fedit-shift-reference 'down))
2972 (defun org-table-fedit-ref-left ()
2973 "Shift the reference at point one field to the left."
2974 (interactive)
2975 (org-table-fedit-shift-reference 'left))
2976 (defun org-table-fedit-ref-right ()
2977 "Shift the reference at point one field to the right."
2978 (interactive)
2979 (org-table-fedit-shift-reference 'right))
2981 (defun org-table-fedit-shift-reference (dir)
2982 (cond
2983 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
2984 (if (memq dir '(left right))
2985 (org-rematch-and-replace 1 (eq dir 'left))
2986 (error "Cannot shift reference in this direction")))
2987 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
2988 ;; A B3-like reference
2989 (if (memq dir '(up down))
2990 (org-rematch-and-replace 2 (eq dir 'up))
2991 (org-rematch-and-replace 1 (eq dir 'left))))
2992 ((org-at-regexp-p
2993 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
2994 ;; An internal reference
2995 (if (memq dir '(up down))
2996 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
2997 (org-rematch-and-replace 5 (eq dir 'left))))))
2999 (defun org-rematch-and-replace (n &optional decr hline)
3000 "Re-match the group N, and replace it with the shifted refrence."
3001 (or (match-end n) (error "Cannot shift reference in this direction"))
3002 (goto-char (match-beginning n))
3003 (and (looking-at (regexp-quote (match-string n)))
3004 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3005 t t)))
3007 (defun org-table-shift-refpart (ref &optional decr hline)
3008 "Shift a refrence part REF.
3009 If DECR is set, decrease the references row/column, else increase.
3010 If HLINE is set, this may be a hline reference, it certainly is not
3011 a translation reference."
3012 (save-match-data
3013 (let* ((sign (string-match "^[-+]" ref)) n)
3015 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3016 (cond
3017 ((and hline (string-match "^I+" ref))
3018 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3019 (setq n (+ n (if decr -1 1)))
3020 (if (= n 0) (setq n (+ n (if decr -1 1))))
3021 (if sign
3022 (setq sign (if (< n 0) "-" "+") n (abs n))
3023 (setq n (max 1 n)))
3024 (concat sign (make-string n ?I)))
3026 ((string-match "^[0-9]+" ref)
3027 (setq n (string-to-number (concat sign ref)))
3028 (setq n (+ n (if decr -1 1)))
3029 (if sign
3030 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3031 (number-to-string (max 1 n))))
3033 ((string-match "^[a-zA-Z]+" ref)
3034 (org-number-to-letters
3035 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3037 (t (error "Cannot shift reference"))))))
3039 (defun org-table-fedit-toggle-coordinates ()
3040 "Toggle the display of coordinates in the referenced table."
3041 (interactive)
3042 (let ((pos (marker-position org-pos)))
3043 (with-current-buffer (marker-buffer org-pos)
3044 (save-excursion
3045 (goto-char pos)
3046 (org-table-toggle-coordinate-overlays)))))
3048 (defun org-table-fedit-finish (&optional arg)
3049 "Parse the buffer for formula definitions and install them.
3050 With prefix ARG, apply the new formulas to the table."
3051 (interactive "P")
3052 (org-table-remove-rectangle-highlight)
3053 (if org-table-use-standard-references
3054 (progn
3055 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3056 (setq org-table-buffer-is-an nil)))
3057 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3058 (goto-char (point-min))
3059 (while (re-search-forward
3060 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3061 nil t)
3062 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3063 form (match-string 3))
3064 (setq form (org-trim form))
3065 (when (not (equal form ""))
3066 (while (string-match "[ \t]*\n[ \t]*" form)
3067 (setq form (replace-match " " t t form)))
3068 (when (assoc var eql)
3069 (error "Double formulas for %s" var))
3070 (push (cons var form) eql)))
3071 (setq org-pos nil)
3072 (set-window-configuration org-window-configuration)
3073 (select-window sel-win)
3074 (goto-char pos)
3075 (unless (org-at-table-p)
3076 (error "Lost table position - cannot install formulae"))
3077 (org-table-store-formulas eql)
3078 (move-marker pos nil)
3079 (kill-buffer "*Edit Formulas*")
3080 (if arg
3081 (org-table-recalculate 'all)
3082 (message "New formulas installed - press C-u C-c C-c to apply."))))
3084 (defun org-table-fedit-abort ()
3085 "Abort editing formulas, without installing the changes."
3086 (interactive)
3087 (org-table-remove-rectangle-highlight)
3088 (let ((pos org-pos) (sel-win org-selected-window))
3089 (set-window-configuration org-window-configuration)
3090 (select-window sel-win)
3091 (goto-char pos)
3092 (move-marker pos nil)
3093 (message "Formula editing aborted without installing changes")))
3095 (defun org-table-fedit-lisp-indent ()
3096 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3097 (interactive)
3098 (let ((pos (point)) beg end ind)
3099 (beginning-of-line 1)
3100 (cond
3101 ((looking-at "[ \t]")
3102 (goto-char pos)
3103 (call-interactively 'lisp-indent-line))
3104 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3105 ((not (fboundp 'pp-buffer))
3106 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3107 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3108 (goto-char (- (match-end 0) 2))
3109 (setq beg (point))
3110 (setq ind (make-string (current-column) ?\ ))
3111 (condition-case nil (forward-sexp 1)
3112 (error
3113 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3114 (setq end (point))
3115 (save-restriction
3116 (narrow-to-region beg end)
3117 (if (eq last-command this-command)
3118 (progn
3119 (goto-char (point-min))
3120 (setq this-command nil)
3121 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3122 (replace-match " ")))
3123 (pp-buffer)
3124 (untabify (point-min) (point-max))
3125 (goto-char (1+ (point-min)))
3126 (while (re-search-forward "^." nil t)
3127 (beginning-of-line 1)
3128 (insert ind))
3129 (goto-char (point-max))
3130 (backward-delete-char 1)))
3131 (goto-char beg))
3132 (t nil))))
3134 (defvar org-show-positions nil)
3136 (defun org-table-show-reference (&optional local)
3137 "Show the location/value of the $ expression at point."
3138 (interactive)
3139 (org-table-remove-rectangle-highlight)
3140 (catch 'exit
3141 (let ((pos (if local (point) org-pos))
3142 (face2 'highlight)
3143 (org-inhibit-highlight-removal t)
3144 (win (selected-window))
3145 (org-show-positions nil)
3146 var name e what match dest)
3147 (if local (org-table-get-specials))
3148 (setq what (cond
3149 ((or (org-at-regexp-p org-table-range-regexp2)
3150 (org-at-regexp-p org-table-translate-regexp)
3151 (org-at-regexp-p org-table-range-regexp))
3152 (setq match
3153 (save-match-data
3154 (org-table-convert-refs-to-rc (match-string 0))))
3155 'range)
3156 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3157 ((org-at-regexp-p "\\$[0-9]+") 'column)
3158 ((not local) nil)
3159 (t (error "No reference at point")))
3160 match (and what (or match (match-string 0))))
3161 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3162 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3163 'secondary-selection))
3164 (org-add-hook 'before-change-functions
3165 'org-table-remove-rectangle-highlight)
3166 (if (eq what 'name) (setq var (substring match 1)))
3167 (when (eq what 'range)
3168 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
3169 (setq match (org-table-formula-substitute-names match)))
3170 (unless local
3171 (save-excursion
3172 (end-of-line 1)
3173 (re-search-backward "^\\S-" nil t)
3174 (beginning-of-line 1)
3175 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3176 (setq dest
3177 (save-match-data
3178 (org-table-convert-refs-to-rc (match-string 1))))
3179 (org-table-add-rectangle-overlay
3180 (match-beginning 1) (match-end 1) face2))))
3181 (if (and (markerp pos) (marker-buffer pos))
3182 (if (get-buffer-window (marker-buffer pos))
3183 (select-window (get-buffer-window (marker-buffer pos)))
3184 (org-switch-to-buffer-other-window (get-buffer-window
3185 (marker-buffer pos)))))
3186 (goto-char pos)
3187 (org-table-force-dataline)
3188 (when dest
3189 (setq name (substring dest 1))
3190 (cond
3191 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3192 (setq e (assoc name org-table-named-field-locations))
3193 (org-goto-line (nth 1 e))
3194 (org-table-goto-column (nth 2 e)))
3195 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
3196 (let ((l (string-to-number (match-string 1 dest)))
3197 (c (string-to-number (match-string 2 dest))))
3198 (org-goto-line (aref org-table-dlines l))
3199 (org-table-goto-column c)))
3200 (t (org-table-goto-column (string-to-number name))))
3201 (move-marker pos (point))
3202 (org-table-highlight-rectangle nil nil face2))
3203 (cond
3204 ((equal dest match))
3205 ((not match))
3206 ((eq what 'range)
3207 (condition-case nil
3208 (save-excursion
3209 (org-table-get-range match nil nil 'highlight))
3210 (error nil)))
3211 ((setq e (assoc var org-table-named-field-locations))
3212 (org-goto-line (nth 1 e))
3213 (org-table-goto-column (nth 2 e))
3214 (org-table-highlight-rectangle (point) (point))
3215 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3216 ((setq e (assoc var org-table-column-names))
3217 (org-table-goto-column (string-to-number (cdr e)))
3218 (org-table-highlight-rectangle (point) (point))
3219 (goto-char (org-table-begin))
3220 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3221 (org-table-end) t)
3222 (progn
3223 (goto-char (match-beginning 1))
3224 (org-table-highlight-rectangle)
3225 (message "Named column (column %s)" (cdr e)))
3226 (error "Column name not found")))
3227 ((eq what 'column)
3228 ;; column number
3229 (org-table-goto-column (string-to-number (substring match 1)))
3230 (org-table-highlight-rectangle (point) (point))
3231 (message "Column %s" (substring match 1)))
3232 ((setq e (assoc var org-table-local-parameters))
3233 (goto-char (org-table-begin))
3234 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3235 (progn
3236 (goto-char (match-beginning 1))
3237 (org-table-highlight-rectangle)
3238 (message "Local parameter."))
3239 (error "Parameter not found")))
3241 (cond
3242 ((not var) (error "No reference at point"))
3243 ((setq e (assoc var org-table-formula-constants-local))
3244 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3245 var (cdr e)))
3246 ((setq e (assoc var org-table-formula-constants))
3247 (message "Constant: $%s=%s in `org-table-formula-constants'."
3248 var (cdr e)))
3249 ((setq e (and (fboundp 'constants-get) (constants-get var)))
3250 (message "Constant: $%s=%s, from `constants.el'%s."
3251 var e (format " (%s units)" constants-unit-system)))
3252 (t (error "Undefined name $%s" var)))))
3253 (goto-char pos)
3254 (when (and org-show-positions
3255 (not (memq this-command '(org-table-fedit-scroll
3256 org-table-fedit-scroll-down))))
3257 (push pos org-show-positions)
3258 (push org-table-current-begin-pos org-show-positions)
3259 (let ((min (apply 'min org-show-positions))
3260 (max (apply 'max org-show-positions)))
3261 (goto-char min) (recenter 0)
3262 (goto-char max)
3263 (or (pos-visible-in-window-p max) (recenter -1))))
3264 (select-window win))))
3266 (defun org-table-force-dataline ()
3267 "Make sure the cursor is in a dataline in a table."
3268 (unless (save-excursion
3269 (beginning-of-line 1)
3270 (looking-at org-table-dataline-regexp))
3271 (let* ((re org-table-dataline-regexp)
3272 (p1 (save-excursion (re-search-forward re nil 'move)))
3273 (p2 (save-excursion (re-search-backward re nil 'move))))
3274 (cond ((and p1 p2)
3275 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
3276 p1 p2)))
3277 ((or p1 p2) (goto-char (or p1 p2)))
3278 (t (error "No table dataline around here"))))))
3280 (defun org-table-fedit-line-up ()
3281 "Move cursor one line up in the window showing the table."
3282 (interactive)
3283 (org-table-fedit-move 'previous-line))
3285 (defun org-table-fedit-line-down ()
3286 "Move cursor one line down in the window showing the table."
3287 (interactive)
3288 (org-table-fedit-move 'next-line))
3290 (defun org-table-fedit-move (command)
3291 "Move the cursor in the window showing the table.
3292 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3293 (let ((org-table-allow-automatic-line-recalculation nil)
3294 (pos org-pos) (win (selected-window)) p)
3295 (select-window (get-buffer-window (marker-buffer org-pos)))
3296 (setq p (point))
3297 (call-interactively command)
3298 (while (and (org-at-table-p)
3299 (org-at-table-hline-p))
3300 (call-interactively command))
3301 (or (org-at-table-p) (goto-char p))
3302 (move-marker pos (point))
3303 (select-window win)))
3305 (defun org-table-fedit-scroll (N)
3306 (interactive "p")
3307 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
3308 (scroll-other-window N)))
3310 (defun org-table-fedit-scroll-down (N)
3311 (interactive "p")
3312 (org-table-fedit-scroll (- N)))
3314 (defvar org-table-rectangle-overlays nil)
3316 (defun org-table-add-rectangle-overlay (beg end &optional face)
3317 "Add a new overlay."
3318 (let ((ov (make-overlay beg end)))
3319 (overlay-put ov 'face (or face 'secondary-selection))
3320 (push ov org-table-rectangle-overlays)))
3322 (defun org-table-highlight-rectangle (&optional beg end face)
3323 "Highlight rectangular region in a table."
3324 (setq beg (or beg (point)) end (or end (point)))
3325 (let ((b (min beg end))
3326 (e (max beg end))
3327 l1 c1 l2 c2 tmp)
3328 (and (boundp 'org-show-positions)
3329 (setq org-show-positions (cons b (cons e org-show-positions))))
3330 (goto-char (min beg end))
3331 (setq l1 (org-current-line)
3332 c1 (org-table-current-column))
3333 (goto-char (max beg end))
3334 (setq l2 (org-current-line)
3335 c2 (org-table-current-column))
3336 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
3337 (org-goto-line l1)
3338 (beginning-of-line 1)
3339 (loop for line from l1 to l2 do
3340 (when (looking-at org-table-dataline-regexp)
3341 (org-table-goto-column c1)
3342 (skip-chars-backward "^|\n") (setq beg (point))
3343 (org-table-goto-column c2)
3344 (skip-chars-forward "^|\n") (setq end (point))
3345 (org-table-add-rectangle-overlay beg end face))
3346 (beginning-of-line 2))
3347 (goto-char b))
3348 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
3350 (defun org-table-remove-rectangle-highlight (&rest ignore)
3351 "Remove the rectangle overlays."
3352 (unless org-inhibit-highlight-removal
3353 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
3354 (mapc 'delete-overlay org-table-rectangle-overlays)
3355 (setq org-table-rectangle-overlays nil)))
3357 (defvar org-table-coordinate-overlays nil
3358 "Collects the coordinate grid overlays, so that they can be removed.")
3359 (make-variable-buffer-local 'org-table-coordinate-overlays)
3361 (defun org-table-overlay-coordinates ()
3362 "Add overlays to the table at point, to show row/column coordinates."
3363 (interactive)
3364 (mapc 'delete-overlay org-table-coordinate-overlays)
3365 (setq org-table-coordinate-overlays nil)
3366 (save-excursion
3367 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
3368 (goto-char (org-table-begin))
3369 (while (org-at-table-p)
3370 (setq eol (point-at-eol))
3371 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
3372 (push ov org-table-coordinate-overlays)
3373 (setq hline (looking-at org-table-hline-regexp))
3374 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
3375 (format "%4d" (setq id (1+ id)))))
3376 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
3377 (when hline
3378 (setq ic 0)
3379 (while (re-search-forward "[+|]\\(-+\\)" eol t)
3380 (setq beg (1+ (match-beginning 0))
3381 ic (1+ ic)
3382 s1 (concat "$" (int-to-string ic))
3383 s2 (org-number-to-letters ic)
3384 str (if (eq org-table-use-standard-references t) s2 s1))
3385 (setq ov (make-overlay beg (+ beg (length str))))
3386 (push ov org-table-coordinate-overlays)
3387 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
3388 (beginning-of-line 2)))))
3390 (defun org-table-toggle-coordinate-overlays ()
3391 "Toggle the display of Row/Column numbers in tables."
3392 (interactive)
3393 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
3394 (message "Row/Column number display turned %s"
3395 (if org-table-overlay-coordinates "on" "off"))
3396 (if (and (org-at-table-p) org-table-overlay-coordinates)
3397 (org-table-align))
3398 (unless org-table-overlay-coordinates
3399 (mapc 'delete-overlay org-table-coordinate-overlays)
3400 (setq org-table-coordinate-overlays nil)))
3402 (defun org-table-toggle-formula-debugger ()
3403 "Toggle the formula debugger in tables."
3404 (interactive)
3405 (setq org-table-formula-debug (not org-table-formula-debug))
3406 (message "Formula debugging has been turned %s"
3407 (if org-table-formula-debug "on" "off")))
3409 ;;; The orgtbl minor mode
3411 ;; Define a minor mode which can be used in other modes in order to
3412 ;; integrate the org-mode table editor.
3414 ;; This is really a hack, because the org-mode table editor uses several
3415 ;; keys which normally belong to the major mode, for example the TAB and
3416 ;; RET keys. Here is how it works: The minor mode defines all the keys
3417 ;; necessary to operate the table editor, but wraps the commands into a
3418 ;; function which tests if the cursor is currently inside a table. If that
3419 ;; is the case, the table editor command is executed. However, when any of
3420 ;; those keys is used outside a table, the function uses `key-binding' to
3421 ;; look up if the key has an associated command in another currently active
3422 ;; keymap (minor modes, major mode, global), and executes that command.
3423 ;; There might be problems if any of the keys used by the table editor is
3424 ;; otherwise used as a prefix key.
3426 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3427 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3428 ;; addresses this by checking explicitly for both bindings.
3430 ;; The optimized version (see variable `orgtbl-optimized') takes over
3431 ;; all keys which are bound to `self-insert-command' in the *global map*.
3432 ;; Some modes bind other commands to simple characters, for example
3433 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3434 ;; active, this binding is ignored inside tables and replaced with a
3435 ;; modified self-insert.
3437 (defvar orgtbl-mode nil
3438 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
3439 table editor in arbitrary modes.")
3440 (make-variable-buffer-local 'orgtbl-mode)
3442 (defvar orgtbl-mode-map (make-keymap)
3443 "Keymap for `orgtbl-mode'.")
3445 ;;;###autoload
3446 (defun turn-on-orgtbl ()
3447 "Unconditionally turn on `orgtbl-mode'."
3448 (orgtbl-mode 1))
3450 (defvar org-old-auto-fill-inhibit-regexp nil
3451 "Local variable used by `orgtbl-mode'")
3453 (defconst orgtbl-line-start-regexp
3454 "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\|TBLNAME\\):\\)"
3455 "Matches a line belonging to an orgtbl.")
3457 (defconst orgtbl-extra-font-lock-keywords
3458 (list (list (concat "^" orgtbl-line-start-regexp ".*")
3459 0 (quote 'org-table) 'prepend))
3460 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
3462 ;;;###autoload
3463 (defun orgtbl-mode (&optional arg)
3464 "The `org-mode' table editor as a minor mode for use in other modes."
3465 (interactive)
3466 (org-load-modules-maybe)
3467 (if (org-mode-p)
3468 ;; Exit without error, in case some hook functions calls this
3469 ;; by accident in org-mode.
3470 (message "Orgtbl-mode is not useful in org-mode, command ignored")
3471 (setq orgtbl-mode
3472 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
3473 (if orgtbl-mode
3474 (progn
3475 (and (orgtbl-setup) (defun orgtbl-setup () nil))
3476 ;; Make sure we are first in minor-mode-map-alist
3477 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
3478 (and c (setq minor-mode-map-alist
3479 (cons c (delq c minor-mode-map-alist)))))
3480 (org-set-local (quote org-table-may-need-update) t)
3481 (org-add-hook 'before-change-functions 'org-before-change-function
3482 nil 'local)
3483 (org-set-local 'org-old-auto-fill-inhibit-regexp
3484 auto-fill-inhibit-regexp)
3485 (org-set-local 'auto-fill-inhibit-regexp
3486 (if auto-fill-inhibit-regexp
3487 (concat orgtbl-line-start-regexp "\\|"
3488 auto-fill-inhibit-regexp)
3489 orgtbl-line-start-regexp))
3490 (add-to-invisibility-spec '(org-cwidth))
3491 (when (fboundp 'font-lock-add-keywords)
3492 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
3493 (org-restart-font-lock))
3494 (easy-menu-add orgtbl-mode-menu)
3495 (run-hooks 'orgtbl-mode-hook))
3496 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
3497 (org-table-cleanup-narrow-column-properties)
3498 (org-remove-from-invisibility-spec '(org-cwidth))
3499 (remove-hook 'before-change-functions 'org-before-change-function t)
3500 (when (fboundp 'font-lock-remove-keywords)
3501 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
3502 (org-restart-font-lock))
3503 (easy-menu-remove orgtbl-mode-menu)
3504 (force-mode-line-update 'all))))
3506 (defun org-table-cleanup-narrow-column-properties ()
3507 "Remove all properties related to narrow-column invisibility."
3508 (let ((s 1))
3509 (while (setq s (text-property-any s (point-max)
3510 'display org-narrow-column-arrow))
3511 (remove-text-properties s (1+ s) '(display t)))
3512 (setq s 1)
3513 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
3514 (remove-text-properties s (1+ s) '(org-cwidth t)))
3515 (setq s 1)
3516 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
3517 (remove-text-properties s (1+ s) '(invisible t)))))
3519 ;; Install it as a minor mode.
3520 (put 'orgtbl-mode :included t)
3521 (put 'orgtbl-mode :menu-tag "Org Table Mode")
3522 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
3524 (defun orgtbl-make-binding (fun n &rest keys)
3525 "Create a function for binding in the table minor mode.
3526 FUN is the command to call inside a table. N is used to create a unique
3527 command name. KEYS are keys that should be checked in for a command
3528 to execute outside of tables."
3529 (eval
3530 (list 'defun
3531 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
3532 '(arg)
3533 (concat "In tables, run `" (symbol-name fun) "'.\n"
3534 "Outside of tables, run the binding of `"
3535 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
3536 "'.")
3537 '(interactive "p")
3538 (list 'if
3539 '(org-at-table-p)
3540 (list 'call-interactively (list 'quote fun))
3541 (list 'let '(orgtbl-mode)
3542 (list 'call-interactively
3543 (append '(or)
3544 (mapcar (lambda (k)
3545 (list 'key-binding k))
3546 keys)
3547 '('orgtbl-error))))))))
3549 (defun orgtbl-error ()
3550 "Error when there is no default binding for a table key."
3551 (interactive)
3552 (error "This key has no function outside tables"))
3554 (defun orgtbl-setup ()
3555 "Setup orgtbl keymaps."
3556 (let ((nfunc 0)
3557 (bindings
3558 (list
3559 '([(meta shift left)] org-table-delete-column)
3560 '([(meta left)] org-table-move-column-left)
3561 '([(meta right)] org-table-move-column-right)
3562 '([(meta shift right)] org-table-insert-column)
3563 '([(meta shift up)] org-table-kill-row)
3564 '([(meta shift down)] org-table-insert-row)
3565 '([(meta up)] org-table-move-row-up)
3566 '([(meta down)] org-table-move-row-down)
3567 '("\C-c\C-w" org-table-cut-region)
3568 '("\C-c\M-w" org-table-copy-region)
3569 '("\C-c\C-y" org-table-paste-rectangle)
3570 '("\C-c-" org-table-insert-hline)
3571 '("\C-c}" org-table-toggle-coordinate-overlays)
3572 '("\C-c{" org-table-toggle-formula-debugger)
3573 '("\C-m" org-table-next-row)
3574 '([(shift return)] org-table-copy-down)
3575 '("\C-c?" org-table-field-info)
3576 '("\C-c " org-table-blank-field)
3577 '("\C-c+" org-table-sum)
3578 '("\C-c=" org-table-eval-formula)
3579 '("\C-c'" org-table-edit-formulas)
3580 '("\C-c`" org-table-edit-field)
3581 '("\C-c*" org-table-recalculate)
3582 '("\C-c^" org-table-sort-lines)
3583 '("\M-a" org-table-beginning-of-field)
3584 '("\M-e" org-table-end-of-field)
3585 '([(control ?#)] org-table-rotate-recalc-marks)))
3586 elt key fun cmd)
3587 (while (setq elt (pop bindings))
3588 (setq nfunc (1+ nfunc))
3589 (setq key (org-key (car elt))
3590 fun (nth 1 elt)
3591 cmd (orgtbl-make-binding fun nfunc key))
3592 (org-defkey orgtbl-mode-map key cmd))
3594 ;; Special treatment needed for TAB and RET
3595 (org-defkey orgtbl-mode-map [(return)]
3596 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
3597 (org-defkey orgtbl-mode-map "\C-m"
3598 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
3600 (org-defkey orgtbl-mode-map [(tab)]
3601 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
3602 (org-defkey orgtbl-mode-map "\C-i"
3603 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
3605 (org-defkey orgtbl-mode-map [(shift tab)]
3606 (orgtbl-make-binding 'org-table-previous-field 104
3607 [(shift tab)] [(tab)] "\C-i"))
3610 (unless (featurep 'xemacs)
3611 (org-defkey orgtbl-mode-map [S-iso-lefttab]
3612 (orgtbl-make-binding 'org-table-previous-field 107
3613 [S-iso-lefttab] [backtab] [(shift tab)]
3614 [(tab)] "\C-i")))
3616 (org-defkey orgtbl-mode-map [backtab]
3617 (orgtbl-make-binding 'org-table-previous-field 108
3618 [backtab] [S-iso-lefttab] [(shift tab)]
3619 [(tab)] "\C-i"))
3621 (org-defkey orgtbl-mode-map "\M-\C-m"
3622 (orgtbl-make-binding 'org-table-wrap-region 105
3623 "\M-\C-m" [(meta return)]))
3624 (org-defkey orgtbl-mode-map [(meta return)]
3625 (orgtbl-make-binding 'org-table-wrap-region 106
3626 [(meta return)] "\M-\C-m"))
3628 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
3629 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
3631 (when orgtbl-optimized
3632 ;; If the user wants maximum table support, we need to hijack
3633 ;; some standard editing functions
3634 (org-remap orgtbl-mode-map
3635 'self-insert-command 'orgtbl-self-insert-command
3636 'delete-char 'org-delete-char
3637 'delete-backward-char 'org-delete-backward-char)
3638 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
3639 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
3640 '("OrgTbl"
3641 ["Create or convert" org-table-create-or-convert-from-region
3642 :active (not (org-at-table-p)) :keys "C-c |" ]
3643 "--"
3644 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
3645 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
3646 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
3647 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
3648 "--"
3649 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
3650 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
3651 ["Copy Field from Above"
3652 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
3653 "--"
3654 ("Column"
3655 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
3656 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
3657 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
3658 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
3659 ("Row"
3660 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
3661 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
3662 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
3663 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
3664 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
3665 "--"
3666 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
3667 ("Rectangle"
3668 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
3669 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
3670 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
3671 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
3672 "--"
3673 ("Radio tables"
3674 ["Insert table template" orgtbl-insert-radio-table
3675 (assq major-mode orgtbl-radio-table-templates)]
3676 ["Comment/uncomment table" orgtbl-toggle-comment t])
3677 "--"
3678 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
3679 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
3680 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
3681 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
3682 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
3683 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
3684 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
3685 ["Sum Column/Rectangle" org-table-sum
3686 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
3687 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
3688 ["Debug Formulas"
3689 org-table-toggle-formula-debugger :active (org-at-table-p)
3690 :keys "C-c {"
3691 :style toggle :selected org-table-formula-debug]
3692 ["Show Col/Row Numbers"
3693 org-table-toggle-coordinate-overlays :active (org-at-table-p)
3694 :keys "C-c }"
3695 :style toggle :selected org-table-overlay-coordinates]
3699 (defun orgtbl-ctrl-c-ctrl-c (arg)
3700 "If the cursor is inside a table, realign the table.
3701 If it is a table to be sent away to a receiver, do it.
3702 With prefix arg, also recompute table."
3703 (interactive "P")
3704 (let ((pos (point)) action)
3705 (save-excursion
3706 (beginning-of-line 1)
3707 (setq action (cond ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
3708 ((looking-at "[ \t]*|") pos)
3709 ((looking-at "[ \t]*#\\+TBLFM:") 'recalc))))
3710 (cond
3711 ((integerp action)
3712 (goto-char action)
3713 (org-table-maybe-eval-formula)
3714 (if arg
3715 (call-interactively 'org-table-recalculate)
3716 (org-table-maybe-recalculate-line))
3717 (call-interactively 'org-table-align)
3718 (orgtbl-send-table 'maybe))
3719 ((eq action 'recalc)
3720 (save-excursion
3721 (beginning-of-line 1)
3722 (skip-chars-backward " \r\n\t")
3723 (if (org-at-table-p)
3724 (org-call-with-arg 'org-table-recalculate t))))
3725 (t (let (orgtbl-mode)
3726 (call-interactively (key-binding "\C-c\C-c")))))))
3728 (defun orgtbl-create-or-convert-from-region (arg)
3729 "Create table or convert region to table, if no conflicting binding.
3730 This installs the table binding `C-c |', but only if there is no
3731 conflicting binding to this key outside orgtbl-mode."
3732 (interactive "P")
3733 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
3734 (if cmd
3735 (call-interactively cmd)
3736 (call-interactively 'org-table-create-or-convert-from-region))))
3738 (defun orgtbl-tab (arg)
3739 "Justification and field motion for `orgtbl-mode'."
3740 (interactive "P")
3741 (if arg (org-table-edit-field t)
3742 (org-table-justify-field-maybe)
3743 (org-table-next-field)))
3745 (defun orgtbl-ret ()
3746 "Justification and field motion for `orgtbl-mode'."
3747 (interactive)
3748 (if (bobp)
3749 (newline)
3750 (org-table-justify-field-maybe)
3751 (org-table-next-row)))
3753 (defun orgtbl-self-insert-command (N)
3754 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
3755 If the cursor is in a table looking at whitespace, the whitespace is
3756 overwritten, and the table is not marked as requiring realignment."
3757 (interactive "p")
3758 (if (and (org-at-table-p)
3760 (and org-table-auto-blank-field
3761 (member last-command
3762 '(orgtbl-hijacker-command-100
3763 orgtbl-hijacker-command-101
3764 orgtbl-hijacker-command-102
3765 orgtbl-hijacker-command-103
3766 orgtbl-hijacker-command-104
3767 orgtbl-hijacker-command-105
3768 yas/expand))
3769 (org-table-blank-field))
3771 (eq N 1)
3772 (looking-at "[^|\n]* +|"))
3773 (let (org-table-may-need-update)
3774 (goto-char (1- (match-end 0)))
3775 (delete-backward-char 1)
3776 (goto-char (match-beginning 0))
3777 (self-insert-command N))
3778 (setq org-table-may-need-update t)
3779 (let* (orgtbl-mode
3781 (cmd (or (key-binding
3782 (or (and (listp function-key-map)
3783 (setq a (assoc last-input-event function-key-map))
3784 (cdr a))
3785 (vector last-input-event)))
3786 'self-insert-command)))
3787 (call-interactively cmd)
3788 (if (and org-self-insert-cluster-for-undo
3789 (eq cmd 'self-insert-command))
3790 (if (not (eq last-command 'orgtbl-self-insert-command))
3791 (setq org-self-insert-command-undo-counter 1)
3792 (if (>= org-self-insert-command-undo-counter 20)
3793 (setq org-self-insert-command-undo-counter 1)
3794 (and (> org-self-insert-command-undo-counter 0)
3795 buffer-undo-list
3796 (not (cadr buffer-undo-list)) ; remove nil entry
3797 (setcdr buffer-undo-list (cddr buffer-undo-list)))
3798 (setq org-self-insert-command-undo-counter
3799 (1+ org-self-insert-command-undo-counter))))))))
3801 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
3802 "Regular expression matching exponentials as produced by calc.")
3804 (defun orgtbl-export (table target)
3805 (require 'org-exp)
3806 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
3807 (lines (org-split-string table "[ \t]*\n[ \t]*"))
3808 org-table-last-alignment org-table-last-column-widths
3809 maxcol column)
3810 (if (not (fboundp func))
3811 (error "Cannot export orgtbl table to %s" target))
3812 (setq lines (org-table-clean-before-export lines))
3813 (setq table
3814 (mapcar
3815 (lambda (x)
3816 (if (string-match org-table-hline-regexp x)
3817 'hline
3818 (org-split-string (org-trim x) "\\s-*|\\s-*")))
3819 lines))
3820 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
3821 table)))
3822 (loop for i from (1- maxcol) downto 0 do
3823 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
3824 (setq column (delq nil column))
3825 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
3826 (push (> (/ (apply '+ (mapcar (lambda (x) (if (string-match org-table-number-regexp x) 1 0)) column)) maxcol) org-table-number-fraction) org-table-last-alignment))
3827 (funcall func table nil)))
3829 (defun orgtbl-gather-send-defs ()
3830 "Gathers a plist of :name, :transform, :params for each destination before
3831 a radio table."
3832 (save-excursion
3833 (goto-char (org-table-begin))
3834 (let (rtn)
3835 (beginning-of-line 0)
3836 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
3837 (let ((name (org-no-properties (match-string 1)))
3838 (transform (intern (match-string 2)))
3839 (params (if (match-end 3)
3840 (read (concat "(" (match-string 3) ")")))))
3841 (push (list :name name :transform transform :params params)
3842 rtn)
3843 (beginning-of-line 0)))
3844 rtn)))
3846 (defun orgtbl-send-replace-tbl (name txt)
3847 "Find and replace table NAME with TXT."
3848 (save-excursion
3849 (goto-char (point-min))
3850 (unless (re-search-forward
3851 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
3852 (error "Don't know where to insert translated table"))
3853 (goto-char (match-beginning 0))
3854 (beginning-of-line 2)
3855 (save-excursion
3856 (let ((beg (point)))
3857 (unless (re-search-forward
3858 (concat "END RECEIVE ORGTBL +" name) nil t)
3859 (error "Cannot find end of insertion region"))
3860 (beginning-of-line 1)
3861 (delete-region beg (point))))
3862 (insert txt "\n")))
3864 ;;;###autoload
3865 (defun org-table-to-lisp (&optional txt)
3866 "Convert the table at point to a Lisp structure.
3867 The structure will be a list. Each item is either the symbol `hline'
3868 for a horizontal separator line, or a list of field values as strings.
3869 The table is taken from the parameter TXT, or from the buffer at point."
3870 (unless txt
3871 (unless (org-at-table-p)
3872 (error "No table at point")))
3873 (let* ((txt (or txt
3874 (buffer-substring-no-properties (org-table-begin)
3875 (org-table-end))))
3876 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
3878 (mapcar
3879 (lambda (x)
3880 (if (string-match org-table-hline-regexp x)
3881 'hline
3882 (org-split-string (org-trim x) "\\s-*|\\s-*")))
3883 lines)))
3885 (defun orgtbl-send-table (&optional maybe)
3886 "Send a transformed version of this table to the receiver position.
3887 With argument MAYBE, fail quietly if no transformation is defined for
3888 this table."
3889 (interactive)
3890 (catch 'exit
3891 (unless (org-at-table-p) (error "Not at a table"))
3892 ;; when non-interactive, we assume align has just happened.
3893 (when (interactive-p) (org-table-align))
3894 (let ((dests (orgtbl-gather-send-defs))
3895 (txt (buffer-substring-no-properties (org-table-begin)
3896 (org-table-end)))
3897 (ntbl 0))
3898 (unless dests (if maybe (throw 'exit nil)
3899 (error "Don't know how to transform this table")))
3900 (dolist (dest dests)
3901 (let* ((name (plist-get dest :name))
3902 (transform (plist-get dest :transform))
3903 (params (plist-get dest :params))
3904 (skip (plist-get params :skip))
3905 (skipcols (plist-get params :skipcols))
3907 (lines (org-table-clean-before-export
3908 (nthcdr (or skip 0)
3909 (org-split-string txt "[ \t]*\n[ \t]*"))))
3910 (i0 (if org-table-clean-did-remove-column 2 1))
3911 (table (mapcar
3912 (lambda (x)
3913 (if (string-match org-table-hline-regexp x)
3914 'hline
3915 (org-remove-by-index
3916 (org-split-string (org-trim x) "\\s-*|\\s-*")
3917 skipcols i0)))
3918 lines))
3919 (fun (if (= i0 2) 'cdr 'identity))
3920 (org-table-last-alignment
3921 (org-remove-by-index (funcall fun org-table-last-alignment)
3922 skipcols i0))
3923 (org-table-last-column-widths
3924 (org-remove-by-index (funcall fun org-table-last-column-widths)
3925 skipcols i0))
3926 (txt (if (fboundp transform)
3927 (funcall transform table params)
3928 (error "No such transformation function %s" transform))))
3929 (orgtbl-send-replace-tbl name txt))
3930 (setq ntbl (1+ ntbl)))
3931 (message "Table converted and installed at %d receiver location%s"
3932 ntbl (if (> ntbl 1) "s" "")))))
3934 (defun org-remove-by-index (list indices &optional i0)
3935 "Remove the elements in LIST with indices in INDICES.
3936 First element has index 0, or I0 if given."
3937 (if (not indices)
3938 list
3939 (if (integerp indices) (setq indices (list indices)))
3940 (setq i0 (1- (or i0 0)))
3941 (delq :rm (mapcar (lambda (x)
3942 (setq i0 (1+ i0))
3943 (if (memq i0 indices) :rm x))
3944 list))))
3946 (defun orgtbl-toggle-comment ()
3947 "Comment or uncomment the orgtbl at point."
3948 (interactive)
3949 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
3950 (re2 (concat "^" orgtbl-line-start-regexp))
3951 (commented (save-excursion (beginning-of-line 1)
3952 (cond ((looking-at re1) t)
3953 ((looking-at re2) nil)
3954 (t (error "Not at an org table")))))
3955 (re (if commented re1 re2))
3956 beg end)
3957 (save-excursion
3958 (beginning-of-line 1)
3959 (while (looking-at re) (beginning-of-line 0))
3960 (beginning-of-line 2)
3961 (setq beg (point))
3962 (while (looking-at re) (beginning-of-line 2))
3963 (setq end (point)))
3964 (comment-region beg end (if commented '(4) nil))))
3966 (defun orgtbl-insert-radio-table ()
3967 "Insert a radio table template appropriate for this major mode."
3968 (interactive)
3969 (let* ((e (assq major-mode orgtbl-radio-table-templates))
3970 (txt (nth 1 e))
3971 name pos)
3972 (unless e (error "No radio table setup defined for %s" major-mode))
3973 (setq name (read-string "Table name: "))
3974 (while (string-match "%n" txt)
3975 (setq txt (replace-match name t t txt)))
3976 (or (bolp) (insert "\n"))
3977 (setq pos (point))
3978 (insert txt)
3979 (goto-char pos)))
3981 ;; Dynamically bound input and output for table formatting.
3982 (defvar *orgtbl-table* nil
3983 "Carries the current table through formatting routines.")
3984 (defvar *orgtbl-rtn* nil
3985 "Formatting routines push the output lines here.")
3986 ;; Formatting parameters for the current table section.
3987 (defvar *orgtbl-hline* nil "Text used for horizontal lines")
3988 (defvar *orgtbl-sep* nil "Text used as a column separator")
3989 (defvar *orgtbl-default-fmt* nil "Default format for each entry")
3990 (defvar *orgtbl-fmt* nil "Format for each entry")
3991 (defvar *orgtbl-efmt* nil "Format for numbers")
3992 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt")
3993 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row")
3994 (defvar *orgtbl-lstart* nil "Text starting a row")
3995 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row")
3996 (defvar *orgtbl-lend* nil "Text ending a row")
3997 (defvar *orgtbl-llend* nil "Specializes lend for the last row")
3999 (defsubst orgtbl-get-fmt (fmt i)
4000 "Retrieve the format from FMT corresponding to the Ith column."
4001 (if (and (not (functionp fmt)) (consp fmt))
4002 (plist-get fmt i)
4003 fmt))
4005 (defsubst orgtbl-apply-fmt (fmt &rest args)
4006 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4007 (cond ((functionp fmt) (apply fmt args))
4008 (fmt (apply 'format fmt args))
4009 (args (car args))
4010 (t args)))
4012 (defsubst orgtbl-eval-str (str)
4013 "If STR is a function, evaluate it with no arguments."
4014 (if (functionp str)
4015 (funcall str)
4016 str))
4018 (defun orgtbl-format-line (line)
4019 "Format LINE as a table row."
4020 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4021 (let* ((i 0)
4022 (line
4023 (mapcar
4024 (lambda (f)
4025 (setq i (1+ i))
4026 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4027 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4028 (orgtbl-apply-fmt efmt (match-string 1 f)
4029 (match-string 2 f))
4030 f)))
4031 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4032 *orgtbl-default-fmt*)
4033 f)))
4034 line)))
4035 (push (if *orgtbl-lfmt*
4036 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4037 (concat (orgtbl-eval-str *orgtbl-lstart*)
4038 (mapconcat 'identity line *orgtbl-sep*)
4039 (orgtbl-eval-str *orgtbl-lend*)))
4040 *orgtbl-rtn*))))
4042 (defun orgtbl-format-section (section-stopper)
4043 "Format lines until the first occurrence of SECTION-STOPPER."
4044 (let (prevline)
4045 (progn
4046 (while (not (eq (car *orgtbl-table*) section-stopper))
4047 (if prevline (orgtbl-format-line prevline))
4048 (setq prevline (pop *orgtbl-table*)))
4049 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4050 (*orgtbl-lend* *orgtbl-llend*)
4051 (*orgtbl-lfmt* *orgtbl-llfmt*))
4052 (orgtbl-format-line prevline))))))
4054 (defun orgtbl-to-generic (table params)
4055 "Convert the orgtbl-mode TABLE to some other format.
4056 This generic routine can be used for many standard cases.
4057 TABLE is a list, each entry either the symbol `hline' for a horizontal
4058 separator line, or a list of fields for that line.
4059 PARAMS is a property list of parameters that can influence the conversion.
4060 For the generic converter, some parameters are obligatory: You need to
4061 specify either :lfmt, or all of (:lstart :lend :sep).
4063 Valid parameters are
4065 :splice When set to t, return only table body lines, don't wrap
4066 them into :tstart and :tend. Default is nil. When :splice
4067 is non-nil, this also means that the exporter should not look
4068 for and interpret header and footer sections.
4070 :hline String to be inserted on horizontal separation lines.
4071 May be nil to ignore hlines.
4073 :sep Separator between two fields
4074 :remove-nil-lines Do not include lines that evaluate to nil.
4077 Each in the following group may be either a string or a function
4078 of no arguments returning a string:
4079 :tstart String to start the table. Ignored when :splice is t.
4080 :tend String to end the table. Ignored when :splice is t.
4081 :lstart String to start a new table line.
4082 :llstart String to start the last table line, defaults to :lstart.
4083 :lend String to end a table line
4084 :llend String to end the last table line, defaults to :lend.
4086 Each in the following group may be a string, a function of one
4087 argument (the field or line) returning a string, or a plist
4088 mapping columns to either of the above:
4089 :lfmt Format for entire line, with enough %s to capture all fields.
4090 If this is present, :lstart, :lend, and :sep are ignored.
4091 :llfmt Format for the entire last line, defaults to :lfmt.
4092 :fmt A format to be used to wrap the field, should contain
4093 %s for the original field value. For example, to wrap
4094 everything in dollars, you could use :fmt \"$%s$\".
4095 This may also be a property list with column numbers and
4096 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4098 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4099 Same as above, specific for the header lines in the table.
4100 All lines before the first hline are treated as header.
4101 If any of these is not present, the data line value is used.
4103 This may be either a string or a function of two arguments:
4104 :efmt Use this format to print numbers with exponentials.
4105 The format should have %s twice for inserting mantissa
4106 and exponent, for example \"%s\\\\times10^{%s}\". This
4107 may also be a property list with column numbers and
4108 formats. :fmt will still be applied after :efmt.
4110 In addition to this, the parameters :skip and :skipcols are always handled
4111 directly by `orgtbl-send-table'. See manual."
4112 (interactive)
4114 (let* ((splicep (plist-get params :splice))
4115 (hline (plist-get params :hline))
4116 (remove-nil-linesp (plist-get params :remove-nil-lines))
4117 (*orgtbl-hline* hline)
4118 (*orgtbl-table* table)
4119 (*orgtbl-sep* (plist-get params :sep))
4120 (*orgtbl-efmt* (plist-get params :efmt))
4121 (*orgtbl-lstart* (plist-get params :lstart))
4122 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4123 (*orgtbl-lend* (plist-get params :lend))
4124 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4125 (*orgtbl-lfmt* (plist-get params :lfmt))
4126 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4127 (*orgtbl-fmt* (plist-get params :fmt))
4128 *orgtbl-rtn*)
4130 ;; Put header
4131 (unless splicep
4132 (when (plist-member params :tstart)
4133 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4134 (if tstart (push tstart *orgtbl-rtn*)))))
4136 ;; Do we have a heading section? If so, format it and handle the
4137 ;; trailing hline.
4138 (if (and (not splicep)
4139 (or (consp (car *orgtbl-table*))
4140 (consp (nth 1 *orgtbl-table*)))
4141 (memq 'hline (cdr *orgtbl-table*)))
4142 (progn
4143 (when (eq 'hline (car *orgtbl-table*))
4144 ;; there is a hline before the first data line
4145 (and hline (push hline *orgtbl-rtn*))
4146 (pop *orgtbl-table*))
4147 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4148 *orgtbl-lstart*))
4149 (*orgtbl-llstart* (or (plist-get params :hllstart)
4150 *orgtbl-llstart*))
4151 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4152 (*orgtbl-llend* (or (plist-get params :hllend)
4153 (plist-get params :hlend) *orgtbl-llend*))
4154 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4155 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4156 (plist-get params :hlfmt) *orgtbl-llfmt*))
4157 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4158 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4159 (orgtbl-format-section 'hline))
4160 (if hline (push hline *orgtbl-rtn*))
4161 (pop *orgtbl-table*)))
4163 ;; Now format the main section.
4164 (orgtbl-format-section nil)
4166 (unless splicep
4167 (when (plist-member params :tend)
4168 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4169 (if tend (push tend *orgtbl-rtn*)))))
4171 (mapconcat 'identity (nreverse (if remove-nil-linesp
4172 (remq nil *orgtbl-rtn*)
4173 *orgtbl-rtn*)) "\n")))
4175 (defun orgtbl-to-tsv (table params)
4176 "Convert the orgtbl-mode table to TAB separated material."
4177 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4178 (defun orgtbl-to-csv (table params)
4179 "Convert the orgtbl-mode table to CSV material.
4180 This does take care of the proper quoting of fields with comma or quotes."
4181 (orgtbl-to-generic table (org-combine-plists
4182 '(:sep "," :fmt org-quote-csv-field)
4183 params)))
4185 (defun orgtbl-to-latex (table params)
4186 "Convert the orgtbl-mode TABLE to LaTeX.
4187 TABLE is a list, each entry either the symbol `hline' for a horizontal
4188 separator line, or a list of fields for that line.
4189 PARAMS is a property list of parameters that can influence the conversion.
4190 Supports all parameters from `orgtbl-to-generic'. Most important for
4191 LaTeX are:
4193 :splice When set to t, return only table body lines, don't wrap
4194 them into a tabular environment. Default is nil.
4196 :fmt A format to be used to wrap the field, should contain %s for the
4197 original field value. For example, to wrap everything in dollars,
4198 use :fmt \"$%s$\". This may also be a property list with column
4199 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4200 The format may also be a function that formats its one argument.
4202 :efmt Format for transforming numbers with exponentials. The format
4203 should have %s twice for inserting mantissa and exponent, for
4204 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4205 This may also be a property list with column numbers and formats.
4206 The format may also be a function that formats its two arguments.
4208 :llend If you find too much space below the last line of a table,
4209 pass a value of \"\" for :llend to suppress the final \\\\.
4211 The general parameters :skip and :skipcols have already been applied when
4212 this function is called."
4213 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4214 org-table-last-alignment ""))
4215 (params2
4216 (list
4217 :tstart (concat "\\begin{tabular}{" alignment "}")
4218 :tend "\\end{tabular}"
4219 :lstart "" :lend " \\\\" :sep " & "
4220 :efmt "%s\\,(%s)" :hline "\\hline")))
4221 (orgtbl-to-generic table (org-combine-plists params2 params))))
4223 (defun orgtbl-to-html (table params)
4224 "Convert the orgtbl-mode TABLE to LaTeX.
4225 TABLE is a list, each entry either the symbol `hline' for a horizontal
4226 separator line, or a list of fields for that line.
4227 PARAMS is a property list of parameters that can influence the conversion.
4228 Currently this function recognizes the following parameters:
4230 :splice When set to t, return only table body lines, don't wrap
4231 them into a <table> environment. Default is nil.
4233 The general parameters :skip and :skipcols have already been applied when
4234 this function is called. The function does *not* use `orgtbl-to-generic',
4235 so you cannot specify parameters for it."
4236 (let* ((splicep (plist-get params :splice))
4237 (html-table-tag org-export-html-table-tag)
4238 html)
4239 ;; Just call the formatter we already have
4240 ;; We need to make text lines for it, so put the fields back together.
4241 (setq html (org-format-org-table-html
4242 (mapcar
4243 (lambda (x)
4244 (if (eq x 'hline)
4245 "|----+----|"
4246 (concat "| " (mapconcat 'identity x " | ") " |")))
4247 table)
4248 splicep))
4249 (if (string-match "\n+\\'" html)
4250 (setq html (replace-match "" t t html)))
4251 html))
4253 (defun orgtbl-to-texinfo (table params)
4254 "Convert the orgtbl-mode TABLE to TeXInfo.
4255 TABLE is a list, each entry either the symbol `hline' for a horizontal
4256 separator line, or a list of fields for that line.
4257 PARAMS is a property list of parameters that can influence the conversion.
4258 Supports all parameters from `orgtbl-to-generic'. Most important for
4259 TeXInfo are:
4261 :splice nil/t When set to t, return only table body lines, don't wrap
4262 them into a multitable environment. Default is nil.
4264 :fmt fmt A format to be used to wrap the field, should contain
4265 %s for the original field value. For example, to wrap
4266 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4267 This may also be a property list with column numbers and
4268 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4269 Each format also may be a function that formats its one
4270 argument.
4272 :cf \"f1 f2..\" The column fractions for the table. By default these
4273 are computed automatically from the width of the columns
4274 under org-mode.
4276 The general parameters :skip and :skipcols have already been applied when
4277 this function is called."
4278 (let* ((total (float (apply '+ org-table-last-column-widths)))
4279 (colfrac (or (plist-get params :cf)
4280 (mapconcat
4281 (lambda (x) (format "%.3f" (/ (float x) total)))
4282 org-table-last-column-widths " ")))
4283 (params2
4284 (list
4285 :tstart (concat "@multitable @columnfractions " colfrac)
4286 :tend "@end multitable"
4287 :lstart "@item " :lend "" :sep " @tab "
4288 :hlstart "@headitem ")))
4289 (orgtbl-to-generic table (org-combine-plists params2 params))))
4291 (defun orgtbl-to-orgtbl (table params)
4292 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4293 Useful when slicing one table into many. The :hline, :sep,
4294 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4295 and :tend suppress strings without splicing; they can be set to
4296 provide ORGTBL directives for the generated table."
4297 (let* ((params2
4298 (list
4299 :tstart nil :tend nil
4300 :hline "|---"
4301 :sep " | "
4302 :lstart "| "
4303 :lend " |"))
4304 (params (org-combine-plists params2 params)))
4305 (orgtbl-to-generic table params)))
4307 (defun org-table-get-remote-range (name-or-id form)
4308 "Get a field value or a list of values in a range from table at ID.
4310 NAME-OR-ID may be the name of a table in the current file as set by
4311 a \"#+TBLNAME:\" directive. The first table following this line
4312 will then be used. Alternatively, it may be an ID referring to
4313 any entry, also in a different file. In this case, the first table
4314 in that entry will be referenced.
4315 FORM is a field or range descriptor like \"@2$3\" or or \"B3\" or
4316 \"@I$2..@II$2\". All the references must be absolute, not relative.
4318 The return value is either a single string for a single field, or a
4319 list of the fields in the rectangle ."
4320 (save-match-data
4321 (let ((id-loc nil)
4322 org-table-column-names org-table-column-name-regexp
4323 org-table-local-parameters org-table-named-field-locations
4324 org-table-current-line-types org-table-current-begin-line
4325 org-table-current-begin-pos org-table-dlines
4326 org-table-hlines org-table-last-alignment
4327 org-table-last-column-widths org-table-last-alignment
4328 org-table-last-column-widths tbeg
4329 buffer loc)
4330 (setq form (org-table-convert-refs-to-rc form))
4331 (save-excursion
4332 (save-restriction
4333 (widen)
4334 (save-excursion
4335 (goto-char (point-min))
4336 (if (re-search-forward
4337 (concat "^[ \t]*#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4338 nil t)
4339 (setq buffer (current-buffer) loc (match-beginning 0))
4340 (setq id-loc (org-id-find name-or-id 'marker))
4341 (unless (and id-loc (markerp id-loc))
4342 (error "Can't find remote table \"%s\"" name-or-id))
4343 (setq buffer (marker-buffer id-loc)
4344 loc (marker-position id-loc))
4345 (move-marker id-loc nil)))
4346 (switch-to-buffer buffer)
4347 (save-excursion
4348 (save-restriction
4349 (widen)
4350 (goto-char loc)
4351 (forward-char 1)
4352 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4353 (not (match-beginning 1)))
4354 (error "Cannot find a table at NAME or ID %s" name-or-id))
4355 (setq tbeg (point-at-bol))
4356 (org-table-get-specials)
4357 (setq form (org-table-formula-substitute-names form))
4358 (if (and (string-match org-table-range-regexp form)
4359 (> (length (match-string 0 form)) 1))
4360 (save-match-data
4361 (org-table-get-range (match-string 0 form) tbeg 1))
4362 form))))))))
4364 (provide 'org-table)
4366 ;; arch-tag: 4d21cfdd-0268-440a-84b0-09237a0fe0ef
4368 ;;; org-table.el ends here