Use Slashdot.org as feed example in the documentation
[org-mode/org-jambu.git] / lisp / org-table.el
blobcd7642ed119f7dababa9aece1eb9d5f8ca368287
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.36trans
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 raise narrow
633 falign falign1 fmax f1 len c e space)
634 (untabify beg end)
635 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
636 ;; Check if we have links or dates
637 (goto-char beg)
638 (setq links (re-search-forward org-bracket-link-regexp end t))
639 (goto-char beg)
640 (setq emph (and org-hide-emphasis-markers
641 (re-search-forward org-emph-re end t)))
642 (goto-char beg)
643 (setq raise (and org-use-sub-superscripts
644 (re-search-forward org-match-substring-regexp end t)))
645 (goto-char beg)
646 (setq dates (and org-display-custom-times
647 (re-search-forward org-ts-regexp-both end t)))
648 ;; Make sure the link properties are right
649 (when links (goto-char beg) (while (org-activate-bracket-links end)))
650 ;; Make sure the date properties are right
651 (when dates (goto-char beg) (while (org-activate-dates end)))
652 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
653 (when raise (goto-char beg) (while (org-raise-scripts end)))
655 ;; Check if we are narrowing any columns
656 (goto-char beg)
657 (setq narrow (and org-table-do-narrow
658 org-format-transports-properties-p
659 (re-search-forward "<[rl]?[0-9]+>" end t)))
660 (goto-char beg)
661 (setq falign (re-search-forward "<[rl][0-9]*>" end t))
662 (goto-char beg)
663 ;; Get the rows
664 (setq lines (org-split-string
665 (buffer-substring beg end) "\n"))
666 ;; Store the indentation of the first line
667 (if (string-match "^ *" (car lines))
668 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
669 ;; Mark the hlines by setting the corresponding element to nil
670 ;; At the same time, we remove trailing space.
671 (setq lines (mapcar (lambda (l)
672 (if (string-match "^ *|-" l)
674 (if (string-match "[ \t]+$" l)
675 (substring l 0 (match-beginning 0))
676 l)))
677 lines))
678 ;; Get the data fields by splitting the lines.
679 (setq fields (mapcar
680 (lambda (l)
681 (org-split-string l " *| *"))
682 (delq nil (copy-sequence lines))))
683 ;; How many fields in the longest line?
684 (condition-case nil
685 (setq maxfields (apply 'max (mapcar 'length fields)))
686 (error
687 (kill-region beg end)
688 (org-table-create org-table-default-size)
689 (error "Empty table - created default table")))
690 ;; A list of empty strings to fill any short rows on output
691 (setq emptystrings (make-list maxfields ""))
692 ;; Check for special formatting.
693 (setq i -1)
694 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
695 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
696 ;; Check if there is an explicit width specified
697 (setq fmax nil)
698 (when (or narrow falign)
699 (setq c column fmax nil falign1 nil)
700 (while c
701 (setq e (pop c))
702 (when (and (stringp e) (string-match "^<\\([rl]\\)?\\([0-9]+\\)?>$" e))
703 (if (match-end 1) (setq falign1 (match-string 1 e)))
704 (if (and org-table-do-narrow (match-end 2))
705 (setq fmax (string-to-number (match-string 2 e)) c nil))))
706 ;; Find fields that are wider than fmax, and shorten them
707 (when fmax
708 (loop for xx in column do
709 (when (and (stringp xx)
710 (> (org-string-width xx) fmax))
711 (org-add-props xx nil
712 'help-echo
713 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
714 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
715 (unless (> f1 1)
716 (error "Cannot narrow field starting with wide link \"%s\""
717 (match-string 0 xx)))
718 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
719 (add-text-properties (- f1 2) f1
720 (list 'display org-narrow-column-arrow)
721 xx)))))
722 ;; Get the maximum width for each column
723 (push (apply 'max (or fmax 1) 1 (mapcar 'org-string-width column))
724 lengths)
725 ;; Get the fraction of numbers, to decide about alignment of the column
726 (if falign1
727 (push (equal (downcase falign1) "r") typenums)
728 (setq cnt 0 frac 0.0)
729 (loop for x in column do
730 (if (equal x "")
732 (setq frac ( / (+ (* frac cnt)
733 (if (string-match org-table-number-regexp x) 1 0))
734 (setq cnt (1+ cnt))))))
735 (push (>= frac org-table-number-fraction) typenums)))
736 (setq lengths (nreverse lengths) typenums (nreverse typenums))
738 ;; Store the alignment of this table, for later editing of single fields
739 (setq org-table-last-alignment typenums
740 org-table-last-column-widths lengths)
742 ;; With invisible characters, `format' does not get the field width right
743 ;; So we need to make these fields wide by hand.
744 (when (or links emph raise)
745 (loop for i from 0 upto (1- maxfields) do
746 (setq len (nth i lengths))
747 (loop for j from 0 upto (1- (length fields)) do
748 (setq c (nthcdr i (car (nthcdr j fields))))
749 (if (and (stringp (car c))
750 (or (text-property-any 0 (length (car c))
751 'invisible 'org-link (car c))
752 (text-property-any 0 (length (car c))
753 'org-dwidth t (car c)))
754 (< (org-string-width (car c)) len))
755 (progn
756 (setq space (make-string (- len (org-string-width (car c))) ?\ ))
757 (setcar c (if (nth i typenums)
758 (concat space (car c))
759 (concat (car c) space))))))))
761 ;; Compute the formats needed for output of the table
762 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
763 (while (setq l (pop lengths))
764 (setq ty (if (pop typenums) "" "-")) ; number types flushright
765 (setq rfmt (concat rfmt (format rfmt1 ty l))
766 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
767 (setq rfmt (concat rfmt "\n")
768 hfmt (concat (substring hfmt 0 -1) "|\n"))
770 (setq new (mapconcat
771 (lambda (l)
772 (if l (apply 'format rfmt
773 (append (pop fields) emptystrings))
774 hfmt))
775 lines ""))
776 (if (equal (char-before) ?\n)
777 ;; This hack is for org-indent, to force redisplay of the
778 ;; line prefix of the first line. Apparently the redisplay
779 ;; is tied to the newline, which is, I think, a bug.
780 ;; To force this redisplay, we remove and re-insert the
781 ;; newline, so that the redisplay engine thinks it belongs
782 ;; to the changed text.
783 (progn
784 (backward-delete-char 1)
785 (insert "\n")))
786 (move-marker org-table-aligned-begin-marker (point))
787 (insert new)
788 ;; Replace the old one
789 (delete-region (point) end)
790 (move-marker end nil)
791 (move-marker org-table-aligned-end-marker (point))
792 (when (and orgtbl-mode (not (org-mode-p)))
793 (goto-char org-table-aligned-begin-marker)
794 (while (org-hide-wide-columns org-table-aligned-end-marker)))
795 ;; Try to move to the old location
796 (org-goto-line winstartline)
797 (setq winstart (point-at-bol))
798 (org-goto-line linepos)
799 (set-window-start (selected-window) winstart 'noforce)
800 (org-table-goto-column colpos)
801 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
802 (setq org-table-may-need-update nil)
805 (defun org-table-begin (&optional table-type)
806 "Find the beginning of the table and return its position.
807 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
808 (save-excursion
809 (if (not (re-search-backward
810 (if table-type org-table-any-border-regexp
811 org-table-border-regexp)
812 nil t))
813 (progn (goto-char (point-min)) (point))
814 (goto-char (match-beginning 0))
815 (beginning-of-line 2)
816 (point))))
818 (defun org-table-end (&optional table-type)
819 "Find the end of the table and return its position.
820 With argument TABLE-TYPE, go to the end of a table.el-type table."
821 (save-excursion
822 (if (not (re-search-forward
823 (if table-type org-table-any-border-regexp
824 org-table-border-regexp)
825 nil t))
826 (goto-char (point-max))
827 (goto-char (match-beginning 0)))
828 (point-marker)))
830 (defun org-table-justify-field-maybe (&optional new)
831 "Justify the current field, text to left, number to right.
832 Optional argument NEW may specify text to replace the current field content."
833 (cond
834 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
835 ((org-at-table-hline-p))
836 ((and (not new)
837 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
838 (current-buffer)))
839 (< (point) org-table-aligned-begin-marker)
840 (>= (point) org-table-aligned-end-marker)))
841 ;; This is not the same table, force a full re-align
842 (setq org-table-may-need-update t))
843 (t ;; realign the current field, based on previous full realign
844 (let* ((pos (point)) s
845 (col (org-table-current-column))
846 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
847 l f n o e)
848 (when (> col 0)
849 (skip-chars-backward "^|\n")
850 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
851 (progn
852 (setq s (match-string 1)
853 o (match-string 0)
854 l (max 1 (- (match-end 0) (match-beginning 0) 3))
855 e (not (= (match-beginning 2) (match-end 2))))
856 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
857 l (if e "|" (setq org-table-may-need-update t) ""))
858 n (format f s))
859 (if new
860 (if (<= (length new) l) ;; FIXME: length -> str-width?
861 (setq n (format f new))
862 (setq n (concat new "|") org-table-may-need-update t)))
863 (if (equal (string-to-char n) ?-) (setq n (concat " " n)))
864 (or (equal n o)
865 (let (org-table-may-need-update)
866 (replace-match n t t))))
867 (setq org-table-may-need-update t))
868 (goto-char pos))))))
870 (defun org-table-next-field ()
871 "Go to the next field in the current table, creating new lines as needed.
872 Before doing so, re-align the table if necessary."
873 (interactive)
874 (org-table-maybe-eval-formula)
875 (org-table-maybe-recalculate-line)
876 (if (and org-table-automatic-realign
877 org-table-may-need-update)
878 (org-table-align))
879 (let ((end (org-table-end)))
880 (if (org-at-table-hline-p)
881 (end-of-line 1))
882 (condition-case nil
883 (progn
884 (re-search-forward "|" end)
885 (if (looking-at "[ \t]*$")
886 (re-search-forward "|" end))
887 (if (and (looking-at "-")
888 org-table-tab-jumps-over-hlines
889 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
890 (goto-char (match-beginning 1)))
891 (if (looking-at "-")
892 (progn
893 (beginning-of-line 0)
894 (org-table-insert-row 'below))
895 (if (looking-at " ") (forward-char 1))))
896 (error
897 (org-table-insert-row 'below)))))
899 (defun org-table-previous-field ()
900 "Go to the previous field in the table.
901 Before doing so, re-align the table if necessary."
902 (interactive)
903 (org-table-justify-field-maybe)
904 (org-table-maybe-recalculate-line)
905 (if (and org-table-automatic-realign
906 org-table-may-need-update)
907 (org-table-align))
908 (if (org-at-table-hline-p)
909 (end-of-line 1))
910 (condition-case nil
911 (progn
912 (re-search-backward "|" (org-table-begin))
913 (re-search-backward "|" (org-table-begin)))
914 (error (error "Cannot move to previous table field")))
915 (while (looking-at "|\\(-\\|[ \t]*$\\)")
916 (re-search-backward "|" (org-table-begin)))
917 (if (looking-at "| ?")
918 (goto-char (match-end 0))))
920 (defun org-table-beginning-of-field (&optional n)
921 "Move to the end of the current table field.
922 If already at or after the end, move to the end of the next table field.
923 With numeric argument N, move N-1 fields forward first."
924 (interactive "p")
925 (let ((pos (point)))
926 (while (> n 1)
927 (setq n (1- n))
928 (org-table-previous-field))
929 (if (not (re-search-backward "|" (point-at-bol 0) t))
930 (error "No more table fields before the current")
931 (goto-char (match-end 0))
932 (and (looking-at " ") (forward-char 1)))
933 (if (>= (point) pos) (org-table-beginning-of-field 2))))
935 (defun org-table-end-of-field (&optional n)
936 "Move to the beginning of the current table field.
937 If already at or before the beginning, move to the beginning of the
938 previous field.
939 With numeric argument N, move N-1 fields backward first."
940 (interactive "p")
941 (let ((pos (point)))
942 (while (> n 1)
943 (setq n (1- n))
944 (org-table-next-field))
945 (when (re-search-forward "|" (point-at-eol 1) t)
946 (backward-char 1)
947 (skip-chars-backward " ")
948 (if (and (equal (char-before (point)) ?|) (looking-at " "))
949 (forward-char 1)))
950 (if (<= (point) pos) (org-table-end-of-field 2))))
952 (defun org-table-next-row ()
953 "Go to the next row (same column) in the current table.
954 Before doing so, re-align the table if necessary."
955 (interactive)
956 (org-table-maybe-eval-formula)
957 (org-table-maybe-recalculate-line)
958 (if (or (looking-at "[ \t]*$")
959 (save-excursion (skip-chars-backward " \t") (bolp)))
960 (newline)
961 (if (and org-table-automatic-realign
962 org-table-may-need-update)
963 (org-table-align))
964 (let ((col (org-table-current-column)))
965 (beginning-of-line 2)
966 (if (or (not (org-at-table-p))
967 (org-at-table-hline-p))
968 (progn
969 (beginning-of-line 0)
970 (org-table-insert-row 'below)))
971 (org-table-goto-column col)
972 (skip-chars-backward "^|\n\r")
973 (if (looking-at " ") (forward-char 1)))))
975 (defun org-table-copy-down (n)
976 "Copy a field down in the current column.
977 If the field at the cursor is empty, copy into it the content of the nearest
978 non-empty field above. With argument N, use the Nth non-empty field.
979 If the current field is not empty, it is copied down to the next row, and
980 the cursor is moved with it. Therefore, repeating this command causes the
981 column to be filled row-by-row.
982 If the variable `org-table-copy-increment' is non-nil and the field is an
983 integer or a timestamp, it will be incremented while copying. In the case of
984 a timestamp, if the cursor is on the year, change the year. If it is on the
985 month or the day, change that. Point will stay on the current date field
986 in order to easily repeat the interval."
987 (interactive "p")
988 (let* ((colpos (org-table-current-column))
989 (col (current-column))
990 (field (org-table-get-field))
991 (non-empty (string-match "[^ \t]" field))
992 (beg (org-table-begin))
993 (orig-n n)
994 txt)
995 (org-table-check-inside-data-field)
996 (if non-empty
997 (progn
998 (setq txt (org-trim field))
999 (org-table-next-row)
1000 (org-table-blank-field))
1001 (save-excursion
1002 (setq txt
1003 (catch 'exit
1004 (while (progn (beginning-of-line 1)
1005 (re-search-backward org-table-dataline-regexp
1006 beg t))
1007 (org-table-goto-column colpos t)
1008 (if (and (looking-at
1009 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1010 (<= (setq n (1- n)) 0))
1011 (throw 'exit (match-string 1))))))))
1012 (if txt
1013 (progn
1014 (if (and org-table-copy-increment
1015 (not (equal orig-n 0))
1016 (string-match "^[0-9]+$" txt)
1017 (< (string-to-number txt) 100000000))
1018 (setq txt (format "%d" (+ (string-to-number txt) 1))))
1019 (insert txt)
1020 (org-move-to-column col)
1021 (if (and org-table-copy-increment (org-at-timestamp-p t))
1022 (org-timestamp-up-day)
1023 (org-table-maybe-recalculate-line))
1024 (org-table-align)
1025 (org-move-to-column col))
1026 (error "No non-empty field found"))))
1028 (defun org-table-check-inside-data-field ()
1029 "Is point inside a table data field?
1030 I.e. not on a hline or before the first or after the last column?
1031 This actually throws an error, so it aborts the current command."
1032 (if (or (not (org-at-table-p))
1033 (= (org-table-current-column) 0)
1034 (org-at-table-hline-p)
1035 (looking-at "[ \t]*$"))
1036 (error "Not in table data field")))
1038 (defvar org-table-clip nil
1039 "Clipboard for table regions.")
1041 (defun org-table-get (line column)
1042 "Get the field in table line LINE, column COLUMN.
1043 If LINE is larger than the number of data lines in the table, the function
1044 returns nil. However, if COLUMN is too large, we will simply return an
1045 empty string.
1046 If LINE is nil, use the current line.
1047 If column is nil, use the current column."
1048 (setq column (or column (org-table-current-column)))
1049 (save-excursion
1050 (and (or (not line) (org-table-goto-line line))
1051 (org-trim (org-table-get-field column)))))
1053 (defun org-table-put (line column value &optional align)
1054 "Put VALUE into line LINE, column COLUMN.
1055 When ALIGN is set, als realign the table."
1056 (setq column (or column (org-table-current-column)))
1057 (prog1 (save-excursion
1058 (and (or (not line) (org-table-goto-line line))
1059 (progn (org-table-goto-column column nil 'force) t)
1060 (org-table-get-field column value)))
1061 (and align (org-table-align))))
1063 (defun org-table-current-line ()
1064 "Return the index of the current data line."
1065 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1066 (save-excursion
1067 (goto-char (org-table-begin))
1068 (while (and (re-search-forward org-table-dataline-regexp end t)
1069 (setq cnt (1+ cnt))
1070 (< (point-at-eol) pos))))
1071 cnt))
1073 (defun org-table-goto-line (N)
1074 "Go to the Nth data line in the current table.
1075 Return t when the line exists, nil if it does not exist."
1076 (goto-char (org-table-begin))
1077 (let ((end (org-table-end)) (cnt 0))
1078 (while (and (re-search-forward org-table-dataline-regexp end t)
1079 (< (setq cnt (1+ cnt)) N)))
1080 (= cnt N)))
1082 (defun org-table-blank-field ()
1083 "Blank the current table field or active region."
1084 (interactive)
1085 (org-table-check-inside-data-field)
1086 (if (and (interactive-p) (org-region-active-p))
1087 (let (org-table-clip)
1088 (org-table-cut-region (region-beginning) (region-end)))
1089 (skip-chars-backward "^|")
1090 (backward-char 1)
1091 (if (looking-at "|[^|\n]+")
1092 (let* ((pos (match-beginning 0))
1093 (match (match-string 0))
1094 (len (org-string-width match)))
1095 (replace-match (concat "|" (make-string (1- len) ?\ )))
1096 (goto-char (+ 2 pos))
1097 (substring match 1)))))
1099 (defun org-table-get-field (&optional n replace)
1100 "Return the value of the field in column N of current row.
1101 N defaults to current field.
1102 If REPLACE is a string, replace field with this value. The return value
1103 is always the old value."
1104 (and n (org-table-goto-column n))
1105 (skip-chars-backward "^|\n")
1106 (backward-char 1)
1107 (if (looking-at "|[^|\r\n]*")
1108 (let* ((pos (match-beginning 0))
1109 (val (buffer-substring (1+ pos) (match-end 0))))
1110 (if replace
1111 (replace-match (concat "|" replace) t t))
1112 (goto-char (min (point-at-eol) (+ 2 pos)))
1113 val)
1114 (forward-char 1) ""))
1116 (defun org-table-field-info (arg)
1117 "Show info about the current field, and highlight any reference at point."
1118 (interactive "P")
1119 (org-table-get-specials)
1120 (save-excursion
1121 (let* ((pos (point))
1122 (col (org-table-current-column))
1123 (cname (car (rassoc (int-to-string col) org-table-column-names)))
1124 (name (car (rassoc (list (org-current-line) col)
1125 org-table-named-field-locations)))
1126 (eql (org-table-get-stored-formulas))
1127 (dline (org-table-current-dline))
1128 (ref (format "@%d$%d" dline col))
1129 (ref1 (org-table-convert-refs-to-an ref))
1130 (fequation (or (assoc name eql) (assoc ref eql)))
1131 (cequation (assoc (int-to-string col) eql))
1132 (eqn (or fequation cequation)))
1133 (goto-char pos)
1134 (condition-case nil
1135 (org-table-show-reference 'local)
1136 (error nil))
1137 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1138 dline col
1139 (if cname (concat " or $" cname) "")
1140 dline col ref1
1141 (if name (concat " or $" name) "")
1142 ;; FIXME: formula info not correct if special table line
1143 (if eqn
1144 (concat ", formula: "
1145 (org-table-formula-to-user
1146 (concat
1147 (if (string-match "^[$@]"(car eqn)) "" "$")
1148 (car eqn) "=" (cdr eqn))))
1149 "")))))
1151 (defun org-table-current-column ()
1152 "Find out which column we are in."
1153 (save-excursion
1154 (let ((cnt 0) (pos (point)))
1155 (beginning-of-line 1)
1156 (while (search-forward "|" pos t)
1157 (setq cnt (1+ cnt)))
1158 cnt)))
1160 (defun org-table-current-dline ()
1161 "Find out what table data line we are in.
1162 Only datalines count for this."
1163 (interactive)
1164 (if (interactive-p) (org-table-check-inside-data-field))
1165 (save-excursion
1166 (let ((cnt 0) (pos (point)))
1167 (goto-char (org-table-begin))
1168 (while (<= (point) pos)
1169 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
1170 (beginning-of-line 2))
1171 (if (interactive-p) (message "This is table line %d" cnt))
1172 cnt)))
1174 (defun org-table-goto-column (n &optional on-delim force)
1175 "Move the cursor to the Nth column in the current table line.
1176 With optional argument ON-DELIM, stop with point before the left delimiter
1177 of the field.
1178 If there are less than N fields, just go to after the last delimiter.
1179 However, when FORCE is non-nil, create new columns if necessary."
1180 (interactive "p")
1181 (beginning-of-line 1)
1182 (when (> n 0)
1183 (while (and (> (setq n (1- n)) -1)
1184 (or (search-forward "|" (point-at-eol) t)
1185 (and force
1186 (progn (end-of-line 1)
1187 (skip-chars-backward "^|")
1188 (insert " | ")
1189 t)))))
1190 (when (and force (not (looking-at ".*|")))
1191 (save-excursion (end-of-line 1) (insert " | ")))
1192 (if on-delim
1193 (backward-char 1)
1194 (if (looking-at " ") (forward-char 1)))))
1196 (defun org-table-insert-column ()
1197 "Insert a new column into the table."
1198 (interactive)
1199 (if (not (org-at-table-p))
1200 (error "Not at a table"))
1201 (org-table-find-dataline)
1202 (let* ((col (max 1 (org-table-current-column)))
1203 (beg (org-table-begin))
1204 (end (org-table-end))
1205 ;; Current cursor position
1206 (linepos (org-current-line))
1207 (colpos col))
1208 (goto-char beg)
1209 (while (< (point) end)
1210 (if (org-at-table-hline-p)
1212 (org-table-goto-column col t)
1213 (insert "| "))
1214 (beginning-of-line 2))
1215 (move-marker end nil)
1216 (org-goto-line linepos)
1217 (org-table-goto-column colpos)
1218 (org-table-align)
1219 (org-table-fix-formulas "$" nil (1- col) 1)
1220 (org-table-fix-formulas "$LR" nil (1- col) 1)))
1222 (defun org-table-find-dataline ()
1223 "Find a dataline in the current table, which is needed for column commands."
1224 (if (and (org-at-table-p)
1225 (not (org-at-table-hline-p)))
1227 (let ((col (current-column))
1228 (end (org-table-end)))
1229 (org-move-to-column col)
1230 (while (and (< (point) end)
1231 (or (not (= (current-column) col))
1232 (org-at-table-hline-p)))
1233 (beginning-of-line 2)
1234 (org-move-to-column col))
1235 (if (and (org-at-table-p)
1236 (not (org-at-table-hline-p)))
1238 (error
1239 "Please position cursor in a data line for column operations")))))
1241 (defun org-table-delete-column ()
1242 "Delete a column from the table."
1243 (interactive)
1244 (if (not (org-at-table-p))
1245 (error "Not at a table"))
1246 (org-table-find-dataline)
1247 (org-table-check-inside-data-field)
1248 (let* ((col (org-table-current-column))
1249 (beg (org-table-begin))
1250 (end (org-table-end))
1251 ;; Current cursor position
1252 (linepos (org-current-line))
1253 (colpos col))
1254 (goto-char beg)
1255 (while (< (point) end)
1256 (if (org-at-table-hline-p)
1258 (org-table-goto-column col t)
1259 (and (looking-at "|[^|\n]+|")
1260 (replace-match "|")))
1261 (beginning-of-line 2))
1262 (move-marker end nil)
1263 (org-goto-line linepos)
1264 (org-table-goto-column colpos)
1265 (org-table-align)
1266 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
1267 col -1 col)
1268 (org-table-fix-formulas "$LR" (list (cons (number-to-string col) "INVALID"))
1269 col -1 col)))
1271 (defun org-table-move-column-right ()
1272 "Move column to the right."
1273 (interactive)
1274 (org-table-move-column nil))
1275 (defun org-table-move-column-left ()
1276 "Move column to the left."
1277 (interactive)
1278 (org-table-move-column 'left))
1280 (defun org-table-move-column (&optional left)
1281 "Move the current column to the right. With arg LEFT, move to the left."
1282 (interactive "P")
1283 (if (not (org-at-table-p))
1284 (error "Not at a table"))
1285 (org-table-find-dataline)
1286 (org-table-check-inside-data-field)
1287 (let* ((col (org-table-current-column))
1288 (col1 (if left (1- col) col))
1289 (beg (org-table-begin))
1290 (end (org-table-end))
1291 ;; Current cursor position
1292 (linepos (org-current-line))
1293 (colpos (if left (1- col) (1+ col))))
1294 (if (and left (= col 1))
1295 (error "Cannot move column further left"))
1296 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
1297 (error "Cannot move column further right"))
1298 (goto-char beg)
1299 (while (< (point) end)
1300 (if (org-at-table-hline-p)
1302 (org-table-goto-column col1 t)
1303 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1304 (replace-match "|\\2|\\1|")))
1305 (beginning-of-line 2))
1306 (move-marker end nil)
1307 (org-goto-line linepos)
1308 (org-table-goto-column colpos)
1309 (org-table-align)
1310 (org-table-fix-formulas
1311 "$" (list (cons (number-to-string col) (number-to-string colpos))
1312 (cons (number-to-string colpos) (number-to-string col))))
1313 (org-table-fix-formulas
1314 "$LR" (list (cons (number-to-string col) (number-to-string colpos))
1315 (cons (number-to-string colpos) (number-to-string col))))))
1317 (defun org-table-move-row-down ()
1318 "Move table row down."
1319 (interactive)
1320 (org-table-move-row nil))
1321 (defun org-table-move-row-up ()
1322 "Move table row up."
1323 (interactive)
1324 (org-table-move-row 'up))
1326 (defun org-table-move-row (&optional up)
1327 "Move the current table line down. With arg UP, move it up."
1328 (interactive "P")
1329 (let* ((col (current-column))
1330 (pos (point))
1331 (hline1p (save-excursion (beginning-of-line 1)
1332 (looking-at org-table-hline-regexp)))
1333 (dline1 (org-table-current-dline))
1334 (dline2 (+ dline1 (if up -1 1)))
1335 (tonew (if up 0 2))
1336 txt hline2p)
1337 (beginning-of-line tonew)
1338 (unless (org-at-table-p)
1339 (goto-char pos)
1340 (error "Cannot move row further"))
1341 (setq hline2p (looking-at org-table-hline-regexp))
1342 (goto-char pos)
1343 (beginning-of-line 1)
1344 (setq pos (point))
1345 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
1346 (delete-region (point) (1+ (point-at-eol)))
1347 (beginning-of-line tonew)
1348 (insert txt)
1349 (beginning-of-line 0)
1350 (org-move-to-column col)
1351 (unless (or hline1p hline2p)
1352 (org-table-fix-formulas
1353 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
1354 (cons (number-to-string dline2) (number-to-string dline1)))))))
1356 (defun org-table-insert-row (&optional arg)
1357 "Insert a new row above the current line into the table.
1358 With prefix ARG, insert below the current line."
1359 (interactive "P")
1360 (if (not (org-at-table-p))
1361 (error "Not at a table"))
1362 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1363 (new (org-table-clean-line line)))
1364 ;; Fix the first field if necessary
1365 (if (string-match "^[ \t]*| *[#$] *|" line)
1366 (setq new (replace-match (match-string 0 line) t t new)))
1367 (beginning-of-line (if arg 2 1))
1368 (let (org-table-may-need-update) (insert-before-markers new "\n"))
1369 (beginning-of-line 0)
1370 (re-search-forward "| ?" (point-at-eol) t)
1371 (and (or org-table-may-need-update org-table-overlay-coordinates)
1372 (org-table-align))
1373 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
1375 (defun org-table-insert-hline (&optional above)
1376 "Insert a horizontal-line below the current line into the table.
1377 With prefix ABOVE, insert above the current line."
1378 (interactive "P")
1379 (if (not (org-at-table-p))
1380 (error "Not at a table"))
1381 (when (eobp) (insert "\n") (backward-char 1))
1382 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1383 (org-table-align))
1384 (let ((line (org-table-clean-line
1385 (buffer-substring (point-at-bol) (point-at-eol))))
1386 (col (current-column)))
1387 (while (string-match "|\\( +\\)|" line)
1388 (setq line (replace-match
1389 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1390 ?-) "|") t t line)))
1391 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
1392 (beginning-of-line (if above 1 2))
1393 (insert line "\n")
1394 (beginning-of-line (if above 1 -1))
1395 (org-move-to-column col)
1396 (and org-table-overlay-coordinates (org-table-align))))
1398 (defun org-table-hline-and-move (&optional same-column)
1399 "Insert a hline and move to the row below that line."
1400 (interactive "P")
1401 (let ((col (org-table-current-column)))
1402 (org-table-maybe-eval-formula)
1403 (org-table-maybe-recalculate-line)
1404 (org-table-insert-hline)
1405 (end-of-line 2)
1406 (if (looking-at "\n[ \t]*|-")
1407 (progn (insert "\n|") (org-table-align))
1408 (org-table-next-field))
1409 (if same-column (org-table-goto-column col))))
1411 (defun org-table-clean-line (s)
1412 "Convert a table line S into a string with only \"|\" and space.
1413 In particular, this does handle wide and invisible characters."
1414 (if (string-match "^[ \t]*|-" s)
1415 ;; It's a hline, just map the characters
1416 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
1417 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
1418 (setq s (replace-match
1419 (concat "|" (make-string (org-string-width (match-string 1 s))
1420 ?\ ) "|")
1421 t t s)))
1424 (defun org-table-kill-row ()
1425 "Delete the current row or horizontal line from the table."
1426 (interactive)
1427 (if (not (org-at-table-p))
1428 (error "Not at a table"))
1429 (let ((col (current-column))
1430 (dline (org-table-current-dline)))
1431 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1432 (if (not (org-at-table-p)) (beginning-of-line 0))
1433 (org-move-to-column col)
1434 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
1435 dline -1 dline)))
1437 (defun org-table-sort-lines (with-case &optional sorting-type)
1438 "Sort table lines according to the column at point.
1440 The position of point indicates the column to be used for
1441 sorting, and the range of lines is the range between the nearest
1442 horizontal separator lines, or the entire table of no such lines
1443 exist. If point is before the first column, you will be prompted
1444 for the sorting column. If there is an active region, the mark
1445 specifies the first line and the sorting column, while point
1446 should be in the last line to be included into the sorting.
1448 The command then prompts for the sorting type which can be
1449 alphabetically, numerically, or by time (as given in a time stamp
1450 in the field). Sorting in reverse order is also possible.
1452 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1454 If SORTING-TYPE is specified when this function is called from a Lisp
1455 program, no prompting will take place. SORTING-TYPE must be a character,
1456 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1457 should be done in reverse order."
1458 (interactive "P")
1459 (let* ((thisline (org-current-line))
1460 (thiscol (org-table-current-column))
1461 beg end bcol ecol tend tbeg column lns pos)
1462 (when (equal thiscol 0)
1463 (if (interactive-p)
1464 (setq thiscol
1465 (string-to-number
1466 (read-string "Use column N for sorting: ")))
1467 (setq thiscol 1))
1468 (org-table-goto-column thiscol))
1469 (org-table-check-inside-data-field)
1470 (if (org-region-active-p)
1471 (progn
1472 (setq beg (region-beginning) end (region-end))
1473 (goto-char beg)
1474 (setq column (org-table-current-column)
1475 beg (point-at-bol))
1476 (goto-char end)
1477 (setq end (point-at-bol 2)))
1478 (setq column (org-table-current-column)
1479 pos (point)
1480 tbeg (org-table-begin)
1481 tend (org-table-end))
1482 (if (re-search-backward org-table-hline-regexp tbeg t)
1483 (setq beg (point-at-bol 2))
1484 (goto-char tbeg)
1485 (setq beg (point-at-bol 1)))
1486 (goto-char pos)
1487 (if (re-search-forward org-table-hline-regexp tend t)
1488 (setq end (point-at-bol 1))
1489 (goto-char tend)
1490 (setq end (point-at-bol))))
1491 (setq beg (move-marker (make-marker) beg)
1492 end (move-marker (make-marker) end))
1493 (untabify beg end)
1494 (goto-char beg)
1495 (org-table-goto-column column)
1496 (skip-chars-backward "^|")
1497 (setq bcol (current-column))
1498 (org-table-goto-column (1+ column))
1499 (skip-chars-backward "^|")
1500 (setq ecol (1- (current-column)))
1501 (org-table-goto-column column)
1502 (setq lns (mapcar (lambda(x) (cons
1503 (org-sort-remove-invisible
1504 (nth (1- column)
1505 (org-split-string x "[ \t]*|[ \t]*")))
1507 (org-split-string (buffer-substring beg end) "\n")))
1508 (setq lns (org-do-sort lns "Table" with-case sorting-type))
1509 (delete-region beg end)
1510 (move-marker beg nil)
1511 (move-marker end nil)
1512 (insert (mapconcat 'cdr lns "\n") "\n")
1513 (org-goto-line thisline)
1514 (org-table-goto-column thiscol)
1515 (message "%d lines sorted, based on column %d" (length lns) column)))
1518 (defun org-table-cut-region (beg end)
1519 "Copy region in table to the clipboard and blank all relevant fields.
1520 If there is no active region, use just the field at point."
1521 (interactive (list
1522 (if (org-region-active-p) (region-beginning) (point))
1523 (if (org-region-active-p) (region-end) (point))))
1524 (org-table-copy-region beg end 'cut))
1526 (defun org-table-copy-region (beg end &optional cut)
1527 "Copy rectangular region in table to clipboard.
1528 A special clipboard is used which can only be accessed
1529 with `org-table-paste-rectangle'."
1530 (interactive (list
1531 (if (org-region-active-p) (region-beginning) (point))
1532 (if (org-region-active-p) (region-end) (point))
1533 current-prefix-arg))
1534 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1535 region cols
1536 (rpl (if cut " " nil)))
1537 (goto-char beg)
1538 (org-table-check-inside-data-field)
1539 (setq l01 (org-current-line)
1540 c01 (org-table-current-column))
1541 (goto-char end)
1542 (org-table-check-inside-data-field)
1543 (setq l02 (org-current-line)
1544 c02 (org-table-current-column))
1545 (setq l1 (min l01 l02) l2 (max l01 l02)
1546 c1 (min c01 c02) c2 (max c01 c02))
1547 (catch 'exit
1548 (while t
1549 (catch 'nextline
1550 (if (> l1 l2) (throw 'exit t))
1551 (org-goto-line l1)
1552 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
1553 (setq cols nil ic1 c1 ic2 c2)
1554 (while (< ic1 (1+ ic2))
1555 (push (org-table-get-field ic1 rpl) cols)
1556 (setq ic1 (1+ ic1)))
1557 (push (nreverse cols) region)
1558 (setq l1 (1+ l1)))))
1559 (setq org-table-clip (nreverse region))
1560 (if cut (org-table-align))
1561 org-table-clip))
1563 (defun org-table-paste-rectangle ()
1564 "Paste a rectangular region into a table.
1565 The upper right corner ends up in the current field. All involved fields
1566 will be overwritten. If the rectangle does not fit into the present table,
1567 the table is enlarged as needed. The process ignores horizontal separator
1568 lines."
1569 (interactive)
1570 (unless (and org-table-clip (listp org-table-clip))
1571 (error "First cut/copy a region to paste!"))
1572 (org-table-check-inside-data-field)
1573 (let* ((clip org-table-clip)
1574 (line (org-current-line))
1575 (col (org-table-current-column))
1576 (org-enable-table-editor t)
1577 (org-table-automatic-realign nil)
1578 c cols field)
1579 (while (setq cols (pop clip))
1580 (while (org-at-table-hline-p) (beginning-of-line 2))
1581 (if (not (org-at-table-p))
1582 (progn (end-of-line 0) (org-table-next-field)))
1583 (setq c col)
1584 (while (setq field (pop cols))
1585 (org-table-goto-column c nil 'force)
1586 (org-table-get-field nil field)
1587 (setq c (1+ c)))
1588 (beginning-of-line 2))
1589 (org-goto-line line)
1590 (org-table-goto-column col)
1591 (org-table-align)))
1593 (defun org-table-convert ()
1594 "Convert from `org-mode' table to table.el and back.
1595 Obviously, this only works within limits. When an Org-mode table is
1596 converted to table.el, all horizontal separator lines get lost, because
1597 table.el uses these as cell boundaries and has no notion of horizontal lines.
1598 A table.el table can be converted to an Org-mode table only if it does not
1599 do row or column spanning. Multiline cells will become multiple cells.
1600 Beware, Org-mode does not test if the table can be successfully converted - it
1601 blindly applies a recipe that works for simple tables."
1602 (interactive)
1603 (require 'table)
1604 (if (org-at-table.el-p)
1605 ;; convert to Org-mode table
1606 (let ((beg (move-marker (make-marker) (org-table-begin t)))
1607 (end (move-marker (make-marker) (org-table-end t))))
1608 (table-unrecognize-region beg end)
1609 (goto-char beg)
1610 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
1611 (replace-match ""))
1612 (goto-char beg))
1613 (if (org-at-table-p)
1614 ;; convert to table.el table
1615 (let ((beg (move-marker (make-marker) (org-table-begin)))
1616 (end (move-marker (make-marker) (org-table-end))))
1617 ;; first, get rid of all horizontal lines
1618 (goto-char beg)
1619 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
1620 (replace-match ""))
1621 ;; insert a hline before first
1622 (goto-char beg)
1623 (org-table-insert-hline 'above)
1624 (beginning-of-line -1)
1625 ;; insert a hline after each line
1626 (while (progn (beginning-of-line 3) (< (point) end))
1627 (org-table-insert-hline))
1628 (goto-char beg)
1629 (setq end (move-marker end (org-table-end)))
1630 ;; replace "+" at beginning and ending of hlines
1631 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
1632 (replace-match "\\1+-"))
1633 (goto-char beg)
1634 (while (re-search-forward "-|[ \t]*$" end t)
1635 (replace-match "-+"))
1636 (goto-char beg)))))
1638 (defun org-table-wrap-region (arg)
1639 "Wrap several fields in a column like a paragraph.
1640 This is useful if you'd like to spread the contents of a field over several
1641 lines, in order to keep the table compact.
1643 If there is an active region, and both point and mark are in the same column,
1644 the text in the column is wrapped to minimum width for the given number of
1645 lines. Generally, this makes the table more compact. A prefix ARG may be
1646 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1647 formats the selected text to two lines. If the region was longer than two
1648 lines, the remaining lines remain empty. A negative prefix argument reduces
1649 the current number of lines by that amount. The wrapped text is pasted back
1650 into the table. If you formatted it to more lines than it was before, fields
1651 further down in the table get overwritten - so you might need to make space in
1652 the table first.
1654 If there is no region, the current field is split at the cursor position and
1655 the text fragment to the right of the cursor is prepended to the field one
1656 line down.
1658 If there is no region, but you specify a prefix ARG, the current field gets
1659 blank, and the content is appended to the field above."
1660 (interactive "P")
1661 (org-table-check-inside-data-field)
1662 (if (org-region-active-p)
1663 ;; There is a region: fill as a paragraph
1664 (let* ((beg (region-beginning))
1665 (cline (save-excursion (goto-char beg) (org-current-line)))
1666 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
1667 nlines)
1668 (org-table-cut-region (region-beginning) (region-end))
1669 (if (> (length (car org-table-clip)) 1)
1670 (error "Region must be limited to single column"))
1671 (setq nlines (if arg
1672 (if (< arg 1)
1673 (+ (length org-table-clip) arg)
1674 arg)
1675 (length org-table-clip)))
1676 (setq org-table-clip
1677 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
1678 nil nlines)))
1679 (org-goto-line cline)
1680 (org-table-goto-column ccol)
1681 (org-table-paste-rectangle))
1682 ;; No region, split the current field at point
1683 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
1684 (skip-chars-forward "^\r\n|"))
1685 (if arg
1686 ;; combine with field above
1687 (let ((s (org-table-blank-field))
1688 (col (org-table-current-column)))
1689 (beginning-of-line 0)
1690 (while (org-at-table-hline-p) (beginning-of-line 0))
1691 (org-table-goto-column col)
1692 (skip-chars-forward "^|")
1693 (skip-chars-backward " ")
1694 (insert " " (org-trim s))
1695 (org-table-align))
1696 ;; split field
1697 (if (looking-at "\\([^|]+\\)+|")
1698 (let ((s (match-string 1)))
1699 (replace-match " |")
1700 (goto-char (match-beginning 0))
1701 (org-table-next-row)
1702 (insert (org-trim s) " ")
1703 (org-table-align))
1704 (org-table-next-row)))))
1706 (defvar org-field-marker nil)
1708 (defun org-table-edit-field (arg)
1709 "Edit table field in a different window.
1710 This is mainly useful for fields that contain hidden parts.
1711 When called with a \\[universal-argument] prefix, just make the full field visible so that
1712 it can be edited in place."
1713 (interactive "P")
1714 (if arg
1715 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1716 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1717 (remove-text-properties b e '(org-cwidth t invisible t
1718 display t intangible t))
1719 (if (and (boundp 'font-lock-mode) font-lock-mode)
1720 (font-lock-fontify-block)))
1721 (let ((pos (move-marker (make-marker) (point)))
1722 (field (org-table-get-field))
1723 (cw (current-window-configuration))
1725 (org-switch-to-buffer-other-window "*Org tmp*")
1726 (erase-buffer)
1727 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
1728 (let ((org-inhibit-startup t)) (org-mode))
1729 (goto-char (setq p (point-max)))
1730 (insert (org-trim field))
1731 (remove-text-properties p (point-max)
1732 '(invisible t org-cwidth t display t
1733 intangible t))
1734 (goto-char p)
1735 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
1736 (org-set-local 'org-window-configuration cw)
1737 (org-set-local 'org-field-marker pos)
1738 (message "Edit and finish with C-c C-c"))))
1740 (defun org-table-finish-edit-field ()
1741 "Finish editing a table data field.
1742 Remove all newline characters, insert the result into the table, realign
1743 the table and kill the editing buffer."
1744 (let ((pos org-field-marker)
1745 (cw org-window-configuration)
1746 (cb (current-buffer))
1747 text)
1748 (goto-char (point-min))
1749 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
1750 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
1751 (replace-match " "))
1752 (setq text (org-trim (buffer-string)))
1753 (set-window-configuration cw)
1754 (kill-buffer cb)
1755 (select-window (get-buffer-window (marker-buffer pos)))
1756 (goto-char pos)
1757 (move-marker pos nil)
1758 (org-table-check-inside-data-field)
1759 (org-table-get-field nil text)
1760 (org-table-align)
1761 (message "New field value inserted")))
1763 (defvar org-timecnt) ; dynamically scoped parameter
1765 (defun org-table-sum (&optional beg end nlast)
1766 "Sum numbers in region of current table column.
1767 The result will be displayed in the echo area, and will be available
1768 as kill to be inserted with \\[yank].
1770 If there is an active region, it is interpreted as a rectangle and all
1771 numbers in that rectangle will be summed. If there is no active
1772 region and point is located in a table column, sum all numbers in that
1773 column.
1775 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1776 numbers are assumed to be times as well (in decimal hours) and the
1777 numbers are added as such.
1779 If NLAST is a number, only the NLAST fields will actually be summed."
1780 (interactive)
1781 (save-excursion
1782 (let (col (org-timecnt 0) diff h m s org-table-clip)
1783 (cond
1784 ((and beg end)) ; beg and end given explicitly
1785 ((org-region-active-p)
1786 (setq beg (region-beginning) end (region-end)))
1788 (setq col (org-table-current-column))
1789 (goto-char (org-table-begin))
1790 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
1791 (error "No table data"))
1792 (org-table-goto-column col)
1793 (setq beg (point))
1794 (goto-char (org-table-end))
1795 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
1796 (error "No table data"))
1797 (org-table-goto-column col)
1798 (setq end (point))))
1799 (let* ((items (apply 'append (org-table-copy-region beg end)))
1800 (items1 (cond ((not nlast) items)
1801 ((>= nlast (length items)) items)
1802 (t (setq items (reverse items))
1803 (setcdr (nthcdr (1- nlast) items) nil)
1804 (nreverse items))))
1805 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
1806 items1)))
1807 (res (apply '+ numbers))
1808 (sres (if (= org-timecnt 0)
1809 (number-to-string res)
1810 (setq diff (* 3600 res)
1811 h (floor (/ diff 3600)) diff (mod diff 3600)
1812 m (floor (/ diff 60)) diff (mod diff 60)
1813 s diff)
1814 (format "%d:%02d:%02d" h m s))))
1815 (kill-new sres)
1816 (if (interactive-p)
1817 (message "%s"
1818 (substitute-command-keys
1819 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
1820 (length numbers) sres))))
1821 sres))))
1823 (defun org-table-get-number-for-summing (s)
1824 (let (n)
1825 (if (string-match "^ *|? *" s)
1826 (setq s (replace-match "" nil nil s)))
1827 (if (string-match " *|? *$" s)
1828 (setq s (replace-match "" nil nil s)))
1829 (setq n (string-to-number s))
1830 (cond
1831 ((and (string-match "0" s)
1832 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
1833 ((string-match "\\`[ \t]+\\'" s) nil)
1834 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
1835 (let ((h (string-to-number (or (match-string 1 s) "0")))
1836 (m (string-to-number (or (match-string 2 s) "0")))
1837 (s (string-to-number (or (match-string 4 s) "0"))))
1838 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
1839 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
1840 ((equal n 0) nil)
1841 (t n))))
1843 (defun org-table-current-field-formula (&optional key noerror)
1844 "Return the formula active for the current field.
1845 Assumes that specials are in place.
1846 If KEY is given, return the key to this formula.
1847 Otherwise return the formula preceeded with \"=\" or \":=\"."
1848 (let* ((name (car (rassoc (list (org-current-line)
1849 (org-table-current-column))
1850 org-table-named-field-locations)))
1851 (col (org-table-current-column))
1852 (scol (int-to-string col))
1853 (ref (format "@%d$%d" (org-table-current-dline) col))
1854 (stored-list (org-table-get-stored-formulas noerror))
1855 (ass (or (assoc name stored-list)
1856 (assoc ref stored-list)
1857 (assoc scol stored-list))))
1858 (if key
1859 (car ass)
1860 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
1861 (cdr ass))))))
1863 (defun org-table-get-formula (&optional equation named)
1864 "Read a formula from the minibuffer, offer stored formula as default.
1865 When NAMED is non-nil, look for a named equation."
1866 (let* ((stored-list (org-table-get-stored-formulas))
1867 (name (car (rassoc (list (org-current-line)
1868 (org-table-current-column))
1869 org-table-named-field-locations)))
1870 (ref (format "@%d$%d" (org-table-current-dline)
1871 (org-table-current-column)))
1872 (refass (assoc ref stored-list))
1873 (nameass (assoc name stored-list))
1874 (scol (if named
1875 (if (and name (not (string-match "^LR[0-9]+$" name)))
1876 name
1877 ref)
1878 (int-to-string (org-table-current-column))))
1879 (dummy (and (or nameass refass) (not named)
1880 (not (y-or-n-p "Replace existing field formula with column formula? " ))
1881 (error "Abort")))
1882 (name (or name ref))
1883 (org-table-may-need-update nil)
1884 (stored (cdr (assoc scol stored-list)))
1885 (eq (cond
1886 ((and stored equation (string-match "^ *=? *$" equation))
1887 stored)
1888 ((stringp equation)
1889 equation)
1890 (t (org-table-formula-from-user
1891 (read-string
1892 (org-table-formula-to-user
1893 (format "%s formula %s%s="
1894 (if named "Field" "Column")
1895 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
1896 scol))
1897 (if stored (org-table-formula-to-user stored) "")
1898 'org-table-formula-history
1899 )))))
1900 mustsave)
1901 (when (not (string-match "\\S-" eq))
1902 ;; remove formula
1903 (setq stored-list (delq (assoc scol stored-list) stored-list))
1904 (org-table-store-formulas stored-list)
1905 (error "Formula removed"))
1906 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
1907 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
1908 (if (and name (not named))
1909 ;; We set the column equation, delete the named one.
1910 (setq stored-list (delq (assoc name stored-list) stored-list)
1911 mustsave t))
1912 (if stored
1913 (setcdr (assoc scol stored-list) eq)
1914 (setq stored-list (cons (cons scol eq) stored-list)))
1915 (if (or mustsave (not (equal stored eq)))
1916 (org-table-store-formulas stored-list))
1917 eq))
1919 (defun org-table-store-formulas (alist)
1920 "Store the list of formulas below the current table."
1921 (setq alist (sort alist 'org-table-formula-less-p))
1922 (save-excursion
1923 (goto-char (org-table-end))
1924 (if (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM:\\(.*\n?\\)")
1925 (progn
1926 ;; don't overwrite TBLFM, we might use text properties to store stuff
1927 (goto-char (match-beginning 2))
1928 (delete-region (match-beginning 2) (match-end 0)))
1929 (org-indent-line-function)
1930 (insert "#+TBLFM:"))
1931 (insert " "
1932 (mapconcat (lambda (x)
1933 (concat
1934 (if (equal (string-to-char (car x)) ?@) "" "$")
1935 (car x) "=" (cdr x)))
1936 alist "::")
1937 "\n")))
1939 (defsubst org-table-formula-make-cmp-string (a)
1940 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
1941 (concat
1942 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
1943 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
1944 (if (match-end 5) (concat "@@" (match-string 5 a))))))
1946 (defun org-table-formula-less-p (a b)
1947 "Compare two formulas for sorting."
1948 (let ((as (org-table-formula-make-cmp-string (car a)))
1949 (bs (org-table-formula-make-cmp-string (car b))))
1950 (and as bs (string< as bs))))
1952 (defun org-table-get-stored-formulas (&optional noerror)
1953 "Return an alist with the stored formulas directly after current table."
1954 (interactive)
1955 (let (scol eq eq-alist strings string seen)
1956 (save-excursion
1957 (goto-char (org-table-end))
1958 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
1959 (setq strings (org-split-string (match-string 2) " *:: *"))
1960 (while (setq string (pop strings))
1961 (when (string-match "\\`\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
1962 (setq scol (if (match-end 2)
1963 (match-string 2 string)
1964 (match-string 1 string))
1965 eq (match-string 3 string)
1966 eq-alist (cons (cons scol eq) eq-alist))
1967 (if (member scol seen)
1968 (if noerror
1969 (progn
1970 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
1971 (ding)
1972 (sit-for 2))
1973 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
1974 (push scol seen))))))
1975 (nreverse eq-alist)))
1977 (defun org-table-fix-formulas (key replace &optional limit delta remove)
1978 "Modify the equations after the table structure has been edited.
1979 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
1980 For all numbers larger than LIMIT, shift them by DELTA."
1981 (save-excursion
1982 (goto-char (org-table-end))
1983 (when (looking-at "[ \t]*#\\+TBLFM:")
1984 (let ((re (concat key "\\([0-9]+\\)"))
1985 (re2
1986 (when remove
1987 (if (or (equal key "$") (equal key "$LR"))
1988 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
1989 (regexp-quote key) remove)
1990 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
1991 s n a)
1992 (when remove
1993 (while (re-search-forward re2 (point-at-eol) t)
1994 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
1995 (replace-match ""))))
1996 (while (re-search-forward re (point-at-eol) t)
1997 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
1998 (setq s (match-string 1) n (string-to-number s))
1999 (cond
2000 ((setq a (assoc s replace))
2001 (replace-match (concat key (cdr a)) t t))
2002 ((and limit (> n limit))
2003 (replace-match (concat key (int-to-string (+ n delta)))
2004 t t)))))))))
2006 (defun org-table-get-specials ()
2007 "Get the column names and local parameters for this table."
2008 (save-excursion
2009 (let ((beg (org-table-begin)) (end (org-table-end))
2010 names name fields fields1 field cnt
2011 c v l line col types dlines hlines last-dline)
2012 (setq org-table-column-names nil
2013 org-table-local-parameters nil
2014 org-table-named-field-locations nil
2015 org-table-current-begin-line nil
2016 org-table-current-begin-pos nil
2017 org-table-current-line-types nil)
2018 (goto-char beg)
2019 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
2020 (setq names (org-split-string (match-string 1) " *| *")
2021 cnt 1)
2022 (while (setq name (pop names))
2023 (setq cnt (1+ cnt))
2024 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
2025 (push (cons name (int-to-string cnt)) org-table-column-names))))
2026 (setq org-table-column-names (nreverse org-table-column-names))
2027 (setq org-table-column-name-regexp
2028 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
2029 (goto-char beg)
2030 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
2031 (setq fields (org-split-string (match-string 1) " *| *"))
2032 (while (setq field (pop fields))
2033 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
2034 (push (cons (match-string 1 field) (match-string 2 field))
2035 org-table-local-parameters))))
2036 (goto-char beg)
2037 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
2038 (setq c (match-string 1)
2039 fields (org-split-string (match-string 2) " *| *"))
2040 (save-excursion
2041 (beginning-of-line (if (equal c "_") 2 0))
2042 (setq line (org-current-line) col 1)
2043 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2044 (setq fields1 (org-split-string (match-string 1) " *| *"))))
2045 (while (and fields1 (setq field (pop fields)))
2046 (setq v (pop fields1) col (1+ col))
2047 (when (and (stringp field) (stringp v)
2048 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
2049 (push (cons field v) org-table-local-parameters)
2050 (push (list field line col) org-table-named-field-locations))))
2051 ;; Analyse the line types
2052 (goto-char beg)
2053 (setq org-table-current-begin-line (org-current-line)
2054 org-table-current-begin-pos (point)
2055 l org-table-current-begin-line)
2056 (while (looking-at "[ \t]*|\\(-\\)?")
2057 (push (if (match-end 1) 'hline 'dline) types)
2058 (if (match-end 1) (push l hlines) (push l dlines))
2059 (beginning-of-line 2)
2060 (setq l (1+ l)))
2061 (push 'hline types) ;; add an imaginary extra hline to the end
2062 (setq org-table-current-line-types (apply 'vector (nreverse types))
2063 last-dline (car dlines)
2064 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
2065 org-table-hlines (apply 'vector (cons nil (nreverse hlines))))
2066 (org-goto-line last-dline)
2067 (let* ((l last-dline)
2068 (fields (org-split-string
2069 (buffer-substring (point-at-bol) (point-at-eol))
2070 "[ \t]*|[ \t]*"))
2071 (nfields (length fields))
2072 al al2)
2073 (loop for i from 1 to nfields do
2074 (push (list (format "LR%d" i) l i) al)
2075 (push (cons (format "LR%d" i) (nth (1- i) fields)) al2))
2076 (setq org-table-named-field-locations
2077 (append org-table-named-field-locations al))
2078 (setq org-table-local-parameters
2079 (append org-table-local-parameters al2))))))
2082 (defun org-table-maybe-eval-formula ()
2083 "Check if the current field starts with \"=\" or \":=\".
2084 If yes, store the formula and apply it."
2085 ;; We already know we are in a table. Get field will only return a formula
2086 ;; when appropriate. It might return a separator line, but no problem.
2087 (when org-table-formula-evaluate-inline
2088 (let* ((field (org-trim (or (org-table-get-field) "")))
2089 named eq)
2090 (when (string-match "^:?=\\(.*\\)" field)
2091 (setq named (equal (string-to-char field) ?:)
2092 eq (match-string 1 field))
2093 (if (or (fboundp 'calc-eval)
2094 (equal (substring eq 0 (min 2 (length eq))) "'("))
2095 (org-table-eval-formula (if named '(4) nil)
2096 (org-table-formula-from-user eq))
2097 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2099 (defvar org-recalc-commands nil
2100 "List of commands triggering the recalculation of a line.
2101 Will be filled automatically during use.")
2103 (defvar org-recalc-marks
2104 '((" " . "Unmarked: no special line, no automatic recalculation")
2105 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2106 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
2107 ("!" . "Column name definition line. Reference in formula as $name.")
2108 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
2109 ("_" . "Names for values in row below this one.")
2110 ("^" . "Names for values in row above this one.")))
2112 (defun org-table-rotate-recalc-marks (&optional newchar)
2113 "Rotate the recalculation mark in the first column.
2114 If in any row, the first field is not consistent with a mark,
2115 insert a new column for the markers.
2116 When there is an active region, change all the lines in the region,
2117 after prompting for the marking character.
2118 After each change, a message will be displayed indicating the meaning
2119 of the new mark."
2120 (interactive)
2121 (unless (org-at-table-p) (error "Not at a table"))
2122 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
2123 (beg (org-table-begin))
2124 (end (org-table-end))
2125 (l (org-current-line))
2126 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2127 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2128 (have-col
2129 (save-excursion
2130 (goto-char beg)
2131 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
2132 (col (org-table-current-column))
2133 (forcenew (car (assoc newchar org-recalc-marks)))
2134 epos new)
2135 (when l1
2136 (message "Change region to what mark? Type # * ! $ or SPC: ")
2137 (setq newchar (char-to-string (read-char-exclusive))
2138 forcenew (car (assoc newchar org-recalc-marks))))
2139 (if (and newchar (not forcenew))
2140 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2141 newchar))
2142 (if l1 (org-goto-line l1))
2143 (save-excursion
2144 (beginning-of-line 1)
2145 (unless (looking-at org-table-dataline-regexp)
2146 (error "Not at a table data line")))
2147 (unless have-col
2148 (org-table-goto-column 1)
2149 (org-table-insert-column)
2150 (org-table-goto-column (1+ col)))
2151 (setq epos (point-at-eol))
2152 (save-excursion
2153 (beginning-of-line 1)
2154 (org-table-get-field
2155 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2156 (concat " "
2157 (setq new (or forcenew
2158 (cadr (member (match-string 1) marks))))
2159 " ")
2160 " # ")))
2161 (if (and l1 l2)
2162 (progn
2163 (org-goto-line l1)
2164 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
2165 (and (looking-at org-table-dataline-regexp)
2166 (org-table-get-field 1 (concat " " new " "))))
2167 (org-goto-line l1)))
2168 (if (not (= epos (point-at-eol))) (org-table-align))
2169 (org-goto-line l)
2170 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
2172 (defun org-table-maybe-recalculate-line ()
2173 "Recompute the current line if marked for it, and if we haven't just done it."
2174 (interactive)
2175 (and org-table-allow-automatic-line-recalculation
2176 (not (and (memq last-command org-recalc-commands)
2177 (equal org-last-recalc-line (org-current-line))))
2178 (save-excursion (beginning-of-line 1)
2179 (looking-at org-table-auto-recalculate-regexp))
2180 (org-table-recalculate) t))
2182 (defvar modes)
2183 (defsubst org-set-calc-mode (var &optional value)
2184 (if (stringp var)
2185 (setq var (assoc var '(("D" calc-angle-mode deg)
2186 ("R" calc-angle-mode rad)
2187 ("F" calc-prefer-frac t)
2188 ("S" calc-symbolic-mode t)))
2189 value (nth 2 var) var (nth 1 var)))
2190 (if (memq var modes)
2191 (setcar (cdr (memq var modes)) value)
2192 (cons var (cons value modes)))
2193 modes)
2195 (defun org-table-eval-formula (&optional arg equation
2196 suppress-align suppress-const
2197 suppress-store suppress-analysis)
2198 "Replace the table field value at the cursor by the result of a calculation.
2200 This function makes use of Dave Gillespie's Calc package, in my view the
2201 most exciting program ever written for GNU Emacs. So you need to have Calc
2202 installed in order to use this function.
2204 In a table, this command replaces the value in the current field with the
2205 result of a formula. It also installs the formula as the \"current\" column
2206 formula, by storing it in a special line below the table. When called
2207 with a `C-u' prefix, the current field must be a named field, and the
2208 formula is installed as valid in only this specific field.
2210 When called with two `C-u' prefixes, insert the active equation
2211 for the field back into the current field, so that it can be
2212 edited there. This is useful in order to use \\[org-table-show-reference]
2213 to check the referenced fields.
2215 When called, the command first prompts for a formula, which is read in
2216 the minibuffer. Previously entered formulas are available through the
2217 history list, and the last used formula is offered as a default.
2218 These stored formulas are adapted correctly when moving, inserting, or
2219 deleting columns with the corresponding commands.
2221 The formula can be any algebraic expression understood by the Calc package.
2222 For details, see the Org-mode manual.
2224 This function can also be called from Lisp programs and offers
2225 additional arguments: EQUATION can be the formula to apply. If this
2226 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2227 used to speed-up recursive calls by by-passing unnecessary aligns.
2228 SUPPRESS-CONST suppresses the interpretation of constants in the
2229 formula, assuming that this has been done already outside the function.
2230 SUPPRESS-STORE means the formula should not be stored, either because
2231 it is already stored, or because it is a modified equation that should
2232 not overwrite the stored one."
2233 (interactive "P")
2234 (org-table-check-inside-data-field)
2235 (or suppress-analysis (org-table-get-specials))
2236 (if (equal arg '(16))
2237 (let ((eq (org-table-current-field-formula)))
2238 (or eq (error "No equation active for current field"))
2239 (org-table-get-field nil eq)
2240 (org-table-align)
2241 (setq org-table-may-need-update t))
2242 (let* (fields
2243 (ndown (if (integerp arg) arg 1))
2244 (org-table-automatic-realign nil)
2245 (case-fold-search nil)
2246 (down (> ndown 1))
2247 (formula (if (and equation suppress-store)
2248 equation
2249 (org-table-get-formula equation (equal arg '(4)))))
2250 (n0 (org-table-current-column))
2251 (modes (copy-sequence org-calc-default-modes))
2252 (numbers nil) ; was a variable, now fixed default
2253 (keep-empty nil)
2254 n form form0 bw fmt x ev orig c lispp literal)
2255 ;; Parse the format string. Since we have a lot of modes, this is
2256 ;; a lot of work. However, I think calc still uses most of the time.
2257 (if (string-match ";" formula)
2258 (let ((tmp (org-split-string formula ";")))
2259 (setq formula (car tmp)
2260 fmt (concat (cdr (assoc "%" org-table-local-parameters))
2261 (nth 1 tmp)))
2262 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
2263 (setq c (string-to-char (match-string 1 fmt))
2264 n (string-to-number (match-string 2 fmt)))
2265 (if (= c ?p)
2266 (setq modes (org-set-calc-mode 'calc-internal-prec n))
2267 (setq modes (org-set-calc-mode
2268 'calc-float-format
2269 (list (cdr (assoc c '((?n . float) (?f . fix)
2270 (?s . sci) (?e . eng))))
2271 n))))
2272 (setq fmt (replace-match "" t t fmt)))
2273 (if (string-match "[NT]" fmt)
2274 (setq numbers (equal (match-string 0 fmt) "N")
2275 fmt (replace-match "" t t fmt)))
2276 (if (string-match "L" fmt)
2277 (setq literal t
2278 fmt (replace-match "" t t fmt)))
2279 (if (string-match "E" fmt)
2280 (setq keep-empty t
2281 fmt (replace-match "" t t fmt)))
2282 (while (string-match "[DRFS]" fmt)
2283 (setq modes (org-set-calc-mode (match-string 0 fmt)))
2284 (setq fmt (replace-match "" t t fmt)))
2285 (unless (string-match "\\S-" fmt)
2286 (setq fmt nil))))
2287 (if (and (not suppress-const) org-table-formula-use-constants)
2288 (setq formula (org-table-formula-substitute-names formula)))
2289 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
2290 (while (> ndown 0)
2291 (setq fields (org-split-string
2292 (org-no-properties
2293 (buffer-substring (point-at-bol) (point-at-eol)))
2294 " *| *"))
2295 (if (eq numbers t)
2296 (setq fields (mapcar
2297 (lambda (x) (number-to-string (string-to-number x)))
2298 fields)))
2299 (setq ndown (1- ndown))
2300 (setq form (copy-sequence formula)
2301 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
2302 (if (and lispp literal) (setq lispp 'literal))
2304 ;; Insert row and column number of formula result field
2305 (while (string-match "[@$]#" form)
2306 (setq form
2307 (replace-match
2308 (format "%d"
2309 (save-match-data
2310 (if (equal (substring form (match-beginning 0)
2311 (1+ (match-beginning 0)))
2312 "@")
2313 (org-table-current-dline)
2314 (org-table-current-column))))
2315 t t form)))
2317 ;; Check for old vertical references
2318 (setq form (org-table-rewrite-old-row-references form))
2319 ;; Insert remote references
2320 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
2321 (setq form
2322 (replace-match
2323 (save-match-data
2324 (org-table-make-reference
2325 (org-table-get-remote-range
2326 (match-string 1 form) (match-string 2 form))
2327 keep-empty numbers lispp))
2328 t t form)))
2329 ;; Insert complex ranges
2330 (while (and (string-match org-table-range-regexp form)
2331 (> (length (match-string 0 form)) 1))
2332 (setq form
2333 (replace-match
2334 (save-match-data
2335 (org-table-make-reference
2336 (org-table-get-range (match-string 0 form) nil n0)
2337 keep-empty numbers lispp))
2338 t t form)))
2339 ;; Insert simple ranges
2340 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
2341 (setq form
2342 (replace-match
2343 (save-match-data
2344 (org-table-make-reference
2345 (org-sublist
2346 fields (string-to-number (match-string 1 form))
2347 (string-to-number (match-string 2 form)))
2348 keep-empty numbers lispp))
2349 t t form)))
2350 (setq form0 form)
2351 ;; Insert the references to fields in same row
2352 (while (string-match "\\$\\([0-9]+\\)" form)
2353 (setq n (string-to-number (match-string 1 form))
2354 x (nth (1- (if (= n 0) n0 n)) fields))
2355 (unless x (error "Invalid field specifier \"%s\""
2356 (match-string 0 form)))
2357 (setq form (replace-match
2358 (save-match-data
2359 (org-table-make-reference x nil numbers lispp))
2360 t t form)))
2362 (if lispp
2363 (setq ev (condition-case nil
2364 (eval (eval (read form)))
2365 (error "#ERROR"))
2366 ev (if (numberp ev) (number-to-string ev) ev))
2367 (or (fboundp 'calc-eval)
2368 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2369 (setq ev (calc-eval (cons form modes)
2370 (if numbers 'num))))
2372 (when org-table-formula-debug
2373 (with-output-to-temp-buffer "*Substitution History*"
2374 (princ (format "Substitution history of formula
2375 Orig: %s
2376 $xyz-> %s
2377 @r$c-> %s
2378 $1-> %s\n" orig formula form0 form))
2379 (if (listp ev)
2380 (princ (format " %s^\nError: %s"
2381 (make-string (car ev) ?\-) (nth 1 ev)))
2382 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2383 ev (or fmt "NONE")
2384 (if fmt (format fmt (string-to-number ev)) ev)))))
2385 (setq bw (get-buffer-window "*Substitution History*"))
2386 (org-fit-window-to-buffer bw)
2387 (unless (and (interactive-p) (not ndown))
2388 (unless (let (inhibit-redisplay)
2389 (y-or-n-p "Debugging Formula. Continue to next? "))
2390 (org-table-align)
2391 (error "Abort"))
2392 (delete-window bw)
2393 (message "")))
2394 (if (listp ev) (setq fmt nil ev "#ERROR"))
2395 (org-table-justify-field-maybe
2396 (if fmt (format fmt (string-to-number ev)) ev))
2397 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2398 (call-interactively 'org-return)
2399 (setq ndown 0)))
2400 (and down (org-table-maybe-recalculate-line))
2401 (or suppress-align (and org-table-may-need-update
2402 (org-table-align))))))
2404 (defun org-table-put-field-property (prop value)
2405 (save-excursion
2406 (put-text-property (progn (skip-chars-backward "^|") (point))
2407 (progn (skip-chars-forward "^|") (point))
2408 prop value)))
2410 (defun org-table-get-range (desc &optional tbeg col highlight)
2411 "Get a calc vector from a column, according to descriptor DESC.
2412 Optional arguments TBEG and COL can give the beginning of the table and
2413 the current column, to avoid unnecessary parsing.
2414 HIGHLIGHT means just highlight the range."
2415 (if (not (equal (string-to-char desc) ?@))
2416 (setq desc (concat "@" desc)))
2417 (save-excursion
2418 (or tbeg (setq tbeg (org-table-begin)))
2419 (or col (setq col (org-table-current-column)))
2420 (let ((thisline (org-current-line))
2421 beg end c1 c2 r1 r2 rangep tmp)
2422 (unless (string-match org-table-range-regexp desc)
2423 (error "Invalid table range specifier `%s'" desc))
2424 (setq rangep (match-end 3)
2425 r1 (and (match-end 1) (match-string 1 desc))
2426 r2 (and (match-end 4) (match-string 4 desc))
2427 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
2428 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
2430 (and c1 (setq c1 (+ (string-to-number c1)
2431 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
2432 (and c2 (setq c2 (+ (string-to-number c2)
2433 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
2434 (if (equal r1 "") (setq r1 nil))
2435 (if (equal r2 "") (setq r2 nil))
2436 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
2437 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
2438 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2439 (if (not r1) (setq r1 thisline))
2440 (if (not r2) (setq r2 thisline))
2441 (if (not c1) (setq c1 col))
2442 (if (not c2) (setq c2 col))
2443 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
2444 ;; just one field
2445 (progn
2446 (org-goto-line r1)
2447 (while (not (looking-at org-table-dataline-regexp))
2448 (beginning-of-line 2))
2449 (prog1 (org-trim (org-table-get-field c1))
2450 (if highlight (org-table-highlight-rectangle (point) (point)))))
2451 ;; A range, return a vector
2452 ;; First sort the numbers to get a regular ractangle
2453 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
2454 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
2455 (org-goto-line r1)
2456 (while (not (looking-at org-table-dataline-regexp))
2457 (beginning-of-line 2))
2458 (org-table-goto-column c1)
2459 (setq beg (point))
2460 (org-goto-line r2)
2461 (while (not (looking-at org-table-dataline-regexp))
2462 (beginning-of-line 0))
2463 (org-table-goto-column c2)
2464 (setq end (point))
2465 (if highlight
2466 (org-table-highlight-rectangle
2467 beg (progn (skip-chars-forward "^|\n") (point))))
2468 ;; return string representation of calc vector
2469 (mapcar 'org-trim
2470 (apply 'append (org-table-copy-region beg end)))))))
2472 (defun org-table-get-descriptor-line (desc &optional cline bline table)
2473 "Analyze descriptor DESC and retrieve the corresponding line number.
2474 The cursor is currently in line CLINE, the table begins in line BLINE,
2475 and TABLE is a vector with line types."
2476 (if (string-match "^[0-9]+$" desc)
2477 (aref org-table-dlines (string-to-number desc))
2478 (setq cline (or cline (org-current-line))
2479 bline (or bline org-table-current-begin-line)
2480 table (or table org-table-current-line-types))
2481 (if (or
2482 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
2483 ;; 1 2 3 4 5 6
2484 (and (not (match-end 3)) (not (match-end 6)))
2485 (and (match-end 3) (match-end 6) (not (match-end 5))))
2486 (error "invalid row descriptor `%s'" desc))
2487 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
2488 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
2489 (odir (and (match-end 5) (match-string 5 desc)))
2490 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
2491 (i (- cline bline))
2492 (rel (and (match-end 6)
2493 (or (and (match-end 1) (not (match-end 3)))
2494 (match-end 5)))))
2495 (if (and hn (not hdir))
2496 (progn
2497 (setq i 0 hdir "+")
2498 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
2499 (if (and (not hn) on (not odir))
2500 (error "should never happen");;(aref org-table-dlines on)
2501 (if (and hn (> hn 0))
2502 (setq i (org-table-find-row-type table i 'hline (equal hdir "-")
2503 nil hn cline desc)))
2504 (if on
2505 (setq i (org-table-find-row-type table i 'dline (equal odir "-")
2506 rel on cline desc)))
2507 (+ bline i)))))
2509 (defun org-table-find-row-type (table i type backwards relative n cline desc)
2510 "FIXME: Needs more documentation."
2511 (let ((l (length table)))
2512 (while (> n 0)
2513 (while (and (setq i (+ i (if backwards -1 1)))
2514 (>= i 0) (< i l)
2515 (not (eq (aref table i) type))
2516 (if (and relative (eq (aref table i) 'hline))
2517 (cond
2518 ((eq org-table-relative-ref-may-cross-hline t) t)
2519 ((eq org-table-relative-ref-may-cross-hline 'error)
2520 (error "Row descriptor %s used in line %d crosses hline" desc cline))
2521 (t (setq i (- i (if backwards -1 1))
2522 n 1)
2523 nil))
2524 t)))
2525 (setq n (1- n)))
2526 (if (or (< i 0) (>= i l))
2527 (error "Row descriptor %s used in line %d leads outside table"
2528 desc cline)
2529 i)))
2531 (defun org-table-rewrite-old-row-references (s)
2532 (if (string-match "&[-+0-9I]" s)
2533 (error "Formula contains old &row reference, please rewrite using @-syntax")
2536 (defun org-table-make-reference (elements keep-empty numbers lispp)
2537 "Convert list ELEMENTS to something appropriate to insert into formula.
2538 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2539 NUMBERS indicates that everything should be converted to numbers.
2540 LISPP means to return something appropriate for a Lisp list."
2541 (if (stringp elements) ; just a single val
2542 (if lispp
2543 (if (eq lispp 'literal)
2544 elements
2545 (prin1-to-string (if numbers (string-to-number elements) elements)))
2546 (if (equal elements "") (setq elements "0"))
2547 (if numbers (setq elements (number-to-string (string-to-number elements))))
2548 (concat "(" elements ")"))
2549 (unless keep-empty
2550 (setq elements
2551 (delq nil
2552 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
2553 elements))))
2554 (setq elements (or elements '("0")))
2555 (if lispp
2556 (mapconcat
2557 (lambda (x)
2558 (if (eq lispp 'literal)
2560 (prin1-to-string (if numbers (string-to-number x) x))))
2561 elements " ")
2562 (concat "[" (mapconcat
2563 (lambda (x)
2564 (if numbers (number-to-string (string-to-number x)) x))
2565 elements
2566 ",") "]"))))
2568 (defun org-table-recalculate (&optional all noalign)
2569 "Recalculate the current table line by applying all stored formulas.
2570 With prefix arg ALL, do this for all lines in the table.
2571 With the prefix argument ALL is `(16)' (a double `C-c C-u' prefix), or if
2572 it is the symbol `iterate', recompute the table until it no longer changes.
2573 If NOALIGN is not nil, do not re-align the table after the computations
2574 are done. This is typically used internally to save time, if it is
2575 known that the table will be realigned a little later anyway."
2576 (interactive "P")
2577 (or (memq this-command org-recalc-commands)
2578 (setq org-recalc-commands (cons this-command org-recalc-commands)))
2579 (unless (org-at-table-p) (error "Not at a table"))
2580 (if (or (eq all 'iterate) (equal all '(16)))
2581 (org-table-iterate)
2582 (org-table-get-specials)
2583 (let* ((eqlist (sort (org-table-get-stored-formulas)
2584 (lambda (a b) (string< (car a) (car b)))))
2585 (inhibit-redisplay (not debug-on-error))
2586 (line-re org-table-dataline-regexp)
2587 (thisline (org-current-line))
2588 (thiscol (org-table-current-column))
2589 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
2590 ;; Insert constants in all formulas
2591 (setq eqlist
2592 (mapcar (lambda (x)
2593 (setcdr x (org-table-formula-substitute-names (cdr x)))
2595 eqlist))
2596 ;; Split the equation list
2597 (while (setq eq (pop eqlist))
2598 (if (<= (string-to-char (car eq)) ?9)
2599 (push eq eqlnum)
2600 (push eq eqlname)))
2601 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
2602 (if all
2603 (progn
2604 (setq end (move-marker (make-marker) (1+ (org-table-end))))
2605 (goto-char (setq beg (org-table-begin)))
2606 (if (re-search-forward org-table-calculate-mark-regexp end t)
2607 ;; This is a table with marked lines, compute selected lines
2608 (setq line-re org-table-recalculate-regexp)
2609 ;; Move forward to the first non-header line
2610 (if (and (re-search-forward org-table-dataline-regexp end t)
2611 (re-search-forward org-table-hline-regexp end t)
2612 (re-search-forward org-table-dataline-regexp end t))
2613 (setq beg (match-beginning 0))
2614 nil))) ;; just leave beg where it is
2615 (setq beg (point-at-bol)
2616 end (move-marker (make-marker) (1+ (point-at-eol)))))
2617 (goto-char beg)
2618 (and all (message "Re-applying formulas to full table..."))
2620 ;; First find the named fields, and mark them untouchable
2621 (remove-text-properties beg end '(org-untouchable t))
2622 (while (setq eq (pop eqlname))
2623 (setq name (car eq)
2624 a (assoc name org-table-named-field-locations))
2625 (and (not a)
2626 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
2627 (setq a (list name
2628 (condition-case nil
2629 (aref org-table-dlines
2630 (string-to-number (match-string 1 name)))
2631 (error (error "Invalid row number in %s"
2632 name)))
2633 (string-to-number (match-string 2 name)))))
2634 (when (and a (or all (equal (nth 1 a) thisline)))
2635 (message "Re-applying formula to field: %s" name)
2636 (org-goto-line (nth 1 a))
2637 (org-table-goto-column (nth 2 a))
2638 (push (append a (list (cdr eq))) eqlname1)
2639 (org-table-put-field-property :org-untouchable t)))
2641 ;; Now evaluate the column formulas, but skip fields covered by
2642 ;; field formulas
2643 (goto-char beg)
2644 (while (re-search-forward line-re end t)
2645 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2646 ;; Unprotected line, recalculate
2647 (and all (message "Re-applying formulas to full table...(line %d)"
2648 (setq cnt (1+ cnt))))
2649 (setq org-last-recalc-line (org-current-line))
2650 (setq eql eqlnum)
2651 (while (setq entry (pop eql))
2652 (org-goto-line org-last-recalc-line)
2653 (org-table-goto-column (string-to-number (car entry)) nil 'force)
2654 (unless (get-text-property (point) :org-untouchable)
2655 (org-table-eval-formula nil (cdr entry)
2656 'noalign 'nocst 'nostore 'noanalysis)))))
2658 ;; Now evaluate the field formulas
2659 (while (setq eq (pop eqlname1))
2660 (message "Re-applying formula to field: %s" (car eq))
2661 (org-goto-line (nth 1 eq))
2662 (org-table-goto-column (nth 2 eq))
2663 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
2664 'nostore 'noanalysis))
2666 (org-goto-line thisline)
2667 (org-table-goto-column thiscol)
2668 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
2669 (or noalign (and org-table-may-need-update (org-table-align))
2670 (and all (message "Re-applying formulas to %d lines...done" cnt)))
2672 ;; back to initial position
2673 (message "Re-applying formulas...done")
2674 (org-goto-line thisline)
2675 (org-table-goto-column thiscol)
2676 (or noalign (and org-table-may-need-update (org-table-align))
2677 (and all (message "Re-applying formulas...done"))))))
2679 (defun org-table-iterate (&optional arg)
2680 "Recalculate the table until it does not change anymore."
2681 (interactive "P")
2682 (let ((imax (if arg (prefix-numeric-value arg) 10))
2683 (i 0)
2684 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2685 thistbl)
2686 (catch 'exit
2687 (while (< i imax)
2688 (setq i (1+ i))
2689 (org-table-recalculate 'all)
2690 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
2691 (if (not (string= lasttbl thistbl))
2692 (setq lasttbl thistbl)
2693 (if (> i 1)
2694 (message "Convergence after %d iterations" i)
2695 (message "Table was already stable"))
2696 (throw 'exit t)))
2697 (error "No convergence after %d iterations" i))))
2699 (defun org-table-recalculate-buffer-tables ()
2700 "Recalculate all tables in the current buffer."
2701 (interactive)
2702 (save-excursion
2703 (save-restriction
2704 (widen)
2705 (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
2707 (defun org-table-iterate-buffer-tables ()
2708 "Iterate all tables in the buffer, to converge inter-table dependencies."
2709 (interactive)
2710 (let* ((imax 10)
2711 (checksum (md5 (buffer-string)))
2714 (i imax))
2715 (save-excursion
2716 (save-restriction
2717 (widen)
2718 (catch 'exit
2719 (while (> i 0)
2720 (setq i (1- i))
2721 (org-table-map-tables (lambda () (org-table-recalculate t)) t)
2722 (if (equal checksum (setq c1 (md5 (buffer-string))))
2723 (progn
2724 (message "Convergence after %d iterations" (- imax i))
2725 (throw 'exit t))
2726 (setq checksum c1)))
2727 (error "No convergence after %d iterations" imax))))))
2729 (defun org-table-formula-substitute-names (f)
2730 "Replace $const with values in string F."
2731 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
2732 ;; First, check for column names
2733 (while (setq start (string-match org-table-column-name-regexp f start))
2734 (setq start (1+ start))
2735 (setq a (assoc (match-string 1 f) org-table-column-names))
2736 (setq f (replace-match (concat "$" (cdr a)) t t f)))
2737 ;; Parameters and constants
2738 (setq start 0)
2739 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start))
2740 (if (match-end 2)
2741 (setq start (match-end 2))
2742 (setq start (1+ start))
2743 (if (setq a (save-match-data
2744 (org-table-get-constant (match-string 1 f))))
2745 (setq f (replace-match
2746 (concat (if pp "(") a (if pp ")")) t t f)))))
2747 (if org-table-formula-debug
2748 (put-text-property 0 (length f) :orig-formula f1 f))
2751 (defun org-table-get-constant (const)
2752 "Find the value for a parameter or constant in a formula.
2753 Parameters get priority."
2754 (or (cdr (assoc const org-table-local-parameters))
2755 (cdr (assoc const org-table-formula-constants-local))
2756 (cdr (assoc const org-table-formula-constants))
2757 (and (fboundp 'constants-get) (constants-get const))
2758 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
2759 (org-entry-get nil (substring const 5) 'inherit))
2760 "#UNDEFINED_NAME"))
2762 (defvar org-table-fedit-map
2763 (let ((map (make-sparse-keymap)))
2764 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
2765 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
2766 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
2767 (org-defkey map "\C-c'" 'org-table-fedit-finish)
2768 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
2769 (org-defkey map "\C-c?" 'org-table-show-reference)
2770 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
2771 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
2772 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
2773 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
2774 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
2775 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
2776 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
2777 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
2778 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
2779 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
2780 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
2781 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
2782 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
2783 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
2784 map))
2786 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
2787 '("Edit-Formulas"
2788 ["Finish and Install" org-table-fedit-finish t]
2789 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
2790 ["Abort" org-table-fedit-abort t]
2791 "--"
2792 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
2793 ["Complete Lisp Symbol" lisp-complete-symbol t]
2794 "--"
2795 "Shift Reference at Point"
2796 ["Up" org-table-fedit-ref-up t]
2797 ["Down" org-table-fedit-ref-down t]
2798 ["Left" org-table-fedit-ref-left t]
2799 ["Right" org-table-fedit-ref-right t]
2801 "Change Test Row for Column Formulas"
2802 ["Up" org-table-fedit-line-up t]
2803 ["Down" org-table-fedit-line-down t]
2804 "--"
2805 ["Scroll Table Window" org-table-fedit-scroll t]
2806 ["Scroll Table Window down" org-table-fedit-scroll-down t]
2807 ["Show Table Grid" org-table-fedit-toggle-coordinates
2808 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
2809 org-table-overlay-coordinates)]
2810 "--"
2811 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
2812 :style toggle :selected org-table-buffer-is-an]))
2814 (defvar org-pos)
2816 (defun org-table-edit-formulas ()
2817 "Edit the formulas of the current table in a separate buffer."
2818 (interactive)
2819 (when (save-excursion (beginning-of-line 1) (looking-at "[ \t]*#\\+TBLFM"))
2820 (beginning-of-line 0))
2821 (unless (org-at-table-p) (error "Not at a table"))
2822 (org-table-get-specials)
2823 (let ((key (org-table-current-field-formula 'key 'noerror))
2824 (eql (sort (org-table-get-stored-formulas 'noerror)
2825 'org-table-formula-less-p))
2826 (pos (move-marker (make-marker) (point)))
2827 (startline 1)
2828 (wc (current-window-configuration))
2829 (sel-win (selected-window))
2830 (titles '((column . "# Column Formulas\n")
2831 (field . "# Field Formulas\n")
2832 (named . "# Named Field Formulas\n")))
2833 entry s type title)
2834 (org-switch-to-buffer-other-window "*Edit Formulas*")
2835 (erase-buffer)
2836 ;; Keep global-font-lock-mode from turning on font-lock-mode
2837 (let ((font-lock-global-modes '(not fundamental-mode)))
2838 (fundamental-mode))
2839 (org-set-local 'font-lock-global-modes (list 'not major-mode))
2840 (org-set-local 'org-pos pos)
2841 (org-set-local 'org-window-configuration wc)
2842 (org-set-local 'org-selected-window sel-win)
2843 (use-local-map org-table-fedit-map)
2844 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
2845 (easy-menu-add org-table-fedit-menu)
2846 (setq startline (org-current-line))
2847 (while (setq entry (pop eql))
2848 (setq type (cond
2849 ((equal (string-to-char (car entry)) ?@) 'field)
2850 ((string-match "^[0-9]" (car entry)) 'column)
2851 (t 'named)))
2852 (when (setq title (assq type titles))
2853 (or (bobp) (insert "\n"))
2854 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
2855 (setq titles (delq title titles)))
2856 (if (equal key (car entry)) (setq startline (org-current-line)))
2857 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
2858 (car entry) " = " (cdr entry) "\n"))
2859 (remove-text-properties 0 (length s) '(face nil) s)
2860 (insert s))
2861 (if (eq org-table-use-standard-references t)
2862 (org-table-fedit-toggle-ref-type))
2863 (org-goto-line startline)
2864 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
2866 (defun org-table-fedit-post-command ()
2867 (when (not (memq this-command '(lisp-complete-symbol)))
2868 (let ((win (selected-window)))
2869 (save-excursion
2870 (condition-case nil
2871 (org-table-show-reference)
2872 (error nil))
2873 (select-window win)))))
2875 (defun org-table-formula-to-user (s)
2876 "Convert a formula from internal to user representation."
2877 (if (eq org-table-use-standard-references t)
2878 (org-table-convert-refs-to-an s)
2881 (defun org-table-formula-from-user (s)
2882 "Convert a formula from user to internal representation."
2883 (if org-table-use-standard-references
2884 (org-table-convert-refs-to-rc s)
2887 (defun org-table-convert-refs-to-rc (s)
2888 "Convert spreadsheet references from AB7 to @7$28.
2889 Works for single references, but also for entire formulas and even the
2890 full TBLFM line."
2891 (let ((start 0))
2892 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^)]*)\\)" s start)
2893 (cond
2894 ((match-end 3)
2895 ;; format match, just advance
2896 (setq start (match-end 0)))
2897 ((and (> (match-beginning 0) 0)
2898 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
2899 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
2900 ;; 3.e5 or something like this.
2901 (setq start (match-end 0)))
2902 ((or (> (- (match-end 1) (match-beginning 1)) 2)
2903 ;; (member (match-string 1 s)
2904 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
2906 ;; function name, just advance
2907 (setq start (match-end 0)))
2909 (setq start (match-beginning 0)
2910 s (replace-match
2911 (if (equal (match-string 2 s) "&")
2912 (format "$%d" (org-letters-to-number (match-string 1 s)))
2913 (format "@%d$%d"
2914 (string-to-number (match-string 2 s))
2915 (org-letters-to-number (match-string 1 s))))
2916 t t s)))))
2919 (defun org-table-convert-refs-to-an (s)
2920 "Convert spreadsheet references from to @7$28 to AB7.
2921 Works for single references, but also for entire formulas and even the
2922 full TBLFM line."
2923 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
2924 (setq s (replace-match
2925 (format "%s%d"
2926 (org-number-to-letters
2927 (string-to-number (match-string 2 s)))
2928 (string-to-number (match-string 1 s)))
2929 t t s)))
2930 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
2931 (setq s (replace-match (concat "\\1"
2932 (org-number-to-letters
2933 (string-to-number (match-string 2 s))) "&")
2934 t nil s)))
2937 (defun org-letters-to-number (s)
2938 "Convert a base 26 number represented by letters into an integer.
2939 For example: AB -> 28."
2940 (let ((n 0))
2941 (setq s (upcase s))
2942 (while (> (length s) 0)
2943 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
2944 s (substring s 1)))
2947 (defun org-number-to-letters (n)
2948 "Convert an integer into a base 26 number represented by letters.
2949 For example: 28 -> AB."
2950 (let ((s ""))
2951 (while (> n 0)
2952 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
2953 n (/ (1- n) 26)))
2956 (defun org-table-fedit-convert-buffer (function)
2957 "Convert all references in this buffer, using FUNCTION."
2958 (let ((line (org-current-line)))
2959 (goto-char (point-min))
2960 (while (not (eobp))
2961 (insert (funcall function (buffer-substring (point) (point-at-eol))))
2962 (delete-region (point) (point-at-eol))
2963 (or (eobp) (forward-char 1)))
2964 (org-goto-line line)))
2966 (defun org-table-fedit-toggle-ref-type ()
2967 "Convert all references in the buffer from B3 to @3$2 and back."
2968 (interactive)
2969 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
2970 (org-table-fedit-convert-buffer
2971 (if org-table-buffer-is-an
2972 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
2973 (message "Reference type switched to %s"
2974 (if org-table-buffer-is-an "A1 etc" "@row$column")))
2976 (defun org-table-fedit-ref-up ()
2977 "Shift the reference at point one row/hline up."
2978 (interactive)
2979 (org-table-fedit-shift-reference 'up))
2980 (defun org-table-fedit-ref-down ()
2981 "Shift the reference at point one row/hline down."
2982 (interactive)
2983 (org-table-fedit-shift-reference 'down))
2984 (defun org-table-fedit-ref-left ()
2985 "Shift the reference at point one field to the left."
2986 (interactive)
2987 (org-table-fedit-shift-reference 'left))
2988 (defun org-table-fedit-ref-right ()
2989 "Shift the reference at point one field to the right."
2990 (interactive)
2991 (org-table-fedit-shift-reference 'right))
2993 (defun org-table-fedit-shift-reference (dir)
2994 (cond
2995 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
2996 (if (memq dir '(left right))
2997 (org-rematch-and-replace 1 (eq dir 'left))
2998 (error "Cannot shift reference in this direction")))
2999 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3000 ;; A B3-like reference
3001 (if (memq dir '(up down))
3002 (org-rematch-and-replace 2 (eq dir 'up))
3003 (org-rematch-and-replace 1 (eq dir 'left))))
3004 ((org-at-regexp-p
3005 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3006 ;; An internal reference
3007 (if (memq dir '(up down))
3008 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3009 (org-rematch-and-replace 5 (eq dir 'left))))))
3011 (defun org-rematch-and-replace (n &optional decr hline)
3012 "Re-match the group N, and replace it with the shifted refrence."
3013 (or (match-end n) (error "Cannot shift reference in this direction"))
3014 (goto-char (match-beginning n))
3015 (and (looking-at (regexp-quote (match-string n)))
3016 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3017 t t)))
3019 (defun org-table-shift-refpart (ref &optional decr hline)
3020 "Shift a refrence part REF.
3021 If DECR is set, decrease the references row/column, else increase.
3022 If HLINE is set, this may be a hline reference, it certainly is not
3023 a translation reference."
3024 (save-match-data
3025 (let* ((sign (string-match "^[-+]" ref)) n)
3027 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3028 (cond
3029 ((and hline (string-match "^I+" ref))
3030 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3031 (setq n (+ n (if decr -1 1)))
3032 (if (= n 0) (setq n (+ n (if decr -1 1))))
3033 (if sign
3034 (setq sign (if (< n 0) "-" "+") n (abs n))
3035 (setq n (max 1 n)))
3036 (concat sign (make-string n ?I)))
3038 ((string-match "^[0-9]+" ref)
3039 (setq n (string-to-number (concat sign ref)))
3040 (setq n (+ n (if decr -1 1)))
3041 (if sign
3042 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3043 (number-to-string (max 1 n))))
3045 ((string-match "^[a-zA-Z]+" ref)
3046 (org-number-to-letters
3047 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3049 (t (error "Cannot shift reference"))))))
3051 (defun org-table-fedit-toggle-coordinates ()
3052 "Toggle the display of coordinates in the referenced table."
3053 (interactive)
3054 (let ((pos (marker-position org-pos)))
3055 (with-current-buffer (marker-buffer org-pos)
3056 (save-excursion
3057 (goto-char pos)
3058 (org-table-toggle-coordinate-overlays)))))
3060 (defun org-table-fedit-finish (&optional arg)
3061 "Parse the buffer for formula definitions and install them.
3062 With prefix ARG, apply the new formulas to the table."
3063 (interactive "P")
3064 (org-table-remove-rectangle-highlight)
3065 (if org-table-use-standard-references
3066 (progn
3067 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3068 (setq org-table-buffer-is-an nil)))
3069 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3070 (goto-char (point-min))
3071 (while (re-search-forward
3072 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3073 nil t)
3074 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3075 form (match-string 3))
3076 (setq form (org-trim form))
3077 (when (not (equal form ""))
3078 (while (string-match "[ \t]*\n[ \t]*" form)
3079 (setq form (replace-match " " t t form)))
3080 (when (assoc var eql)
3081 (error "Double formulas for %s" var))
3082 (push (cons var form) eql)))
3083 (setq org-pos nil)
3084 (set-window-configuration org-window-configuration)
3085 (select-window sel-win)
3086 (goto-char pos)
3087 (unless (org-at-table-p)
3088 (error "Lost table position - cannot install formulae"))
3089 (org-table-store-formulas eql)
3090 (move-marker pos nil)
3091 (kill-buffer "*Edit Formulas*")
3092 (if arg
3093 (org-table-recalculate 'all)
3094 (message "New formulas installed - press C-u C-c C-c to apply."))))
3096 (defun org-table-fedit-abort ()
3097 "Abort editing formulas, without installing the changes."
3098 (interactive)
3099 (org-table-remove-rectangle-highlight)
3100 (let ((pos org-pos) (sel-win org-selected-window))
3101 (set-window-configuration org-window-configuration)
3102 (select-window sel-win)
3103 (goto-char pos)
3104 (move-marker pos nil)
3105 (message "Formula editing aborted without installing changes")))
3107 (defun org-table-fedit-lisp-indent ()
3108 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3109 (interactive)
3110 (let ((pos (point)) beg end ind)
3111 (beginning-of-line 1)
3112 (cond
3113 ((looking-at "[ \t]")
3114 (goto-char pos)
3115 (call-interactively 'lisp-indent-line))
3116 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3117 ((not (fboundp 'pp-buffer))
3118 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3119 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3120 (goto-char (- (match-end 0) 2))
3121 (setq beg (point))
3122 (setq ind (make-string (current-column) ?\ ))
3123 (condition-case nil (forward-sexp 1)
3124 (error
3125 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3126 (setq end (point))
3127 (save-restriction
3128 (narrow-to-region beg end)
3129 (if (eq last-command this-command)
3130 (progn
3131 (goto-char (point-min))
3132 (setq this-command nil)
3133 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3134 (replace-match " ")))
3135 (pp-buffer)
3136 (untabify (point-min) (point-max))
3137 (goto-char (1+ (point-min)))
3138 (while (re-search-forward "^." nil t)
3139 (beginning-of-line 1)
3140 (insert ind))
3141 (goto-char (point-max))
3142 (backward-delete-char 1)))
3143 (goto-char beg))
3144 (t nil))))
3146 (defvar org-show-positions nil)
3148 (defun org-table-show-reference (&optional local)
3149 "Show the location/value of the $ expression at point."
3150 (interactive)
3151 (org-table-remove-rectangle-highlight)
3152 (catch 'exit
3153 (let ((pos (if local (point) org-pos))
3154 (face2 'highlight)
3155 (org-inhibit-highlight-removal t)
3156 (win (selected-window))
3157 (org-show-positions nil)
3158 var name e what match dest)
3159 (if local (org-table-get-specials))
3160 (setq what (cond
3161 ((or (org-at-regexp-p org-table-range-regexp2)
3162 (org-at-regexp-p org-table-translate-regexp)
3163 (org-at-regexp-p org-table-range-regexp))
3164 (setq match
3165 (save-match-data
3166 (org-table-convert-refs-to-rc (match-string 0))))
3167 'range)
3168 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3169 ((org-at-regexp-p "\\$[0-9]+") 'column)
3170 ((not local) nil)
3171 (t (error "No reference at point")))
3172 match (and what (or match (match-string 0))))
3173 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3174 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3175 'secondary-selection))
3176 (org-add-hook 'before-change-functions
3177 'org-table-remove-rectangle-highlight)
3178 (if (eq what 'name) (setq var (substring match 1)))
3179 (when (eq what 'range)
3180 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
3181 (setq match (org-table-formula-substitute-names match)))
3182 (unless local
3183 (save-excursion
3184 (end-of-line 1)
3185 (re-search-backward "^\\S-" nil t)
3186 (beginning-of-line 1)
3187 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3188 (setq dest
3189 (save-match-data
3190 (org-table-convert-refs-to-rc (match-string 1))))
3191 (org-table-add-rectangle-overlay
3192 (match-beginning 1) (match-end 1) face2))))
3193 (if (and (markerp pos) (marker-buffer pos))
3194 (if (get-buffer-window (marker-buffer pos))
3195 (select-window (get-buffer-window (marker-buffer pos)))
3196 (org-switch-to-buffer-other-window (get-buffer-window
3197 (marker-buffer pos)))))
3198 (goto-char pos)
3199 (org-table-force-dataline)
3200 (when dest
3201 (setq name (substring dest 1))
3202 (cond
3203 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3204 (setq e (assoc name org-table-named-field-locations))
3205 (org-goto-line (nth 1 e))
3206 (org-table-goto-column (nth 2 e)))
3207 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
3208 (let ((l (string-to-number (match-string 1 dest)))
3209 (c (string-to-number (match-string 2 dest))))
3210 (org-goto-line (aref org-table-dlines l))
3211 (org-table-goto-column c)))
3212 (t (org-table-goto-column (string-to-number name))))
3213 (move-marker pos (point))
3214 (org-table-highlight-rectangle nil nil face2))
3215 (cond
3216 ((equal dest match))
3217 ((not match))
3218 ((eq what 'range)
3219 (condition-case nil
3220 (save-excursion
3221 (org-table-get-range match nil nil 'highlight))
3222 (error nil)))
3223 ((setq e (assoc var org-table-named-field-locations))
3224 (org-goto-line (nth 1 e))
3225 (org-table-goto-column (nth 2 e))
3226 (org-table-highlight-rectangle (point) (point))
3227 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3228 ((setq e (assoc var org-table-column-names))
3229 (org-table-goto-column (string-to-number (cdr e)))
3230 (org-table-highlight-rectangle (point) (point))
3231 (goto-char (org-table-begin))
3232 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3233 (org-table-end) t)
3234 (progn
3235 (goto-char (match-beginning 1))
3236 (org-table-highlight-rectangle)
3237 (message "Named column (column %s)" (cdr e)))
3238 (error "Column name not found")))
3239 ((eq what 'column)
3240 ;; column number
3241 (org-table-goto-column (string-to-number (substring match 1)))
3242 (org-table-highlight-rectangle (point) (point))
3243 (message "Column %s" (substring match 1)))
3244 ((setq e (assoc var org-table-local-parameters))
3245 (goto-char (org-table-begin))
3246 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3247 (progn
3248 (goto-char (match-beginning 1))
3249 (org-table-highlight-rectangle)
3250 (message "Local parameter."))
3251 (error "Parameter not found")))
3253 (cond
3254 ((not var) (error "No reference at point"))
3255 ((setq e (assoc var org-table-formula-constants-local))
3256 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3257 var (cdr e)))
3258 ((setq e (assoc var org-table-formula-constants))
3259 (message "Constant: $%s=%s in `org-table-formula-constants'."
3260 var (cdr e)))
3261 ((setq e (and (fboundp 'constants-get) (constants-get var)))
3262 (message "Constant: $%s=%s, from `constants.el'%s."
3263 var e (format " (%s units)" constants-unit-system)))
3264 (t (error "Undefined name $%s" var)))))
3265 (goto-char pos)
3266 (when (and org-show-positions
3267 (not (memq this-command '(org-table-fedit-scroll
3268 org-table-fedit-scroll-down))))
3269 (push pos org-show-positions)
3270 (push org-table-current-begin-pos org-show-positions)
3271 (let ((min (apply 'min org-show-positions))
3272 (max (apply 'max org-show-positions)))
3273 (goto-char min) (recenter 0)
3274 (goto-char max)
3275 (or (pos-visible-in-window-p max) (recenter -1))))
3276 (select-window win))))
3278 (defun org-table-force-dataline ()
3279 "Make sure the cursor is in a dataline in a table."
3280 (unless (save-excursion
3281 (beginning-of-line 1)
3282 (looking-at org-table-dataline-regexp))
3283 (let* ((re org-table-dataline-regexp)
3284 (p1 (save-excursion (re-search-forward re nil 'move)))
3285 (p2 (save-excursion (re-search-backward re nil 'move))))
3286 (cond ((and p1 p2)
3287 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
3288 p1 p2)))
3289 ((or p1 p2) (goto-char (or p1 p2)))
3290 (t (error "No table dataline around here"))))))
3292 (defun org-table-fedit-line-up ()
3293 "Move cursor one line up in the window showing the table."
3294 (interactive)
3295 (org-table-fedit-move 'previous-line))
3297 (defun org-table-fedit-line-down ()
3298 "Move cursor one line down in the window showing the table."
3299 (interactive)
3300 (org-table-fedit-move 'next-line))
3302 (defun org-table-fedit-move (command)
3303 "Move the cursor in the window showing the table.
3304 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3305 (let ((org-table-allow-automatic-line-recalculation nil)
3306 (pos org-pos) (win (selected-window)) p)
3307 (select-window (get-buffer-window (marker-buffer org-pos)))
3308 (setq p (point))
3309 (call-interactively command)
3310 (while (and (org-at-table-p)
3311 (org-at-table-hline-p))
3312 (call-interactively command))
3313 (or (org-at-table-p) (goto-char p))
3314 (move-marker pos (point))
3315 (select-window win)))
3317 (defun org-table-fedit-scroll (N)
3318 (interactive "p")
3319 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
3320 (scroll-other-window N)))
3322 (defun org-table-fedit-scroll-down (N)
3323 (interactive "p")
3324 (org-table-fedit-scroll (- N)))
3326 (defvar org-table-rectangle-overlays nil)
3328 (defun org-table-add-rectangle-overlay (beg end &optional face)
3329 "Add a new overlay."
3330 (let ((ov (make-overlay beg end)))
3331 (overlay-put ov 'face (or face 'secondary-selection))
3332 (push ov org-table-rectangle-overlays)))
3334 (defun org-table-highlight-rectangle (&optional beg end face)
3335 "Highlight rectangular region in a table."
3336 (setq beg (or beg (point)) end (or end (point)))
3337 (let ((b (min beg end))
3338 (e (max beg end))
3339 l1 c1 l2 c2 tmp)
3340 (and (boundp 'org-show-positions)
3341 (setq org-show-positions (cons b (cons e org-show-positions))))
3342 (goto-char (min beg end))
3343 (setq l1 (org-current-line)
3344 c1 (org-table-current-column))
3345 (goto-char (max beg end))
3346 (setq l2 (org-current-line)
3347 c2 (org-table-current-column))
3348 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
3349 (org-goto-line l1)
3350 (beginning-of-line 1)
3351 (loop for line from l1 to l2 do
3352 (when (looking-at org-table-dataline-regexp)
3353 (org-table-goto-column c1)
3354 (skip-chars-backward "^|\n") (setq beg (point))
3355 (org-table-goto-column c2)
3356 (skip-chars-forward "^|\n") (setq end (point))
3357 (org-table-add-rectangle-overlay beg end face))
3358 (beginning-of-line 2))
3359 (goto-char b))
3360 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
3362 (defun org-table-remove-rectangle-highlight (&rest ignore)
3363 "Remove the rectangle overlays."
3364 (unless org-inhibit-highlight-removal
3365 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
3366 (mapc 'delete-overlay org-table-rectangle-overlays)
3367 (setq org-table-rectangle-overlays nil)))
3369 (defvar org-table-coordinate-overlays nil
3370 "Collects the coordinate grid overlays, so that they can be removed.")
3371 (make-variable-buffer-local 'org-table-coordinate-overlays)
3373 (defun org-table-overlay-coordinates ()
3374 "Add overlays to the table at point, to show row/column coordinates."
3375 (interactive)
3376 (mapc 'delete-overlay org-table-coordinate-overlays)
3377 (setq org-table-coordinate-overlays nil)
3378 (save-excursion
3379 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
3380 (goto-char (org-table-begin))
3381 (while (org-at-table-p)
3382 (setq eol (point-at-eol))
3383 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
3384 (push ov org-table-coordinate-overlays)
3385 (setq hline (looking-at org-table-hline-regexp))
3386 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
3387 (format "%4d" (setq id (1+ id)))))
3388 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
3389 (when hline
3390 (setq ic 0)
3391 (while (re-search-forward "[+|]\\(-+\\)" eol t)
3392 (setq beg (1+ (match-beginning 0))
3393 ic (1+ ic)
3394 s1 (concat "$" (int-to-string ic))
3395 s2 (org-number-to-letters ic)
3396 str (if (eq org-table-use-standard-references t) s2 s1))
3397 (setq ov (make-overlay beg (+ beg (length str))))
3398 (push ov org-table-coordinate-overlays)
3399 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
3400 (beginning-of-line 2)))))
3402 (defun org-table-toggle-coordinate-overlays ()
3403 "Toggle the display of Row/Column numbers in tables."
3404 (interactive)
3405 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
3406 (message "Row/Column number display turned %s"
3407 (if org-table-overlay-coordinates "on" "off"))
3408 (if (and (org-at-table-p) org-table-overlay-coordinates)
3409 (org-table-align))
3410 (unless org-table-overlay-coordinates
3411 (mapc 'delete-overlay org-table-coordinate-overlays)
3412 (setq org-table-coordinate-overlays nil)))
3414 (defun org-table-toggle-formula-debugger ()
3415 "Toggle the formula debugger in tables."
3416 (interactive)
3417 (setq org-table-formula-debug (not org-table-formula-debug))
3418 (message "Formula debugging has been turned %s"
3419 (if org-table-formula-debug "on" "off")))
3421 ;;; The orgtbl minor mode
3423 ;; Define a minor mode which can be used in other modes in order to
3424 ;; integrate the org-mode table editor.
3426 ;; This is really a hack, because the org-mode table editor uses several
3427 ;; keys which normally belong to the major mode, for example the TAB and
3428 ;; RET keys. Here is how it works: The minor mode defines all the keys
3429 ;; necessary to operate the table editor, but wraps the commands into a
3430 ;; function which tests if the cursor is currently inside a table. If that
3431 ;; is the case, the table editor command is executed. However, when any of
3432 ;; those keys is used outside a table, the function uses `key-binding' to
3433 ;; look up if the key has an associated command in another currently active
3434 ;; keymap (minor modes, major mode, global), and executes that command.
3435 ;; There might be problems if any of the keys used by the table editor is
3436 ;; otherwise used as a prefix key.
3438 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3439 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3440 ;; addresses this by checking explicitly for both bindings.
3442 ;; The optimized version (see variable `orgtbl-optimized') takes over
3443 ;; all keys which are bound to `self-insert-command' in the *global map*.
3444 ;; Some modes bind other commands to simple characters, for example
3445 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3446 ;; active, this binding is ignored inside tables and replaced with a
3447 ;; modified self-insert.
3450 (defvar orgtbl-mode-map (make-keymap)
3451 "Keymap for `orgtbl-mode'.")
3453 ;;;###autoload
3454 (defun turn-on-orgtbl ()
3455 "Unconditionally turn on `orgtbl-mode'."
3456 (orgtbl-mode 1))
3458 (defvar org-old-auto-fill-inhibit-regexp nil
3459 "Local variable used by `orgtbl-mode'")
3461 (defconst orgtbl-line-start-regexp
3462 "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\|TBLNAME\\):\\)"
3463 "Matches a line belonging to an orgtbl.")
3465 (defconst orgtbl-extra-font-lock-keywords
3466 (list (list (concat "^" orgtbl-line-start-regexp ".*")
3467 0 (quote 'org-table) 'prepend))
3468 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
3470 ;; Install it as a minor mode.
3471 (put 'orgtbl-mode :included t)
3472 (put 'orgtbl-mode :menu-tag "Org Table Mode")
3474 ;;;###autoload
3475 (define-minor-mode orgtbl-mode
3476 "The `org-mode' table editor as a minor mode for use in other modes."
3477 :lighter " OrgTbl" :keymap orgtbl-mode-map
3478 (org-load-modules-maybe)
3479 (cond
3480 ((org-mode-p)
3481 ;; Exit without error, in case some hook functions calls this
3482 ;; by accident in org-mode.
3483 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
3484 (orgtbl-mode
3485 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
3486 ;; Make sure we are first in minor-mode-map-alist
3487 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
3488 ;; FIXME: maybe it should use emulation-mode-map-alists?
3489 (and c (setq minor-mode-map-alist
3490 (cons c (delq c minor-mode-map-alist)))))
3491 (org-set-local (quote org-table-may-need-update) t)
3492 (org-add-hook 'before-change-functions 'org-before-change-function
3493 nil 'local)
3494 (org-set-local 'org-old-auto-fill-inhibit-regexp
3495 auto-fill-inhibit-regexp)
3496 (org-set-local 'auto-fill-inhibit-regexp
3497 (if auto-fill-inhibit-regexp
3498 (concat orgtbl-line-start-regexp "\\|"
3499 auto-fill-inhibit-regexp)
3500 orgtbl-line-start-regexp))
3501 (add-to-invisibility-spec '(org-cwidth))
3502 (when (fboundp 'font-lock-add-keywords)
3503 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
3504 (org-restart-font-lock))
3505 (easy-menu-add orgtbl-mode-menu))
3507 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
3508 (org-table-cleanup-narrow-column-properties)
3509 (org-remove-from-invisibility-spec '(org-cwidth))
3510 (remove-hook 'before-change-functions 'org-before-change-function t)
3511 (when (fboundp 'font-lock-remove-keywords)
3512 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
3513 (org-restart-font-lock))
3514 (easy-menu-remove orgtbl-mode-menu)
3515 (force-mode-line-update 'all))))
3517 (defun org-table-cleanup-narrow-column-properties ()
3518 "Remove all properties related to narrow-column invisibility."
3519 (let ((s 1))
3520 (while (setq s (text-property-any s (point-max)
3521 'display org-narrow-column-arrow))
3522 (remove-text-properties s (1+ s) '(display t)))
3523 (setq s 1)
3524 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
3525 (remove-text-properties s (1+ s) '(org-cwidth t)))
3526 (setq s 1)
3527 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
3528 (remove-text-properties s (1+ s) '(invisible t)))))
3530 (defun orgtbl-make-binding (fun n &rest keys)
3531 "Create a function for binding in the table minor mode.
3532 FUN is the command to call inside a table. N is used to create a unique
3533 command name. KEYS are keys that should be checked in for a command
3534 to execute outside of tables."
3535 (eval
3536 (list 'defun
3537 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
3538 '(arg)
3539 (concat "In tables, run `" (symbol-name fun) "'.\n"
3540 "Outside of tables, run the binding of `"
3541 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
3542 "'.")
3543 '(interactive "p")
3544 (list 'if
3545 '(org-at-table-p)
3546 (list 'call-interactively (list 'quote fun))
3547 (list 'let '(orgtbl-mode)
3548 (list 'call-interactively
3549 (append '(or)
3550 (mapcar (lambda (k)
3551 (list 'key-binding k))
3552 keys)
3553 '('orgtbl-error))))))))
3555 (defun orgtbl-error ()
3556 "Error when there is no default binding for a table key."
3557 (interactive)
3558 (error "This key has no function outside tables"))
3560 (defun orgtbl-setup ()
3561 "Setup orgtbl keymaps."
3562 (let ((nfunc 0)
3563 (bindings
3564 '(([(meta shift left)] org-table-delete-column)
3565 ([(meta left)] org-table-move-column-left)
3566 ([(meta right)] org-table-move-column-right)
3567 ([(meta shift right)] org-table-insert-column)
3568 ([(meta shift up)] org-table-kill-row)
3569 ([(meta shift down)] org-table-insert-row)
3570 ([(meta up)] org-table-move-row-up)
3571 ([(meta down)] org-table-move-row-down)
3572 ("\C-c\C-w" org-table-cut-region)
3573 ("\C-c\M-w" org-table-copy-region)
3574 ("\C-c\C-y" org-table-paste-rectangle)
3575 ("\C-c-" org-table-insert-hline)
3576 ("\C-c}" org-table-toggle-coordinate-overlays)
3577 ("\C-c{" org-table-toggle-formula-debugger)
3578 ("\C-m" org-table-next-row)
3579 ([(shift return)] org-table-copy-down)
3580 ("\C-c?" org-table-field-info)
3581 ("\C-c " org-table-blank-field)
3582 ("\C-c+" org-table-sum)
3583 ("\C-c=" org-table-eval-formula)
3584 ("\C-c'" org-table-edit-formulas)
3585 ("\C-c`" org-table-edit-field)
3586 ("\C-c*" org-table-recalculate)
3587 ("\C-c^" org-table-sort-lines)
3588 ("\M-a" org-table-beginning-of-field)
3589 ("\M-e" org-table-end-of-field)
3590 ([(control ?#)] org-table-rotate-recalc-marks)))
3591 elt key fun cmd)
3592 (while (setq elt (pop bindings))
3593 (setq nfunc (1+ nfunc))
3594 (setq key (org-key (car elt))
3595 fun (nth 1 elt)
3596 cmd (orgtbl-make-binding fun nfunc key))
3597 (org-defkey orgtbl-mode-map key cmd))
3599 ;; Special treatment needed for TAB and RET
3600 (org-defkey orgtbl-mode-map [(return)]
3601 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
3602 (org-defkey orgtbl-mode-map "\C-m"
3603 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
3605 (org-defkey orgtbl-mode-map [(tab)]
3606 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
3607 (org-defkey orgtbl-mode-map "\C-i"
3608 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
3610 (org-defkey orgtbl-mode-map [(shift tab)]
3611 (orgtbl-make-binding 'org-table-previous-field 104
3612 [(shift tab)] [(tab)] "\C-i"))
3615 (unless (featurep 'xemacs)
3616 (org-defkey orgtbl-mode-map [S-iso-lefttab]
3617 (orgtbl-make-binding 'org-table-previous-field 107
3618 [S-iso-lefttab] [backtab] [(shift tab)]
3619 [(tab)] "\C-i")))
3621 (org-defkey orgtbl-mode-map [backtab]
3622 (orgtbl-make-binding 'org-table-previous-field 108
3623 [backtab] [S-iso-lefttab] [(shift tab)]
3624 [(tab)] "\C-i"))
3626 (org-defkey orgtbl-mode-map "\M-\C-m"
3627 (orgtbl-make-binding 'org-table-wrap-region 105
3628 "\M-\C-m" [(meta return)]))
3629 (org-defkey orgtbl-mode-map [(meta return)]
3630 (orgtbl-make-binding 'org-table-wrap-region 106
3631 [(meta return)] "\M-\C-m"))
3633 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
3634 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
3636 (when orgtbl-optimized
3637 ;; If the user wants maximum table support, we need to hijack
3638 ;; some standard editing functions
3639 (org-remap orgtbl-mode-map
3640 'self-insert-command 'orgtbl-self-insert-command
3641 'delete-char 'org-delete-char
3642 'delete-backward-char 'org-delete-backward-char)
3643 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
3644 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
3645 '("OrgTbl"
3646 ["Create or convert" org-table-create-or-convert-from-region
3647 :active (not (org-at-table-p)) :keys "C-c |" ]
3648 "--"
3649 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
3650 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
3651 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
3652 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
3653 "--"
3654 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
3655 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
3656 ["Copy Field from Above"
3657 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
3658 "--"
3659 ("Column"
3660 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
3661 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
3662 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
3663 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
3664 ("Row"
3665 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
3666 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
3667 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
3668 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
3669 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
3670 "--"
3671 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
3672 ("Rectangle"
3673 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
3674 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
3675 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
3676 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
3677 "--"
3678 ("Radio tables"
3679 ["Insert table template" orgtbl-insert-radio-table
3680 (assq major-mode orgtbl-radio-table-templates)]
3681 ["Comment/uncomment table" orgtbl-toggle-comment t])
3682 "--"
3683 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
3684 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
3685 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
3686 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
3687 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
3688 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
3689 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
3690 ["Sum Column/Rectangle" org-table-sum
3691 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
3692 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
3693 ["Debug Formulas"
3694 org-table-toggle-formula-debugger :active (org-at-table-p)
3695 :keys "C-c {"
3696 :style toggle :selected org-table-formula-debug]
3697 ["Show Col/Row Numbers"
3698 org-table-toggle-coordinate-overlays :active (org-at-table-p)
3699 :keys "C-c }"
3700 :style toggle :selected org-table-overlay-coordinates]
3704 (defun orgtbl-ctrl-c-ctrl-c (arg)
3705 "If the cursor is inside a table, realign the table.
3706 If it is a table to be sent away to a receiver, do it.
3707 With prefix arg, also recompute table."
3708 (interactive "P")
3709 (let ((pos (point)) action)
3710 (save-excursion
3711 (beginning-of-line 1)
3712 (setq action (cond ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
3713 ((looking-at "[ \t]*|") pos)
3714 ((looking-at "[ \t]*#\\+TBLFM:") 'recalc))))
3715 (cond
3716 ((integerp action)
3717 (goto-char action)
3718 (org-table-maybe-eval-formula)
3719 (if arg
3720 (call-interactively 'org-table-recalculate)
3721 (org-table-maybe-recalculate-line))
3722 (call-interactively 'org-table-align)
3723 (orgtbl-send-table 'maybe))
3724 ((eq action 'recalc)
3725 (save-excursion
3726 (beginning-of-line 1)
3727 (skip-chars-backward " \r\n\t")
3728 (if (org-at-table-p)
3729 (org-call-with-arg 'org-table-recalculate t))))
3730 (t (let (orgtbl-mode)
3731 (call-interactively (key-binding "\C-c\C-c")))))))
3733 (defun orgtbl-create-or-convert-from-region (arg)
3734 "Create table or convert region to table, if no conflicting binding.
3735 This installs the table binding `C-c |', but only if there is no
3736 conflicting binding to this key outside orgtbl-mode."
3737 (interactive "P")
3738 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
3739 (if cmd
3740 (call-interactively cmd)
3741 (call-interactively 'org-table-create-or-convert-from-region))))
3743 (defun orgtbl-tab (arg)
3744 "Justification and field motion for `orgtbl-mode'."
3745 (interactive "P")
3746 (if arg (org-table-edit-field t)
3747 (org-table-justify-field-maybe)
3748 (org-table-next-field)))
3750 (defun orgtbl-ret ()
3751 "Justification and field motion for `orgtbl-mode'."
3752 (interactive)
3753 (if (bobp)
3754 (newline)
3755 (org-table-justify-field-maybe)
3756 (org-table-next-row)))
3758 (defun orgtbl-self-insert-command (N)
3759 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
3760 If the cursor is in a table looking at whitespace, the whitespace is
3761 overwritten, and the table is not marked as requiring realignment."
3762 (interactive "p")
3763 (if (and (org-at-table-p)
3765 (and org-table-auto-blank-field
3766 (member last-command
3767 '(orgtbl-hijacker-command-100
3768 orgtbl-hijacker-command-101
3769 orgtbl-hijacker-command-102
3770 orgtbl-hijacker-command-103
3771 orgtbl-hijacker-command-104
3772 orgtbl-hijacker-command-105
3773 yas/expand))
3774 (org-table-blank-field))
3776 (eq N 1)
3777 (looking-at "[^|\n]* +|"))
3778 (let (org-table-may-need-update)
3779 (goto-char (1- (match-end 0)))
3780 (delete-backward-char 1)
3781 (goto-char (match-beginning 0))
3782 (self-insert-command N))
3783 (setq org-table-may-need-update t)
3784 (let* (orgtbl-mode
3786 (cmd (or (key-binding
3787 (or (and (listp function-key-map)
3788 (setq a (assoc last-input-event function-key-map))
3789 (cdr a))
3790 (vector last-input-event)))
3791 'self-insert-command)))
3792 (call-interactively cmd)
3793 (if (and org-self-insert-cluster-for-undo
3794 (eq cmd 'self-insert-command))
3795 (if (not (eq last-command 'orgtbl-self-insert-command))
3796 (setq org-self-insert-command-undo-counter 1)
3797 (if (>= org-self-insert-command-undo-counter 20)
3798 (setq org-self-insert-command-undo-counter 1)
3799 (and (> org-self-insert-command-undo-counter 0)
3800 buffer-undo-list
3801 (not (cadr buffer-undo-list)) ; remove nil entry
3802 (setcdr buffer-undo-list (cddr buffer-undo-list)))
3803 (setq org-self-insert-command-undo-counter
3804 (1+ org-self-insert-command-undo-counter))))))))
3806 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
3807 "Regular expression matching exponentials as produced by calc.")
3809 (defun orgtbl-export (table target)
3810 (require 'org-exp)
3811 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
3812 (lines (org-split-string table "[ \t]*\n[ \t]*"))
3813 org-table-last-alignment org-table-last-column-widths
3814 maxcol column)
3815 (if (not (fboundp func))
3816 (error "Cannot export orgtbl table to %s" target))
3817 (setq lines (org-table-clean-before-export lines))
3818 (setq table
3819 (mapcar
3820 (lambda (x)
3821 (if (string-match org-table-hline-regexp x)
3822 'hline
3823 (org-split-string (org-trim x) "\\s-*|\\s-*")))
3824 lines))
3825 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
3826 table)))
3827 (loop for i from (1- maxcol) downto 0 do
3828 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
3829 (setq column (delq nil column))
3830 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
3831 (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))
3832 (funcall func table nil)))
3834 (defun orgtbl-gather-send-defs ()
3835 "Gathers a plist of :name, :transform, :params for each destination before
3836 a radio table."
3837 (save-excursion
3838 (goto-char (org-table-begin))
3839 (let (rtn)
3840 (beginning-of-line 0)
3841 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
3842 (let ((name (org-no-properties (match-string 1)))
3843 (transform (intern (match-string 2)))
3844 (params (if (match-end 3)
3845 (read (concat "(" (match-string 3) ")")))))
3846 (push (list :name name :transform transform :params params)
3847 rtn)
3848 (beginning-of-line 0)))
3849 rtn)))
3851 (defun orgtbl-send-replace-tbl (name txt)
3852 "Find and replace table NAME with TXT."
3853 (save-excursion
3854 (goto-char (point-min))
3855 (unless (re-search-forward
3856 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
3857 (error "Don't know where to insert translated table"))
3858 (goto-char (match-beginning 0))
3859 (beginning-of-line 2)
3860 (save-excursion
3861 (let ((beg (point)))
3862 (unless (re-search-forward
3863 (concat "END RECEIVE ORGTBL +" name) nil t)
3864 (error "Cannot find end of insertion region"))
3865 (beginning-of-line 1)
3866 (delete-region beg (point))))
3867 (insert txt "\n")))
3869 ;;;###autoload
3870 (defun org-table-to-lisp (&optional txt)
3871 "Convert the table at point to a Lisp structure.
3872 The structure will be a list. Each item is either the symbol `hline'
3873 for a horizontal separator line, or a list of field values as strings.
3874 The table is taken from the parameter TXT, or from the buffer at point."
3875 (unless txt
3876 (unless (org-at-table-p)
3877 (error "No table at point")))
3878 (let* ((txt (or txt
3879 (buffer-substring-no-properties (org-table-begin)
3880 (org-table-end))))
3881 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
3883 (mapcar
3884 (lambda (x)
3885 (if (string-match org-table-hline-regexp x)
3886 'hline
3887 (org-split-string (org-trim x) "\\s-*|\\s-*")))
3888 lines)))
3890 (defun orgtbl-send-table (&optional maybe)
3891 "Send a transformed version of this table to the receiver position.
3892 With argument MAYBE, fail quietly if no transformation is defined for
3893 this table."
3894 (interactive)
3895 (catch 'exit
3896 (unless (org-at-table-p) (error "Not at a table"))
3897 ;; when non-interactive, we assume align has just happened.
3898 (when (interactive-p) (org-table-align))
3899 (let ((dests (orgtbl-gather-send-defs))
3900 (txt (buffer-substring-no-properties (org-table-begin)
3901 (org-table-end)))
3902 (ntbl 0))
3903 (unless dests (if maybe (throw 'exit nil)
3904 (error "Don't know how to transform this table")))
3905 (dolist (dest dests)
3906 (let* ((name (plist-get dest :name))
3907 (transform (plist-get dest :transform))
3908 (params (plist-get dest :params))
3909 (skip (plist-get params :skip))
3910 (skipcols (plist-get params :skipcols))
3912 (lines (org-table-clean-before-export
3913 (nthcdr (or skip 0)
3914 (org-split-string txt "[ \t]*\n[ \t]*"))))
3915 (i0 (if org-table-clean-did-remove-column 2 1))
3916 (table (mapcar
3917 (lambda (x)
3918 (if (string-match org-table-hline-regexp x)
3919 'hline
3920 (org-remove-by-index
3921 (org-split-string (org-trim x) "\\s-*|\\s-*")
3922 skipcols i0)))
3923 lines))
3924 (fun (if (= i0 2) 'cdr 'identity))
3925 (org-table-last-alignment
3926 (org-remove-by-index (funcall fun org-table-last-alignment)
3927 skipcols i0))
3928 (org-table-last-column-widths
3929 (org-remove-by-index (funcall fun org-table-last-column-widths)
3930 skipcols i0))
3931 (txt (if (fboundp transform)
3932 (funcall transform table params)
3933 (error "No such transformation function %s" transform))))
3934 (orgtbl-send-replace-tbl name txt))
3935 (setq ntbl (1+ ntbl)))
3936 (message "Table converted and installed at %d receiver location%s"
3937 ntbl (if (> ntbl 1) "s" "")))))
3939 (defun org-remove-by-index (list indices &optional i0)
3940 "Remove the elements in LIST with indices in INDICES.
3941 First element has index 0, or I0 if given."
3942 (if (not indices)
3943 list
3944 (if (integerp indices) (setq indices (list indices)))
3945 (setq i0 (1- (or i0 0)))
3946 (delq :rm (mapcar (lambda (x)
3947 (setq i0 (1+ i0))
3948 (if (memq i0 indices) :rm x))
3949 list))))
3951 (defun orgtbl-toggle-comment ()
3952 "Comment or uncomment the orgtbl at point."
3953 (interactive)
3954 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
3955 (re2 (concat "^" orgtbl-line-start-regexp))
3956 (commented (save-excursion (beginning-of-line 1)
3957 (cond ((looking-at re1) t)
3958 ((looking-at re2) nil)
3959 (t (error "Not at an org table")))))
3960 (re (if commented re1 re2))
3961 beg end)
3962 (save-excursion
3963 (beginning-of-line 1)
3964 (while (looking-at re) (beginning-of-line 0))
3965 (beginning-of-line 2)
3966 (setq beg (point))
3967 (while (looking-at re) (beginning-of-line 2))
3968 (setq end (point)))
3969 (comment-region beg end (if commented '(4) nil))))
3971 (defun orgtbl-insert-radio-table ()
3972 "Insert a radio table template appropriate for this major mode."
3973 (interactive)
3974 (let* ((e (assq major-mode orgtbl-radio-table-templates))
3975 (txt (nth 1 e))
3976 name pos)
3977 (unless e (error "No radio table setup defined for %s" major-mode))
3978 (setq name (read-string "Table name: "))
3979 (while (string-match "%n" txt)
3980 (setq txt (replace-match name t t txt)))
3981 (or (bolp) (insert "\n"))
3982 (setq pos (point))
3983 (insert txt)
3984 (goto-char pos)))
3986 ;; Dynamically bound input and output for table formatting.
3987 (defvar *orgtbl-table* nil
3988 "Carries the current table through formatting routines.")
3989 (defvar *orgtbl-rtn* nil
3990 "Formatting routines push the output lines here.")
3991 ;; Formatting parameters for the current table section.
3992 (defvar *orgtbl-hline* nil "Text used for horizontal lines")
3993 (defvar *orgtbl-sep* nil "Text used as a column separator")
3994 (defvar *orgtbl-default-fmt* nil "Default format for each entry")
3995 (defvar *orgtbl-fmt* nil "Format for each entry")
3996 (defvar *orgtbl-efmt* nil "Format for numbers")
3997 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt")
3998 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row")
3999 (defvar *orgtbl-lstart* nil "Text starting a row")
4000 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row")
4001 (defvar *orgtbl-lend* nil "Text ending a row")
4002 (defvar *orgtbl-llend* nil "Specializes lend for the last row")
4004 (defsubst orgtbl-get-fmt (fmt i)
4005 "Retrieve the format from FMT corresponding to the Ith column."
4006 (if (and (not (functionp fmt)) (consp fmt))
4007 (plist-get fmt i)
4008 fmt))
4010 (defsubst orgtbl-apply-fmt (fmt &rest args)
4011 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4012 (cond ((functionp fmt) (apply fmt args))
4013 (fmt (apply 'format fmt args))
4014 (args (car args))
4015 (t args)))
4017 (defsubst orgtbl-eval-str (str)
4018 "If STR is a function, evaluate it with no arguments."
4019 (if (functionp str)
4020 (funcall str)
4021 str))
4023 (defun orgtbl-format-line (line)
4024 "Format LINE as a table row."
4025 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4026 (let* ((i 0)
4027 (line
4028 (mapcar
4029 (lambda (f)
4030 (setq i (1+ i))
4031 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4032 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4033 (orgtbl-apply-fmt efmt (match-string 1 f)
4034 (match-string 2 f))
4035 f)))
4036 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4037 *orgtbl-default-fmt*)
4038 f)))
4039 line)))
4040 (push (if *orgtbl-lfmt*
4041 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4042 (concat (orgtbl-eval-str *orgtbl-lstart*)
4043 (mapconcat 'identity line *orgtbl-sep*)
4044 (orgtbl-eval-str *orgtbl-lend*)))
4045 *orgtbl-rtn*))))
4047 (defun orgtbl-format-section (section-stopper)
4048 "Format lines until the first occurrence of SECTION-STOPPER."
4049 (let (prevline)
4050 (progn
4051 (while (not (eq (car *orgtbl-table*) section-stopper))
4052 (if prevline (orgtbl-format-line prevline))
4053 (setq prevline (pop *orgtbl-table*)))
4054 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4055 (*orgtbl-lend* *orgtbl-llend*)
4056 (*orgtbl-lfmt* *orgtbl-llfmt*))
4057 (orgtbl-format-line prevline))))))
4059 (defun orgtbl-to-generic (table params)
4060 "Convert the orgtbl-mode TABLE to some other format.
4061 This generic routine can be used for many standard cases.
4062 TABLE is a list, each entry either the symbol `hline' for a horizontal
4063 separator line, or a list of fields for that line.
4064 PARAMS is a property list of parameters that can influence the conversion.
4065 For the generic converter, some parameters are obligatory: You need to
4066 specify either :lfmt, or all of (:lstart :lend :sep).
4068 Valid parameters are
4070 :splice When set to t, return only table body lines, don't wrap
4071 them into :tstart and :tend. Default is nil. When :splice
4072 is non-nil, this also means that the exporter should not look
4073 for and interpret header and footer sections.
4075 :hline String to be inserted on horizontal separation lines.
4076 May be nil to ignore hlines.
4078 :sep Separator between two fields
4079 :remove-nil-lines Do not include lines that evaluate to nil.
4082 Each in the following group may be either a string or a function
4083 of no arguments returning a string:
4084 :tstart String to start the table. Ignored when :splice is t.
4085 :tend String to end the table. Ignored when :splice is t.
4086 :lstart String to start a new table line.
4087 :llstart String to start the last table line, defaults to :lstart.
4088 :lend String to end a table line
4089 :llend String to end the last table line, defaults to :lend.
4091 Each in the following group may be a string, a function of one
4092 argument (the field or line) returning a string, or a plist
4093 mapping columns to either of the above:
4094 :lfmt Format for entire line, with enough %s to capture all fields.
4095 If this is present, :lstart, :lend, and :sep are ignored.
4096 :llfmt Format for the entire last line, defaults to :lfmt.
4097 :fmt A format to be used to wrap the field, should contain
4098 %s for the original field value. For example, to wrap
4099 everything in dollars, you could use :fmt \"$%s$\".
4100 This may also be a property list with column numbers and
4101 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4103 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4104 Same as above, specific for the header lines in the table.
4105 All lines before the first hline are treated as header.
4106 If any of these is not present, the data line value is used.
4108 This may be either a string or a function of two arguments:
4109 :efmt Use this format to print numbers with exponentials.
4110 The format should have %s twice for inserting mantissa
4111 and exponent, for example \"%s\\\\times10^{%s}\". This
4112 may also be a property list with column numbers and
4113 formats. :fmt will still be applied after :efmt.
4115 In addition to this, the parameters :skip and :skipcols are always handled
4116 directly by `orgtbl-send-table'. See manual."
4117 (interactive)
4119 (let* ((splicep (plist-get params :splice))
4120 (hline (plist-get params :hline))
4121 (remove-nil-linesp (plist-get params :remove-nil-lines))
4122 (remove-newlines (plist-get params :remove-newlines))
4123 (*orgtbl-hline* hline)
4124 (*orgtbl-table* table)
4125 (*orgtbl-sep* (plist-get params :sep))
4126 (*orgtbl-efmt* (plist-get params :efmt))
4127 (*orgtbl-lstart* (plist-get params :lstart))
4128 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4129 (*orgtbl-lend* (plist-get params :lend))
4130 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4131 (*orgtbl-lfmt* (plist-get params :lfmt))
4132 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4133 (*orgtbl-fmt* (plist-get params :fmt))
4134 *orgtbl-rtn*)
4136 ;; Put header
4137 (unless splicep
4138 (when (plist-member params :tstart)
4139 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4140 (if tstart (push tstart *orgtbl-rtn*)))))
4142 ;; Do we have a heading section? If so, format it and handle the
4143 ;; trailing hline.
4144 (if (and (not splicep)
4145 (or (consp (car *orgtbl-table*))
4146 (consp (nth 1 *orgtbl-table*)))
4147 (memq 'hline (cdr *orgtbl-table*)))
4148 (progn
4149 (when (eq 'hline (car *orgtbl-table*))
4150 ;; there is a hline before the first data line
4151 (and hline (push hline *orgtbl-rtn*))
4152 (pop *orgtbl-table*))
4153 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4154 *orgtbl-lstart*))
4155 (*orgtbl-llstart* (or (plist-get params :hllstart)
4156 *orgtbl-llstart*))
4157 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4158 (*orgtbl-llend* (or (plist-get params :hllend)
4159 (plist-get params :hlend) *orgtbl-llend*))
4160 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4161 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4162 (plist-get params :hlfmt) *orgtbl-llfmt*))
4163 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4164 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4165 (orgtbl-format-section 'hline))
4166 (if hline (push hline *orgtbl-rtn*))
4167 (pop *orgtbl-table*)))
4169 ;; Now format the main section.
4170 (orgtbl-format-section nil)
4172 (unless splicep
4173 (when (plist-member params :tend)
4174 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4175 (if tend (push tend *orgtbl-rtn*)))))
4177 (mapconcat (if remove-newlines
4178 (lambda (tend)
4179 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4180 'identity)
4181 (nreverse (if remove-nil-linesp
4182 (remq nil *orgtbl-rtn*)
4183 *orgtbl-rtn*)) "\n")))
4185 (defun orgtbl-to-tsv (table params)
4186 "Convert the orgtbl-mode table to TAB separated material."
4187 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4188 (defun orgtbl-to-csv (table params)
4189 "Convert the orgtbl-mode table to CSV material.
4190 This does take care of the proper quoting of fields with comma or quotes."
4191 (orgtbl-to-generic table (org-combine-plists
4192 '(:sep "," :fmt org-quote-csv-field)
4193 params)))
4195 (defun orgtbl-to-latex (table params)
4196 "Convert the orgtbl-mode TABLE to LaTeX.
4197 TABLE is a list, each entry either the symbol `hline' for a horizontal
4198 separator line, or a list of fields for that line.
4199 PARAMS is a property list of parameters that can influence the conversion.
4200 Supports all parameters from `orgtbl-to-generic'. Most important for
4201 LaTeX are:
4203 :splice When set to t, return only table body lines, don't wrap
4204 them into a tabular environment. Default is nil.
4206 :fmt A format to be used to wrap the field, should contain %s for the
4207 original field value. For example, to wrap everything in dollars,
4208 use :fmt \"$%s$\". This may also be a property list with column
4209 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4210 The format may also be a function that formats its one argument.
4212 :efmt Format for transforming numbers with exponentials. The format
4213 should have %s twice for inserting mantissa and exponent, for
4214 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4215 This may also be a property list with column numbers and formats.
4216 The format may also be a function that formats its two arguments.
4218 :llend If you find too much space below the last line of a table,
4219 pass a value of \"\" for :llend to suppress the final \\\\.
4221 The general parameters :skip and :skipcols have already been applied when
4222 this function is called."
4223 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4224 org-table-last-alignment ""))
4225 (params2
4226 (list
4227 :tstart (concat "\\begin{tabular}{" alignment "}")
4228 :tend "\\end{tabular}"
4229 :lstart "" :lend " \\\\" :sep " & "
4230 :efmt "%s\\,(%s)" :hline "\\hline")))
4231 (orgtbl-to-generic table (org-combine-plists params2 params))))
4233 (defun orgtbl-to-html (table params)
4234 "Convert the orgtbl-mode TABLE to HTML.
4235 TABLE is a list, each entry either the symbol `hline' for a horizontal
4236 separator line, or a list of fields for that line.
4237 PARAMS is a property list of parameters that can influence the conversion.
4238 Currently this function recognizes the following parameters:
4240 :splice When set to t, return only table body lines, don't wrap
4241 them into a <table> environment. Default is nil.
4243 The general parameters :skip and :skipcols have already been applied when
4244 this function is called. The function does *not* use `orgtbl-to-generic',
4245 so you cannot specify parameters for it."
4246 (let* ((splicep (plist-get params :splice))
4247 (html-table-tag org-export-html-table-tag)
4248 html)
4249 ;; Just call the formatter we already have
4250 ;; We need to make text lines for it, so put the fields back together.
4251 (setq html (org-format-org-table-html
4252 (mapcar
4253 (lambda (x)
4254 (if (eq x 'hline)
4255 "|----+----|"
4256 (concat "| " (mapconcat 'identity x " | ") " |")))
4257 table)
4258 splicep))
4259 (if (string-match "\n+\\'" html)
4260 (setq html (replace-match "" t t html)))
4261 html))
4263 (defun orgtbl-to-texinfo (table params)
4264 "Convert the orgtbl-mode TABLE to TeXInfo.
4265 TABLE is a list, each entry either the symbol `hline' for a horizontal
4266 separator line, or a list of fields for that line.
4267 PARAMS is a property list of parameters that can influence the conversion.
4268 Supports all parameters from `orgtbl-to-generic'. Most important for
4269 TeXInfo are:
4271 :splice nil/t When set to t, return only table body lines, don't wrap
4272 them into a multitable environment. Default is nil.
4274 :fmt fmt A format to be used to wrap the field, should contain
4275 %s for the original field value. For example, to wrap
4276 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4277 This may also be a property list with column numbers and
4278 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4279 Each format also may be a function that formats its one
4280 argument.
4282 :cf \"f1 f2..\" The column fractions for the table. By default these
4283 are computed automatically from the width of the columns
4284 under org-mode.
4286 The general parameters :skip and :skipcols have already been applied when
4287 this function is called."
4288 (let* ((total (float (apply '+ org-table-last-column-widths)))
4289 (colfrac (or (plist-get params :cf)
4290 (mapconcat
4291 (lambda (x) (format "%.3f" (/ (float x) total)))
4292 org-table-last-column-widths " ")))
4293 (params2
4294 (list
4295 :tstart (concat "@multitable @columnfractions " colfrac)
4296 :tend "@end multitable"
4297 :lstart "@item " :lend "" :sep " @tab "
4298 :hlstart "@headitem ")))
4299 (orgtbl-to-generic table (org-combine-plists params2 params))))
4301 (defun orgtbl-to-orgtbl (table params)
4302 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4303 Useful when slicing one table into many. The :hline, :sep,
4304 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4305 and :tend suppress strings without splicing; they can be set to
4306 provide ORGTBL directives for the generated table."
4307 (let* ((params2
4308 (list
4309 :remove-newlines t
4310 :tstart nil :tend nil
4311 :hline "|---"
4312 :sep " | "
4313 :lstart "| "
4314 :lend " |"))
4315 (params (org-combine-plists params2 params)))
4316 (orgtbl-to-generic table params)))
4318 (defun org-table-get-remote-range (name-or-id form)
4319 "Get a field value or a list of values in a range from table at ID.
4321 NAME-OR-ID may be the name of a table in the current file as set by
4322 a \"#+TBLNAME:\" directive. The first table following this line
4323 will then be used. Alternatively, it may be an ID referring to
4324 any entry, also in a different file. In this case, the first table
4325 in that entry will be referenced.
4326 FORM is a field or range descriptor like \"@2$3\" or or \"B3\" or
4327 \"@I$2..@II$2\". All the references must be absolute, not relative.
4329 The return value is either a single string for a single field, or a
4330 list of the fields in the rectangle ."
4331 (save-match-data
4332 (let ((id-loc nil)
4333 org-table-column-names org-table-column-name-regexp
4334 org-table-local-parameters org-table-named-field-locations
4335 org-table-current-line-types org-table-current-begin-line
4336 org-table-current-begin-pos org-table-dlines
4337 org-table-hlines org-table-last-alignment
4338 org-table-last-column-widths org-table-last-alignment
4339 org-table-last-column-widths tbeg
4340 buffer loc)
4341 (setq form (org-table-convert-refs-to-rc form))
4342 (save-excursion
4343 (save-restriction
4344 (widen)
4345 (save-excursion
4346 (goto-char (point-min))
4347 (if (re-search-forward
4348 (concat "^[ \t]*#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4349 nil t)
4350 (setq buffer (current-buffer) loc (match-beginning 0))
4351 (setq id-loc (org-id-find name-or-id 'marker))
4352 (unless (and id-loc (markerp id-loc))
4353 (error "Can't find remote table \"%s\"" name-or-id))
4354 (setq buffer (marker-buffer id-loc)
4355 loc (marker-position id-loc))
4356 (move-marker id-loc nil)))
4357 (with-current-buffer buffer
4358 (save-excursion
4359 (save-restriction
4360 (widen)
4361 (goto-char loc)
4362 (forward-char 1)
4363 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4364 (not (match-beginning 1)))
4365 (error "Cannot find a table at NAME or ID %s" name-or-id))
4366 (setq tbeg (point-at-bol))
4367 (org-table-get-specials)
4368 (setq form (org-table-formula-substitute-names form))
4369 (if (and (string-match org-table-range-regexp form)
4370 (> (length (match-string 0 form)) 1))
4371 (save-match-data
4372 (org-table-get-range (match-string 0 form) tbeg 1))
4373 form)))))))))
4375 (provide 'org-table)
4377 ;; arch-tag: 4d21cfdd-0268-440a-84b0-09237a0fe0ef
4379 ;;; org-table.el ends here