Release 7.01a
[org-mode.git] / lisp / org-table.el
blob3cbdb207bfc2dcead9cbe5da0ab4bfee172032b2
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: 7.01a
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'.
280 These can be overridden for a specific table by setting the
281 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
282 radio tables for the different export transformations and
283 available parameters."
284 :group 'org-table-import-export
285 :type 'string)
287 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
288 "Detects a table line marked for automatic recalculation.")
289 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
290 "Detects a table line marked for automatic recalculation.")
291 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
292 "Detects a table line marked for automatic recalculation.")
293 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
294 "Searching from within a table (any type) this finds the first line 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 command.")
309 (defvar org-table-current-begin-line nil
310 "Table begin line, non-nil only for the duration of a command.")
311 (defvar org-table-current-begin-pos nil
312 "Table begin position, non-nil only for the duration of a command.")
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, also 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 data lines 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 data line 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 preceded 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)' \
2572 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2573 it is the symbol `iterate', recompute the table until it no longer changes.
2574 If NOALIGN is not nil, do not re-align the table after the computations
2575 are done. This is typically used internally to save time, if it is
2576 known that the table will be realigned a little later anyway."
2577 (interactive "P")
2578 (or (memq this-command org-recalc-commands)
2579 (setq org-recalc-commands (cons this-command org-recalc-commands)))
2580 (unless (org-at-table-p) (error "Not at a table"))
2581 (if (or (eq all 'iterate) (equal all '(16)))
2582 (org-table-iterate)
2583 (org-table-get-specials)
2584 (let* ((eqlist (sort (org-table-get-stored-formulas)
2585 (lambda (a b) (string< (car a) (car b)))))
2586 (inhibit-redisplay (not debug-on-error))
2587 (line-re org-table-dataline-regexp)
2588 (thisline (org-current-line))
2589 (thiscol (org-table-current-column))
2590 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
2591 ;; Insert constants in all formulas
2592 (setq eqlist
2593 (mapcar (lambda (x)
2594 (setcdr x (org-table-formula-substitute-names (cdr x)))
2596 eqlist))
2597 ;; Split the equation list
2598 (while (setq eq (pop eqlist))
2599 (if (<= (string-to-char (car eq)) ?9)
2600 (push eq eqlnum)
2601 (push eq eqlname)))
2602 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
2603 (if all
2604 (progn
2605 (setq end (move-marker (make-marker) (1+ (org-table-end))))
2606 (goto-char (setq beg (org-table-begin)))
2607 (if (re-search-forward org-table-calculate-mark-regexp end t)
2608 ;; This is a table with marked lines, compute selected lines
2609 (setq line-re org-table-recalculate-regexp)
2610 ;; Move forward to the first non-header line
2611 (if (and (re-search-forward org-table-dataline-regexp end t)
2612 (re-search-forward org-table-hline-regexp end t)
2613 (re-search-forward org-table-dataline-regexp end t))
2614 (setq beg (match-beginning 0))
2615 nil))) ;; just leave beg where it is
2616 (setq beg (point-at-bol)
2617 end (move-marker (make-marker) (1+ (point-at-eol)))))
2618 (goto-char beg)
2619 (and all (message "Re-applying formulas to full table..."))
2621 ;; First find the named fields, and mark them untouchable
2622 (remove-text-properties beg end '(org-untouchable t))
2623 (while (setq eq (pop eqlname))
2624 (setq name (car eq)
2625 a (assoc name org-table-named-field-locations))
2626 (and (not a)
2627 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
2628 (setq a (list name
2629 (condition-case nil
2630 (aref org-table-dlines
2631 (string-to-number (match-string 1 name)))
2632 (error (error "Invalid row number in %s"
2633 name)))
2634 (string-to-number (match-string 2 name)))))
2635 (when (and a (or all (equal (nth 1 a) thisline)))
2636 (message "Re-applying formula to field: %s" name)
2637 (org-goto-line (nth 1 a))
2638 (org-table-goto-column (nth 2 a))
2639 (push (append a (list (cdr eq))) eqlname1)
2640 (org-table-put-field-property :org-untouchable t)))
2642 ;; Now evaluate the column formulas, but skip fields covered by
2643 ;; field formulas
2644 (goto-char beg)
2645 (while (re-search-forward line-re end t)
2646 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2647 ;; Unprotected line, recalculate
2648 (and all (message "Re-applying formulas to full table...(line %d)"
2649 (setq cnt (1+ cnt))))
2650 (setq org-last-recalc-line (org-current-line))
2651 (setq eql eqlnum)
2652 (while (setq entry (pop eql))
2653 (org-goto-line org-last-recalc-line)
2654 (org-table-goto-column (string-to-number (car entry)) nil 'force)
2655 (unless (get-text-property (point) :org-untouchable)
2656 (org-table-eval-formula nil (cdr entry)
2657 'noalign 'nocst 'nostore 'noanalysis)))))
2659 ;; Now evaluate the field formulas
2660 (while (setq eq (pop eqlname1))
2661 (message "Re-applying formula to field: %s" (car eq))
2662 (org-goto-line (nth 1 eq))
2663 (org-table-goto-column (nth 2 eq))
2664 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
2665 'nostore 'noanalysis))
2667 (org-goto-line thisline)
2668 (org-table-goto-column thiscol)
2669 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
2670 (or noalign (and org-table-may-need-update (org-table-align))
2671 (and all (message "Re-applying formulas to %d lines...done" cnt)))
2673 ;; back to initial position
2674 (message "Re-applying formulas...done")
2675 (org-goto-line thisline)
2676 (org-table-goto-column thiscol)
2677 (or noalign (and org-table-may-need-update (org-table-align))
2678 (and all (message "Re-applying formulas...done"))))))
2680 (defun org-table-iterate (&optional arg)
2681 "Recalculate the table until it does not change anymore."
2682 (interactive "P")
2683 (let ((imax (if arg (prefix-numeric-value arg) 10))
2684 (i 0)
2685 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2686 thistbl)
2687 (catch 'exit
2688 (while (< i imax)
2689 (setq i (1+ i))
2690 (org-table-recalculate 'all)
2691 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
2692 (if (not (string= lasttbl thistbl))
2693 (setq lasttbl thistbl)
2694 (if (> i 1)
2695 (message "Convergence after %d iterations" i)
2696 (message "Table was already stable"))
2697 (throw 'exit t)))
2698 (error "No convergence after %d iterations" i))))
2700 (defun org-table-recalculate-buffer-tables ()
2701 "Recalculate all tables in the current buffer."
2702 (interactive)
2703 (save-excursion
2704 (save-restriction
2705 (widen)
2706 (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
2708 (defun org-table-iterate-buffer-tables ()
2709 "Iterate all tables in the buffer, to converge inter-table dependencies."
2710 (interactive)
2711 (let* ((imax 10)
2712 (checksum (md5 (buffer-string)))
2715 (i imax))
2716 (save-excursion
2717 (save-restriction
2718 (widen)
2719 (catch 'exit
2720 (while (> i 0)
2721 (setq i (1- i))
2722 (org-table-map-tables (lambda () (org-table-recalculate t)) t)
2723 (if (equal checksum (setq c1 (md5 (buffer-string))))
2724 (progn
2725 (message "Convergence after %d iterations" (- imax i))
2726 (throw 'exit t))
2727 (setq checksum c1)))
2728 (error "No convergence after %d iterations" imax))))))
2730 (defun org-table-formula-substitute-names (f)
2731 "Replace $const with values in string F."
2732 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
2733 ;; First, check for column names
2734 (while (setq start (string-match org-table-column-name-regexp f start))
2735 (setq start (1+ start))
2736 (setq a (assoc (match-string 1 f) org-table-column-names))
2737 (setq f (replace-match (concat "$" (cdr a)) t t f)))
2738 ;; Parameters and constants
2739 (setq start 0)
2740 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start))
2741 (if (match-end 2)
2742 (setq start (match-end 2))
2743 (setq start (1+ start))
2744 (if (setq a (save-match-data
2745 (org-table-get-constant (match-string 1 f))))
2746 (setq f (replace-match
2747 (concat (if pp "(") a (if pp ")")) t t f)))))
2748 (if org-table-formula-debug
2749 (put-text-property 0 (length f) :orig-formula f1 f))
2752 (defun org-table-get-constant (const)
2753 "Find the value for a parameter or constant in a formula.
2754 Parameters get priority."
2755 (or (cdr (assoc const org-table-local-parameters))
2756 (cdr (assoc const org-table-formula-constants-local))
2757 (cdr (assoc const org-table-formula-constants))
2758 (and (fboundp 'constants-get) (constants-get const))
2759 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
2760 (org-entry-get nil (substring const 5) 'inherit))
2761 "#UNDEFINED_NAME"))
2763 (defvar org-table-fedit-map
2764 (let ((map (make-sparse-keymap)))
2765 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
2766 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
2767 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
2768 (org-defkey map "\C-c'" 'org-table-fedit-finish)
2769 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
2770 (org-defkey map "\C-c?" 'org-table-show-reference)
2771 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
2772 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
2773 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
2774 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
2775 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
2776 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
2777 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
2778 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
2779 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
2780 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
2781 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
2782 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
2783 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
2784 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
2785 map))
2787 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
2788 '("Edit-Formulas"
2789 ["Finish and Install" org-table-fedit-finish t]
2790 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
2791 ["Abort" org-table-fedit-abort t]
2792 "--"
2793 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
2794 ["Complete Lisp Symbol" lisp-complete-symbol t]
2795 "--"
2796 "Shift Reference at Point"
2797 ["Up" org-table-fedit-ref-up t]
2798 ["Down" org-table-fedit-ref-down t]
2799 ["Left" org-table-fedit-ref-left t]
2800 ["Right" org-table-fedit-ref-right t]
2802 "Change Test Row for Column Formulas"
2803 ["Up" org-table-fedit-line-up t]
2804 ["Down" org-table-fedit-line-down t]
2805 "--"
2806 ["Scroll Table Window" org-table-fedit-scroll t]
2807 ["Scroll Table Window down" org-table-fedit-scroll-down t]
2808 ["Show Table Grid" org-table-fedit-toggle-coordinates
2809 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
2810 org-table-overlay-coordinates)]
2811 "--"
2812 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
2813 :style toggle :selected org-table-buffer-is-an]))
2815 (defvar org-pos)
2817 (defun org-table-edit-formulas ()
2818 "Edit the formulas of the current table in a separate buffer."
2819 (interactive)
2820 (when (save-excursion (beginning-of-line 1) (looking-at "[ \t]*#\\+TBLFM"))
2821 (beginning-of-line 0))
2822 (unless (org-at-table-p) (error "Not at a table"))
2823 (org-table-get-specials)
2824 (let ((key (org-table-current-field-formula 'key 'noerror))
2825 (eql (sort (org-table-get-stored-formulas 'noerror)
2826 'org-table-formula-less-p))
2827 (pos (move-marker (make-marker) (point)))
2828 (startline 1)
2829 (wc (current-window-configuration))
2830 (sel-win (selected-window))
2831 (titles '((column . "# Column Formulas\n")
2832 (field . "# Field Formulas\n")
2833 (named . "# Named Field Formulas\n")))
2834 entry s type title)
2835 (org-switch-to-buffer-other-window "*Edit Formulas*")
2836 (erase-buffer)
2837 ;; Keep global-font-lock-mode from turning on font-lock-mode
2838 (let ((font-lock-global-modes '(not fundamental-mode)))
2839 (fundamental-mode))
2840 (org-set-local 'font-lock-global-modes (list 'not major-mode))
2841 (org-set-local 'org-pos pos)
2842 (org-set-local 'org-window-configuration wc)
2843 (org-set-local 'org-selected-window sel-win)
2844 (use-local-map org-table-fedit-map)
2845 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
2846 (easy-menu-add org-table-fedit-menu)
2847 (setq startline (org-current-line))
2848 (while (setq entry (pop eql))
2849 (setq type (cond
2850 ((equal (string-to-char (car entry)) ?@) 'field)
2851 ((string-match "^[0-9]" (car entry)) 'column)
2852 (t 'named)))
2853 (when (setq title (assq type titles))
2854 (or (bobp) (insert "\n"))
2855 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
2856 (setq titles (delq title titles)))
2857 (if (equal key (car entry)) (setq startline (org-current-line)))
2858 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
2859 (car entry) " = " (cdr entry) "\n"))
2860 (remove-text-properties 0 (length s) '(face nil) s)
2861 (insert s))
2862 (if (eq org-table-use-standard-references t)
2863 (org-table-fedit-toggle-ref-type))
2864 (org-goto-line startline)
2865 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
2867 (defun org-table-fedit-post-command ()
2868 (when (not (memq this-command '(lisp-complete-symbol)))
2869 (let ((win (selected-window)))
2870 (save-excursion
2871 (condition-case nil
2872 (org-table-show-reference)
2873 (error nil))
2874 (select-window win)))))
2876 (defun org-table-formula-to-user (s)
2877 "Convert a formula from internal to user representation."
2878 (if (eq org-table-use-standard-references t)
2879 (org-table-convert-refs-to-an s)
2882 (defun org-table-formula-from-user (s)
2883 "Convert a formula from user to internal representation."
2884 (if org-table-use-standard-references
2885 (org-table-convert-refs-to-rc s)
2888 (defun org-table-convert-refs-to-rc (s)
2889 "Convert spreadsheet references from AB7 to @7$28.
2890 Works for single references, but also for entire formulas and even the
2891 full TBLFM line."
2892 (let ((start 0))
2893 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^)]*)\\)" s start)
2894 (cond
2895 ((match-end 3)
2896 ;; format match, just advance
2897 (setq start (match-end 0)))
2898 ((and (> (match-beginning 0) 0)
2899 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
2900 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
2901 ;; 3.e5 or something like this.
2902 (setq start (match-end 0)))
2903 ((or (> (- (match-end 1) (match-beginning 1)) 2)
2904 ;; (member (match-string 1 s)
2905 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
2907 ;; function name, just advance
2908 (setq start (match-end 0)))
2910 (setq start (match-beginning 0)
2911 s (replace-match
2912 (if (equal (match-string 2 s) "&")
2913 (format "$%d" (org-letters-to-number (match-string 1 s)))
2914 (format "@%d$%d"
2915 (string-to-number (match-string 2 s))
2916 (org-letters-to-number (match-string 1 s))))
2917 t t s)))))
2920 (defun org-table-convert-refs-to-an (s)
2921 "Convert spreadsheet references from to @7$28 to AB7.
2922 Works for single references, but also for entire formulas and even the
2923 full TBLFM line."
2924 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
2925 (setq s (replace-match
2926 (format "%s%d"
2927 (org-number-to-letters
2928 (string-to-number (match-string 2 s)))
2929 (string-to-number (match-string 1 s)))
2930 t t s)))
2931 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
2932 (setq s (replace-match (concat "\\1"
2933 (org-number-to-letters
2934 (string-to-number (match-string 2 s))) "&")
2935 t nil s)))
2938 (defun org-letters-to-number (s)
2939 "Convert a base 26 number represented by letters into an integer.
2940 For example: AB -> 28."
2941 (let ((n 0))
2942 (setq s (upcase s))
2943 (while (> (length s) 0)
2944 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
2945 s (substring s 1)))
2948 (defun org-number-to-letters (n)
2949 "Convert an integer into a base 26 number represented by letters.
2950 For example: 28 -> AB."
2951 (let ((s ""))
2952 (while (> n 0)
2953 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
2954 n (/ (1- n) 26)))
2957 (defun org-table-fedit-convert-buffer (function)
2958 "Convert all references in this buffer, using FUNCTION."
2959 (let ((line (org-current-line)))
2960 (goto-char (point-min))
2961 (while (not (eobp))
2962 (insert (funcall function (buffer-substring (point) (point-at-eol))))
2963 (delete-region (point) (point-at-eol))
2964 (or (eobp) (forward-char 1)))
2965 (org-goto-line line)))
2967 (defun org-table-fedit-toggle-ref-type ()
2968 "Convert all references in the buffer from B3 to @3$2 and back."
2969 (interactive)
2970 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
2971 (org-table-fedit-convert-buffer
2972 (if org-table-buffer-is-an
2973 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
2974 (message "Reference type switched to %s"
2975 (if org-table-buffer-is-an "A1 etc" "@row$column")))
2977 (defun org-table-fedit-ref-up ()
2978 "Shift the reference at point one row/hline up."
2979 (interactive)
2980 (org-table-fedit-shift-reference 'up))
2981 (defun org-table-fedit-ref-down ()
2982 "Shift the reference at point one row/hline down."
2983 (interactive)
2984 (org-table-fedit-shift-reference 'down))
2985 (defun org-table-fedit-ref-left ()
2986 "Shift the reference at point one field to the left."
2987 (interactive)
2988 (org-table-fedit-shift-reference 'left))
2989 (defun org-table-fedit-ref-right ()
2990 "Shift the reference at point one field to the right."
2991 (interactive)
2992 (org-table-fedit-shift-reference 'right))
2994 (defun org-table-fedit-shift-reference (dir)
2995 (cond
2996 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
2997 (if (memq dir '(left right))
2998 (org-rematch-and-replace 1 (eq dir 'left))
2999 (error "Cannot shift reference in this direction")))
3000 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3001 ;; A B3-like reference
3002 (if (memq dir '(up down))
3003 (org-rematch-and-replace 2 (eq dir 'up))
3004 (org-rematch-and-replace 1 (eq dir 'left))))
3005 ((org-at-regexp-p
3006 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3007 ;; An internal reference
3008 (if (memq dir '(up down))
3009 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3010 (org-rematch-and-replace 5 (eq dir 'left))))))
3012 (defun org-rematch-and-replace (n &optional decr hline)
3013 "Re-match the group N, and replace it with the shifted reference."
3014 (or (match-end n) (error "Cannot shift reference in this direction"))
3015 (goto-char (match-beginning n))
3016 (and (looking-at (regexp-quote (match-string n)))
3017 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3018 t t)))
3020 (defun org-table-shift-refpart (ref &optional decr hline)
3021 "Shift a reference part REF.
3022 If DECR is set, decrease the references row/column, else increase.
3023 If HLINE is set, this may be a hline reference, it certainly is not
3024 a translation reference."
3025 (save-match-data
3026 (let* ((sign (string-match "^[-+]" ref)) n)
3028 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3029 (cond
3030 ((and hline (string-match "^I+" ref))
3031 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3032 (setq n (+ n (if decr -1 1)))
3033 (if (= n 0) (setq n (+ n (if decr -1 1))))
3034 (if sign
3035 (setq sign (if (< n 0) "-" "+") n (abs n))
3036 (setq n (max 1 n)))
3037 (concat sign (make-string n ?I)))
3039 ((string-match "^[0-9]+" ref)
3040 (setq n (string-to-number (concat sign ref)))
3041 (setq n (+ n (if decr -1 1)))
3042 (if sign
3043 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3044 (number-to-string (max 1 n))))
3046 ((string-match "^[a-zA-Z]+" ref)
3047 (org-number-to-letters
3048 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3050 (t (error "Cannot shift reference"))))))
3052 (defun org-table-fedit-toggle-coordinates ()
3053 "Toggle the display of coordinates in the referenced table."
3054 (interactive)
3055 (let ((pos (marker-position org-pos)))
3056 (with-current-buffer (marker-buffer org-pos)
3057 (save-excursion
3058 (goto-char pos)
3059 (org-table-toggle-coordinate-overlays)))))
3061 (defun org-table-fedit-finish (&optional arg)
3062 "Parse the buffer for formula definitions and install them.
3063 With prefix ARG, apply the new formulas to the table."
3064 (interactive "P")
3065 (org-table-remove-rectangle-highlight)
3066 (if org-table-use-standard-references
3067 (progn
3068 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3069 (setq org-table-buffer-is-an nil)))
3070 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3071 (goto-char (point-min))
3072 (while (re-search-forward
3073 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3074 nil t)
3075 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3076 form (match-string 3))
3077 (setq form (org-trim form))
3078 (when (not (equal form ""))
3079 (while (string-match "[ \t]*\n[ \t]*" form)
3080 (setq form (replace-match " " t t form)))
3081 (when (assoc var eql)
3082 (error "Double formulas for %s" var))
3083 (push (cons var form) eql)))
3084 (setq org-pos nil)
3085 (set-window-configuration org-window-configuration)
3086 (select-window sel-win)
3087 (goto-char pos)
3088 (unless (org-at-table-p)
3089 (error "Lost table position - cannot install formulas"))
3090 (org-table-store-formulas eql)
3091 (move-marker pos nil)
3092 (kill-buffer "*Edit Formulas*")
3093 (if arg
3094 (org-table-recalculate 'all)
3095 (message "New formulas installed - press C-u C-c C-c to apply."))))
3097 (defun org-table-fedit-abort ()
3098 "Abort editing formulas, without installing the changes."
3099 (interactive)
3100 (org-table-remove-rectangle-highlight)
3101 (let ((pos org-pos) (sel-win org-selected-window))
3102 (set-window-configuration org-window-configuration)
3103 (select-window sel-win)
3104 (goto-char pos)
3105 (move-marker pos nil)
3106 (message "Formula editing aborted without installing changes")))
3108 (defun org-table-fedit-lisp-indent ()
3109 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3110 (interactive)
3111 (let ((pos (point)) beg end ind)
3112 (beginning-of-line 1)
3113 (cond
3114 ((looking-at "[ \t]")
3115 (goto-char pos)
3116 (call-interactively 'lisp-indent-line))
3117 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3118 ((not (fboundp 'pp-buffer))
3119 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3120 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3121 (goto-char (- (match-end 0) 2))
3122 (setq beg (point))
3123 (setq ind (make-string (current-column) ?\ ))
3124 (condition-case nil (forward-sexp 1)
3125 (error
3126 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3127 (setq end (point))
3128 (save-restriction
3129 (narrow-to-region beg end)
3130 (if (eq last-command this-command)
3131 (progn
3132 (goto-char (point-min))
3133 (setq this-command nil)
3134 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3135 (replace-match " ")))
3136 (pp-buffer)
3137 (untabify (point-min) (point-max))
3138 (goto-char (1+ (point-min)))
3139 (while (re-search-forward "^." nil t)
3140 (beginning-of-line 1)
3141 (insert ind))
3142 (goto-char (point-max))
3143 (backward-delete-char 1)))
3144 (goto-char beg))
3145 (t nil))))
3147 (defvar org-show-positions nil)
3149 (defun org-table-show-reference (&optional local)
3150 "Show the location/value of the $ expression at point."
3151 (interactive)
3152 (org-table-remove-rectangle-highlight)
3153 (catch 'exit
3154 (let ((pos (if local (point) org-pos))
3155 (face2 'highlight)
3156 (org-inhibit-highlight-removal t)
3157 (win (selected-window))
3158 (org-show-positions nil)
3159 var name e what match dest)
3160 (if local (org-table-get-specials))
3161 (setq what (cond
3162 ((or (org-at-regexp-p org-table-range-regexp2)
3163 (org-at-regexp-p org-table-translate-regexp)
3164 (org-at-regexp-p org-table-range-regexp))
3165 (setq match
3166 (save-match-data
3167 (org-table-convert-refs-to-rc (match-string 0))))
3168 'range)
3169 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3170 ((org-at-regexp-p "\\$[0-9]+") 'column)
3171 ((not local) nil)
3172 (t (error "No reference at point")))
3173 match (and what (or match (match-string 0))))
3174 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3175 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3176 'secondary-selection))
3177 (org-add-hook 'before-change-functions
3178 'org-table-remove-rectangle-highlight)
3179 (if (eq what 'name) (setq var (substring match 1)))
3180 (when (eq what 'range)
3181 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
3182 (setq match (org-table-formula-substitute-names match)))
3183 (unless local
3184 (save-excursion
3185 (end-of-line 1)
3186 (re-search-backward "^\\S-" nil t)
3187 (beginning-of-line 1)
3188 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3189 (setq dest
3190 (save-match-data
3191 (org-table-convert-refs-to-rc (match-string 1))))
3192 (org-table-add-rectangle-overlay
3193 (match-beginning 1) (match-end 1) face2))))
3194 (if (and (markerp pos) (marker-buffer pos))
3195 (if (get-buffer-window (marker-buffer pos))
3196 (select-window (get-buffer-window (marker-buffer pos)))
3197 (org-switch-to-buffer-other-window (get-buffer-window
3198 (marker-buffer pos)))))
3199 (goto-char pos)
3200 (org-table-force-dataline)
3201 (when dest
3202 (setq name (substring dest 1))
3203 (cond
3204 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3205 (setq e (assoc name org-table-named-field-locations))
3206 (org-goto-line (nth 1 e))
3207 (org-table-goto-column (nth 2 e)))
3208 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
3209 (let ((l (string-to-number (match-string 1 dest)))
3210 (c (string-to-number (match-string 2 dest))))
3211 (org-goto-line (aref org-table-dlines l))
3212 (org-table-goto-column c)))
3213 (t (org-table-goto-column (string-to-number name))))
3214 (move-marker pos (point))
3215 (org-table-highlight-rectangle nil nil face2))
3216 (cond
3217 ((equal dest match))
3218 ((not match))
3219 ((eq what 'range)
3220 (condition-case nil
3221 (save-excursion
3222 (org-table-get-range match nil nil 'highlight))
3223 (error nil)))
3224 ((setq e (assoc var org-table-named-field-locations))
3225 (org-goto-line (nth 1 e))
3226 (org-table-goto-column (nth 2 e))
3227 (org-table-highlight-rectangle (point) (point))
3228 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3229 ((setq e (assoc var org-table-column-names))
3230 (org-table-goto-column (string-to-number (cdr e)))
3231 (org-table-highlight-rectangle (point) (point))
3232 (goto-char (org-table-begin))
3233 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3234 (org-table-end) t)
3235 (progn
3236 (goto-char (match-beginning 1))
3237 (org-table-highlight-rectangle)
3238 (message "Named column (column %s)" (cdr e)))
3239 (error "Column name not found")))
3240 ((eq what 'column)
3241 ;; column number
3242 (org-table-goto-column (string-to-number (substring match 1)))
3243 (org-table-highlight-rectangle (point) (point))
3244 (message "Column %s" (substring match 1)))
3245 ((setq e (assoc var org-table-local-parameters))
3246 (goto-char (org-table-begin))
3247 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3248 (progn
3249 (goto-char (match-beginning 1))
3250 (org-table-highlight-rectangle)
3251 (message "Local parameter."))
3252 (error "Parameter not found")))
3254 (cond
3255 ((not var) (error "No reference at point"))
3256 ((setq e (assoc var org-table-formula-constants-local))
3257 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3258 var (cdr e)))
3259 ((setq e (assoc var org-table-formula-constants))
3260 (message "Constant: $%s=%s in `org-table-formula-constants'."
3261 var (cdr e)))
3262 ((setq e (and (fboundp 'constants-get) (constants-get var)))
3263 (message "Constant: $%s=%s, from `constants.el'%s."
3264 var e (format " (%s units)" constants-unit-system)))
3265 (t (error "Undefined name $%s" var)))))
3266 (goto-char pos)
3267 (when (and org-show-positions
3268 (not (memq this-command '(org-table-fedit-scroll
3269 org-table-fedit-scroll-down))))
3270 (push pos org-show-positions)
3271 (push org-table-current-begin-pos org-show-positions)
3272 (let ((min (apply 'min org-show-positions))
3273 (max (apply 'max org-show-positions)))
3274 (goto-char min) (recenter 0)
3275 (goto-char max)
3276 (or (pos-visible-in-window-p max) (recenter -1))))
3277 (select-window win))))
3279 (defun org-table-force-dataline ()
3280 "Make sure the cursor is in a dataline in a table."
3281 (unless (save-excursion
3282 (beginning-of-line 1)
3283 (looking-at org-table-dataline-regexp))
3284 (let* ((re org-table-dataline-regexp)
3285 (p1 (save-excursion (re-search-forward re nil 'move)))
3286 (p2 (save-excursion (re-search-backward re nil 'move))))
3287 (cond ((and p1 p2)
3288 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
3289 p1 p2)))
3290 ((or p1 p2) (goto-char (or p1 p2)))
3291 (t (error "No table dataline around here"))))))
3293 (defun org-table-fedit-line-up ()
3294 "Move cursor one line up in the window showing the table."
3295 (interactive)
3296 (org-table-fedit-move 'previous-line))
3298 (defun org-table-fedit-line-down ()
3299 "Move cursor one line down in the window showing the table."
3300 (interactive)
3301 (org-table-fedit-move 'next-line))
3303 (defun org-table-fedit-move (command)
3304 "Move the cursor in the window showing the table.
3305 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3306 (let ((org-table-allow-automatic-line-recalculation nil)
3307 (pos org-pos) (win (selected-window)) p)
3308 (select-window (get-buffer-window (marker-buffer org-pos)))
3309 (setq p (point))
3310 (call-interactively command)
3311 (while (and (org-at-table-p)
3312 (org-at-table-hline-p))
3313 (call-interactively command))
3314 (or (org-at-table-p) (goto-char p))
3315 (move-marker pos (point))
3316 (select-window win)))
3318 (defun org-table-fedit-scroll (N)
3319 (interactive "p")
3320 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
3321 (scroll-other-window N)))
3323 (defun org-table-fedit-scroll-down (N)
3324 (interactive "p")
3325 (org-table-fedit-scroll (- N)))
3327 (defvar org-table-rectangle-overlays nil)
3329 (defun org-table-add-rectangle-overlay (beg end &optional face)
3330 "Add a new overlay."
3331 (let ((ov (make-overlay beg end)))
3332 (overlay-put ov 'face (or face 'secondary-selection))
3333 (push ov org-table-rectangle-overlays)))
3335 (defun org-table-highlight-rectangle (&optional beg end face)
3336 "Highlight rectangular region in a table."
3337 (setq beg (or beg (point)) end (or end (point)))
3338 (let ((b (min beg end))
3339 (e (max beg end))
3340 l1 c1 l2 c2 tmp)
3341 (and (boundp 'org-show-positions)
3342 (setq org-show-positions (cons b (cons e org-show-positions))))
3343 (goto-char (min beg end))
3344 (setq l1 (org-current-line)
3345 c1 (org-table-current-column))
3346 (goto-char (max beg end))
3347 (setq l2 (org-current-line)
3348 c2 (org-table-current-column))
3349 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
3350 (org-goto-line l1)
3351 (beginning-of-line 1)
3352 (loop for line from l1 to l2 do
3353 (when (looking-at org-table-dataline-regexp)
3354 (org-table-goto-column c1)
3355 (skip-chars-backward "^|\n") (setq beg (point))
3356 (org-table-goto-column c2)
3357 (skip-chars-forward "^|\n") (setq end (point))
3358 (org-table-add-rectangle-overlay beg end face))
3359 (beginning-of-line 2))
3360 (goto-char b))
3361 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
3363 (defun org-table-remove-rectangle-highlight (&rest ignore)
3364 "Remove the rectangle overlays."
3365 (unless org-inhibit-highlight-removal
3366 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
3367 (mapc 'delete-overlay org-table-rectangle-overlays)
3368 (setq org-table-rectangle-overlays nil)))
3370 (defvar org-table-coordinate-overlays nil
3371 "Collects the coordinate grid overlays, so that they can be removed.")
3372 (make-variable-buffer-local 'org-table-coordinate-overlays)
3374 (defun org-table-overlay-coordinates ()
3375 "Add overlays to the table at point, to show row/column coordinates."
3376 (interactive)
3377 (mapc 'delete-overlay org-table-coordinate-overlays)
3378 (setq org-table-coordinate-overlays nil)
3379 (save-excursion
3380 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
3381 (goto-char (org-table-begin))
3382 (while (org-at-table-p)
3383 (setq eol (point-at-eol))
3384 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
3385 (push ov org-table-coordinate-overlays)
3386 (setq hline (looking-at org-table-hline-regexp))
3387 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
3388 (format "%4d" (setq id (1+ id)))))
3389 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
3390 (when hline
3391 (setq ic 0)
3392 (while (re-search-forward "[+|]\\(-+\\)" eol t)
3393 (setq beg (1+ (match-beginning 0))
3394 ic (1+ ic)
3395 s1 (concat "$" (int-to-string ic))
3396 s2 (org-number-to-letters ic)
3397 str (if (eq org-table-use-standard-references t) s2 s1))
3398 (setq ov (make-overlay beg (+ beg (length str))))
3399 (push ov org-table-coordinate-overlays)
3400 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
3401 (beginning-of-line 2)))))
3403 (defun org-table-toggle-coordinate-overlays ()
3404 "Toggle the display of Row/Column numbers in tables."
3405 (interactive)
3406 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
3407 (message "Row/Column number display turned %s"
3408 (if org-table-overlay-coordinates "on" "off"))
3409 (if (and (org-at-table-p) org-table-overlay-coordinates)
3410 (org-table-align))
3411 (unless org-table-overlay-coordinates
3412 (mapc 'delete-overlay org-table-coordinate-overlays)
3413 (setq org-table-coordinate-overlays nil)))
3415 (defun org-table-toggle-formula-debugger ()
3416 "Toggle the formula debugger in tables."
3417 (interactive)
3418 (setq org-table-formula-debug (not org-table-formula-debug))
3419 (message "Formula debugging has been turned %s"
3420 (if org-table-formula-debug "on" "off")))
3422 ;;; The orgtbl minor mode
3424 ;; Define a minor mode which can be used in other modes in order to
3425 ;; integrate the org-mode table editor.
3427 ;; This is really a hack, because the org-mode table editor uses several
3428 ;; keys which normally belong to the major mode, for example the TAB and
3429 ;; RET keys. Here is how it works: The minor mode defines all the keys
3430 ;; necessary to operate the table editor, but wraps the commands into a
3431 ;; function which tests if the cursor is currently inside a table. If that
3432 ;; is the case, the table editor command is executed. However, when any of
3433 ;; those keys is used outside a table, the function uses `key-binding' to
3434 ;; look up if the key has an associated command in another currently active
3435 ;; keymap (minor modes, major mode, global), and executes that command.
3436 ;; There might be problems if any of the keys used by the table editor is
3437 ;; otherwise used as a prefix key.
3439 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3440 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3441 ;; addresses this by checking explicitly for both bindings.
3443 ;; The optimized version (see variable `orgtbl-optimized') takes over
3444 ;; all keys which are bound to `self-insert-command' in the *global map*.
3445 ;; Some modes bind other commands to simple characters, for example
3446 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3447 ;; active, this binding is ignored inside tables and replaced with a
3448 ;; modified self-insert.
3451 (defvar orgtbl-mode-map (make-keymap)
3452 "Keymap for `orgtbl-mode'.")
3454 ;;;###autoload
3455 (defun turn-on-orgtbl ()
3456 "Unconditionally turn on `orgtbl-mode'."
3457 (orgtbl-mode 1))
3459 (defvar org-old-auto-fill-inhibit-regexp nil
3460 "Local variable used by `orgtbl-mode'.")
3462 (defconst orgtbl-line-start-regexp
3463 "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\|TBLNAME\\):\\)"
3464 "Matches a line belonging to an orgtbl.")
3466 (defconst orgtbl-extra-font-lock-keywords
3467 (list (list (concat "^" orgtbl-line-start-regexp ".*")
3468 0 (quote 'org-table) 'prepend))
3469 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
3471 ;; Install it as a minor mode.
3472 (put 'orgtbl-mode :included t)
3473 (put 'orgtbl-mode :menu-tag "Org Table Mode")
3475 ;;;###autoload
3476 (define-minor-mode orgtbl-mode
3477 "The `org-mode' table editor as a minor mode for use in other modes."
3478 :lighter " OrgTbl" :keymap orgtbl-mode-map
3479 (org-load-modules-maybe)
3480 (cond
3481 ((org-mode-p)
3482 ;; Exit without error, in case some hook functions calls this
3483 ;; by accident in org-mode.
3484 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
3485 (orgtbl-mode
3486 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
3487 ;; Make sure we are first in minor-mode-map-alist
3488 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
3489 ;; FIXME: maybe it should use emulation-mode-map-alists?
3490 (and c (setq minor-mode-map-alist
3491 (cons c (delq c minor-mode-map-alist)))))
3492 (org-set-local (quote org-table-may-need-update) t)
3493 (org-add-hook 'before-change-functions 'org-before-change-function
3494 nil 'local)
3495 (org-set-local 'org-old-auto-fill-inhibit-regexp
3496 auto-fill-inhibit-regexp)
3497 (org-set-local 'auto-fill-inhibit-regexp
3498 (if auto-fill-inhibit-regexp
3499 (concat orgtbl-line-start-regexp "\\|"
3500 auto-fill-inhibit-regexp)
3501 orgtbl-line-start-regexp))
3502 (add-to-invisibility-spec '(org-cwidth))
3503 (when (fboundp 'font-lock-add-keywords)
3504 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
3505 (org-restart-font-lock))
3506 (easy-menu-add orgtbl-mode-menu))
3508 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
3509 (org-table-cleanup-narrow-column-properties)
3510 (org-remove-from-invisibility-spec '(org-cwidth))
3511 (remove-hook 'before-change-functions 'org-before-change-function t)
3512 (when (fboundp 'font-lock-remove-keywords)
3513 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
3514 (org-restart-font-lock))
3515 (easy-menu-remove orgtbl-mode-menu)
3516 (force-mode-line-update 'all))))
3518 (defun org-table-cleanup-narrow-column-properties ()
3519 "Remove all properties related to narrow-column invisibility."
3520 (let ((s 1))
3521 (while (setq s (text-property-any s (point-max)
3522 'display org-narrow-column-arrow))
3523 (remove-text-properties s (1+ s) '(display t)))
3524 (setq s 1)
3525 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
3526 (remove-text-properties s (1+ s) '(org-cwidth t)))
3527 (setq s 1)
3528 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
3529 (remove-text-properties s (1+ s) '(invisible t)))))
3531 (defun orgtbl-make-binding (fun n &rest keys)
3532 "Create a function for binding in the table minor mode.
3533 FUN is the command to call inside a table. N is used to create a unique
3534 command name. KEYS are keys that should be checked in for a command
3535 to execute outside of tables."
3536 (eval
3537 (list 'defun
3538 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
3539 '(arg)
3540 (concat "In tables, run `" (symbol-name fun) "'.\n"
3541 "Outside of tables, run the binding of `"
3542 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
3543 "'.")
3544 '(interactive "p")
3545 (list 'if
3546 '(org-at-table-p)
3547 (list 'call-interactively (list 'quote fun))
3548 (list 'let '(orgtbl-mode)
3549 (list 'call-interactively
3550 (append '(or)
3551 (mapcar (lambda (k)
3552 (list 'key-binding k))
3553 keys)
3554 '('orgtbl-error))))))))
3556 (defun orgtbl-error ()
3557 "Error when there is no default binding for a table key."
3558 (interactive)
3559 (error "This key has no function outside tables"))
3561 (defun orgtbl-setup ()
3562 "Setup orgtbl keymaps."
3563 (let ((nfunc 0)
3564 (bindings
3565 '(([(meta shift left)] org-table-delete-column)
3566 ([(meta left)] org-table-move-column-left)
3567 ([(meta right)] org-table-move-column-right)
3568 ([(meta shift right)] org-table-insert-column)
3569 ([(meta shift up)] org-table-kill-row)
3570 ([(meta shift down)] org-table-insert-row)
3571 ([(meta up)] org-table-move-row-up)
3572 ([(meta down)] org-table-move-row-down)
3573 ("\C-c\C-w" org-table-cut-region)
3574 ("\C-c\M-w" org-table-copy-region)
3575 ("\C-c\C-y" org-table-paste-rectangle)
3576 ("\C-c-" org-table-insert-hline)
3577 ("\C-c}" org-table-toggle-coordinate-overlays)
3578 ("\C-c{" org-table-toggle-formula-debugger)
3579 ("\C-m" org-table-next-row)
3580 ([(shift return)] org-table-copy-down)
3581 ("\C-c?" org-table-field-info)
3582 ("\C-c " org-table-blank-field)
3583 ("\C-c+" org-table-sum)
3584 ("\C-c=" org-table-eval-formula)
3585 ("\C-c'" org-table-edit-formulas)
3586 ("\C-c`" org-table-edit-field)
3587 ("\C-c*" org-table-recalculate)
3588 ("\C-c^" org-table-sort-lines)
3589 ("\M-a" org-table-beginning-of-field)
3590 ("\M-e" org-table-end-of-field)
3591 ([(control ?#)] org-table-rotate-recalc-marks)))
3592 elt key fun cmd)
3593 (while (setq elt (pop bindings))
3594 (setq nfunc (1+ nfunc))
3595 (setq key (org-key (car elt))
3596 fun (nth 1 elt)
3597 cmd (orgtbl-make-binding fun nfunc key))
3598 (org-defkey orgtbl-mode-map key cmd))
3600 ;; Special treatment needed for TAB and RET
3601 (org-defkey orgtbl-mode-map [(return)]
3602 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
3603 (org-defkey orgtbl-mode-map "\C-m"
3604 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
3606 (org-defkey orgtbl-mode-map [(tab)]
3607 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
3608 (org-defkey orgtbl-mode-map "\C-i"
3609 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
3611 (org-defkey orgtbl-mode-map [(shift tab)]
3612 (orgtbl-make-binding 'org-table-previous-field 104
3613 [(shift tab)] [(tab)] "\C-i"))
3616 (unless (featurep 'xemacs)
3617 (org-defkey orgtbl-mode-map [S-iso-lefttab]
3618 (orgtbl-make-binding 'org-table-previous-field 107
3619 [S-iso-lefttab] [backtab] [(shift tab)]
3620 [(tab)] "\C-i")))
3622 (org-defkey orgtbl-mode-map [backtab]
3623 (orgtbl-make-binding 'org-table-previous-field 108
3624 [backtab] [S-iso-lefttab] [(shift tab)]
3625 [(tab)] "\C-i"))
3627 (org-defkey orgtbl-mode-map "\M-\C-m"
3628 (orgtbl-make-binding 'org-table-wrap-region 105
3629 "\M-\C-m" [(meta return)]))
3630 (org-defkey orgtbl-mode-map [(meta return)]
3631 (orgtbl-make-binding 'org-table-wrap-region 106
3632 [(meta return)] "\M-\C-m"))
3634 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
3635 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
3637 (when orgtbl-optimized
3638 ;; If the user wants maximum table support, we need to hijack
3639 ;; some standard editing functions
3640 (org-remap orgtbl-mode-map
3641 'self-insert-command 'orgtbl-self-insert-command
3642 'delete-char 'org-delete-char
3643 'delete-backward-char 'org-delete-backward-char)
3644 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
3645 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
3646 '("OrgTbl"
3647 ["Create or convert" org-table-create-or-convert-from-region
3648 :active (not (org-at-table-p)) :keys "C-c |" ]
3649 "--"
3650 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
3651 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
3652 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
3653 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
3654 "--"
3655 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
3656 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
3657 ["Copy Field from Above"
3658 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
3659 "--"
3660 ("Column"
3661 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
3662 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
3663 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
3664 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
3665 ("Row"
3666 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
3667 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
3668 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
3669 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
3670 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
3671 "--"
3672 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
3673 ("Rectangle"
3674 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
3675 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
3676 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
3677 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
3678 "--"
3679 ("Radio tables"
3680 ["Insert table template" orgtbl-insert-radio-table
3681 (assq major-mode orgtbl-radio-table-templates)]
3682 ["Comment/uncomment table" orgtbl-toggle-comment t])
3683 "--"
3684 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
3685 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
3686 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
3687 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
3688 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
3689 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
3690 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
3691 ["Sum Column/Rectangle" org-table-sum
3692 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
3693 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
3694 ["Debug Formulas"
3695 org-table-toggle-formula-debugger :active (org-at-table-p)
3696 :keys "C-c {"
3697 :style toggle :selected org-table-formula-debug]
3698 ["Show Col/Row Numbers"
3699 org-table-toggle-coordinate-overlays :active (org-at-table-p)
3700 :keys "C-c }"
3701 :style toggle :selected org-table-overlay-coordinates]
3705 (defun orgtbl-ctrl-c-ctrl-c (arg)
3706 "If the cursor is inside a table, realign the table.
3707 If it is a table to be sent away to a receiver, do it.
3708 With prefix arg, also recompute table."
3709 (interactive "P")
3710 (let ((pos (point)) action)
3711 (save-excursion
3712 (beginning-of-line 1)
3713 (setq action (cond ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
3714 ((looking-at "[ \t]*|") pos)
3715 ((looking-at "[ \t]*#\\+TBLFM:") 'recalc))))
3716 (cond
3717 ((integerp action)
3718 (goto-char action)
3719 (org-table-maybe-eval-formula)
3720 (if arg
3721 (call-interactively 'org-table-recalculate)
3722 (org-table-maybe-recalculate-line))
3723 (call-interactively 'org-table-align)
3724 (orgtbl-send-table 'maybe))
3725 ((eq action 'recalc)
3726 (save-excursion
3727 (beginning-of-line 1)
3728 (skip-chars-backward " \r\n\t")
3729 (if (org-at-table-p)
3730 (org-call-with-arg 'org-table-recalculate t))))
3731 (t (let (orgtbl-mode)
3732 (call-interactively (key-binding "\C-c\C-c")))))))
3734 (defun orgtbl-create-or-convert-from-region (arg)
3735 "Create table or convert region to table, if no conflicting binding.
3736 This installs the table binding `C-c |', but only if there is no
3737 conflicting binding to this key outside orgtbl-mode."
3738 (interactive "P")
3739 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
3740 (if cmd
3741 (call-interactively cmd)
3742 (call-interactively 'org-table-create-or-convert-from-region))))
3744 (defun orgtbl-tab (arg)
3745 "Justification and field motion for `orgtbl-mode'."
3746 (interactive "P")
3747 (if arg (org-table-edit-field t)
3748 (org-table-justify-field-maybe)
3749 (org-table-next-field)))
3751 (defun orgtbl-ret ()
3752 "Justification and field motion for `orgtbl-mode'."
3753 (interactive)
3754 (if (bobp)
3755 (newline)
3756 (org-table-justify-field-maybe)
3757 (org-table-next-row)))
3759 (defun orgtbl-self-insert-command (N)
3760 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
3761 If the cursor is in a table looking at whitespace, the whitespace is
3762 overwritten, and the table is not marked as requiring realignment."
3763 (interactive "p")
3764 (if (and (org-at-table-p)
3766 (and org-table-auto-blank-field
3767 (member last-command
3768 '(orgtbl-hijacker-command-100
3769 orgtbl-hijacker-command-101
3770 orgtbl-hijacker-command-102
3771 orgtbl-hijacker-command-103
3772 orgtbl-hijacker-command-104
3773 orgtbl-hijacker-command-105
3774 yas/expand))
3775 (org-table-blank-field))
3777 (eq N 1)
3778 (looking-at "[^|\n]* +|"))
3779 (let (org-table-may-need-update)
3780 (goto-char (1- (match-end 0)))
3781 (delete-backward-char 1)
3782 (goto-char (match-beginning 0))
3783 (self-insert-command N))
3784 (setq org-table-may-need-update t)
3785 (let* (orgtbl-mode
3787 (cmd (or (key-binding
3788 (or (and (listp function-key-map)
3789 (setq a (assoc last-input-event function-key-map))
3790 (cdr a))
3791 (vector last-input-event)))
3792 'self-insert-command)))
3793 (call-interactively cmd)
3794 (if (and org-self-insert-cluster-for-undo
3795 (eq cmd 'self-insert-command))
3796 (if (not (eq last-command 'orgtbl-self-insert-command))
3797 (setq org-self-insert-command-undo-counter 1)
3798 (if (>= org-self-insert-command-undo-counter 20)
3799 (setq org-self-insert-command-undo-counter 1)
3800 (and (> org-self-insert-command-undo-counter 0)
3801 buffer-undo-list
3802 (not (cadr buffer-undo-list)) ; remove nil entry
3803 (setcdr buffer-undo-list (cddr buffer-undo-list)))
3804 (setq org-self-insert-command-undo-counter
3805 (1+ org-self-insert-command-undo-counter))))))))
3807 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
3808 "Regular expression matching exponentials as produced by calc.")
3810 (defun orgtbl-export (table target)
3811 (require 'org-exp)
3812 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
3813 (lines (org-split-string table "[ \t]*\n[ \t]*"))
3814 org-table-last-alignment org-table-last-column-widths
3815 maxcol column)
3816 (if (not (fboundp func))
3817 (error "Cannot export orgtbl table to %s" target))
3818 (setq lines (org-table-clean-before-export lines))
3819 (setq table
3820 (mapcar
3821 (lambda (x)
3822 (if (string-match org-table-hline-regexp x)
3823 'hline
3824 (org-split-string (org-trim x) "\\s-*|\\s-*")))
3825 lines))
3826 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
3827 table)))
3828 (loop for i from (1- maxcol) downto 0 do
3829 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
3830 (setq column (delq nil column))
3831 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
3832 (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))
3833 (funcall func table nil)))
3835 (defun orgtbl-gather-send-defs ()
3836 "Gather a plist of :name, :transform, :params for each destination before
3837 a radio table."
3838 (save-excursion
3839 (goto-char (org-table-begin))
3840 (let (rtn)
3841 (beginning-of-line 0)
3842 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
3843 (let ((name (org-no-properties (match-string 1)))
3844 (transform (intern (match-string 2)))
3845 (params (if (match-end 3)
3846 (read (concat "(" (match-string 3) ")")))))
3847 (push (list :name name :transform transform :params params)
3848 rtn)
3849 (beginning-of-line 0)))
3850 rtn)))
3852 (defun orgtbl-send-replace-tbl (name txt)
3853 "Find and replace table NAME with TXT."
3854 (save-excursion
3855 (goto-char (point-min))
3856 (unless (re-search-forward
3857 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
3858 (error "Don't know where to insert translated table"))
3859 (goto-char (match-beginning 0))
3860 (beginning-of-line 2)
3861 (save-excursion
3862 (let ((beg (point)))
3863 (unless (re-search-forward
3864 (concat "END RECEIVE ORGTBL +" name) nil t)
3865 (error "Cannot find end of insertion region"))
3866 (beginning-of-line 1)
3867 (delete-region beg (point))))
3868 (insert txt "\n")))
3870 ;;;###autoload
3871 (defun org-table-to-lisp (&optional txt)
3872 "Convert the table at point to a Lisp structure.
3873 The structure will be a list. Each item is either the symbol `hline'
3874 for a horizontal separator line, or a list of field values as strings.
3875 The table is taken from the parameter TXT, or from the buffer at point."
3876 (unless txt
3877 (unless (org-at-table-p)
3878 (error "No table at point")))
3879 (let* ((txt (or txt
3880 (buffer-substring-no-properties (org-table-begin)
3881 (org-table-end))))
3882 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
3884 (mapcar
3885 (lambda (x)
3886 (if (string-match org-table-hline-regexp x)
3887 'hline
3888 (org-split-string (org-trim x) "\\s-*|\\s-*")))
3889 lines)))
3891 (defun orgtbl-send-table (&optional maybe)
3892 "Send a transformed version of this table to the receiver position.
3893 With argument MAYBE, fail quietly if no transformation is defined for
3894 this table."
3895 (interactive)
3896 (catch 'exit
3897 (unless (org-at-table-p) (error "Not at a table"))
3898 ;; when non-interactive, we assume align has just happened.
3899 (when (interactive-p) (org-table-align))
3900 (let ((dests (orgtbl-gather-send-defs))
3901 (txt (buffer-substring-no-properties (org-table-begin)
3902 (org-table-end)))
3903 (ntbl 0))
3904 (unless dests (if maybe (throw 'exit nil)
3905 (error "Don't know how to transform this table")))
3906 (dolist (dest dests)
3907 (let* ((name (plist-get dest :name))
3908 (transform (plist-get dest :transform))
3909 (params (plist-get dest :params))
3910 (skip (plist-get params :skip))
3911 (skipcols (plist-get params :skipcols))
3913 (lines (org-table-clean-before-export
3914 (nthcdr (or skip 0)
3915 (org-split-string txt "[ \t]*\n[ \t]*"))))
3916 (i0 (if org-table-clean-did-remove-column 2 1))
3917 (table (mapcar
3918 (lambda (x)
3919 (if (string-match org-table-hline-regexp x)
3920 'hline
3921 (org-remove-by-index
3922 (org-split-string (org-trim x) "\\s-*|\\s-*")
3923 skipcols i0)))
3924 lines))
3925 (fun (if (= i0 2) 'cdr 'identity))
3926 (org-table-last-alignment
3927 (org-remove-by-index (funcall fun org-table-last-alignment)
3928 skipcols i0))
3929 (org-table-last-column-widths
3930 (org-remove-by-index (funcall fun org-table-last-column-widths)
3931 skipcols i0))
3932 (txt (if (fboundp transform)
3933 (funcall transform table params)
3934 (error "No such transformation function %s" transform))))
3935 (orgtbl-send-replace-tbl name txt))
3936 (setq ntbl (1+ ntbl)))
3937 (message "Table converted and installed at %d receiver location%s"
3938 ntbl (if (> ntbl 1) "s" "")))))
3940 (defun org-remove-by-index (list indices &optional i0)
3941 "Remove the elements in LIST with indices in INDICES.
3942 First element has index 0, or I0 if given."
3943 (if (not indices)
3944 list
3945 (if (integerp indices) (setq indices (list indices)))
3946 (setq i0 (1- (or i0 0)))
3947 (delq :rm (mapcar (lambda (x)
3948 (setq i0 (1+ i0))
3949 (if (memq i0 indices) :rm x))
3950 list))))
3952 (defun orgtbl-toggle-comment ()
3953 "Comment or uncomment the orgtbl at point."
3954 (interactive)
3955 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
3956 (re2 (concat "^" orgtbl-line-start-regexp))
3957 (commented (save-excursion (beginning-of-line 1)
3958 (cond ((looking-at re1) t)
3959 ((looking-at re2) nil)
3960 (t (error "Not at an org table")))))
3961 (re (if commented re1 re2))
3962 beg end)
3963 (save-excursion
3964 (beginning-of-line 1)
3965 (while (looking-at re) (beginning-of-line 0))
3966 (beginning-of-line 2)
3967 (setq beg (point))
3968 (while (looking-at re) (beginning-of-line 2))
3969 (setq end (point)))
3970 (comment-region beg end (if commented '(4) nil))))
3972 (defun orgtbl-insert-radio-table ()
3973 "Insert a radio table template appropriate for this major mode."
3974 (interactive)
3975 (let* ((e (assq major-mode orgtbl-radio-table-templates))
3976 (txt (nth 1 e))
3977 name pos)
3978 (unless e (error "No radio table setup defined for %s" major-mode))
3979 (setq name (read-string "Table name: "))
3980 (while (string-match "%n" txt)
3981 (setq txt (replace-match name t t txt)))
3982 (or (bolp) (insert "\n"))
3983 (setq pos (point))
3984 (insert txt)
3985 (goto-char pos)))
3987 ;; Dynamically bound input and output for table formatting.
3988 (defvar *orgtbl-table* nil
3989 "Carries the current table through formatting routines.")
3990 (defvar *orgtbl-rtn* nil
3991 "Formatting routines push the output lines here.")
3992 ;; Formatting parameters for the current table section.
3993 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
3994 (defvar *orgtbl-sep* nil "Text used as a column separator.")
3995 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
3996 (defvar *orgtbl-fmt* nil "Format for each entry.")
3997 (defvar *orgtbl-efmt* nil "Format for numbers.")
3998 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
3999 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4000 (defvar *orgtbl-lstart* nil "Text starting a row.")
4001 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4002 (defvar *orgtbl-lend* nil "Text ending a row.")
4003 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4005 (defsubst orgtbl-get-fmt (fmt i)
4006 "Retrieve the format from FMT corresponding to the Ith column."
4007 (if (and (not (functionp fmt)) (consp fmt))
4008 (plist-get fmt i)
4009 fmt))
4011 (defsubst orgtbl-apply-fmt (fmt &rest args)
4012 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4013 (cond ((functionp fmt) (apply fmt args))
4014 (fmt (apply 'format fmt args))
4015 (args (car args))
4016 (t args)))
4018 (defsubst orgtbl-eval-str (str)
4019 "If STR is a function, evaluate it with no arguments."
4020 (if (functionp str)
4021 (funcall str)
4022 str))
4024 (defun orgtbl-format-line (line)
4025 "Format LINE as a table row."
4026 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4027 (let* ((i 0)
4028 (line
4029 (mapcar
4030 (lambda (f)
4031 (setq i (1+ i))
4032 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4033 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4034 (orgtbl-apply-fmt efmt (match-string 1 f)
4035 (match-string 2 f))
4036 f)))
4037 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4038 *orgtbl-default-fmt*)
4039 f)))
4040 line)))
4041 (push (if *orgtbl-lfmt*
4042 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4043 (concat (orgtbl-eval-str *orgtbl-lstart*)
4044 (mapconcat 'identity line *orgtbl-sep*)
4045 (orgtbl-eval-str *orgtbl-lend*)))
4046 *orgtbl-rtn*))))
4048 (defun orgtbl-format-section (section-stopper)
4049 "Format lines until the first occurrence of SECTION-STOPPER."
4050 (let (prevline)
4051 (progn
4052 (while (not (eq (car *orgtbl-table*) section-stopper))
4053 (if prevline (orgtbl-format-line prevline))
4054 (setq prevline (pop *orgtbl-table*)))
4055 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4056 (*orgtbl-lend* *orgtbl-llend*)
4057 (*orgtbl-lfmt* *orgtbl-llfmt*))
4058 (orgtbl-format-line prevline))))))
4060 (defun orgtbl-to-generic (table params)
4061 "Convert the orgtbl-mode TABLE to some other format.
4062 This generic routine can be used for many standard cases.
4063 TABLE is a list, each entry either the symbol `hline' for a horizontal
4064 separator line, or a list of fields for that line.
4065 PARAMS is a property list of parameters that can influence the conversion.
4066 For the generic converter, some parameters are obligatory: You need to
4067 specify either :lfmt, or all of (:lstart :lend :sep).
4069 Valid parameters are
4071 :splice When set to t, return only table body lines, don't wrap
4072 them into :tstart and :tend. Default is nil. When :splice
4073 is non-nil, this also means that the exporter should not look
4074 for and interpret header and footer sections.
4076 :hline String to be inserted on horizontal separation lines.
4077 May be nil to ignore hlines.
4079 :sep Separator between two fields
4080 :remove-nil-lines Do not include lines that evaluate to nil.
4083 Each in the following group may be either a string or a function
4084 of no arguments returning a string:
4085 :tstart String to start the table. Ignored when :splice is t.
4086 :tend String to end the table. Ignored when :splice is t.
4087 :lstart String to start a new table line.
4088 :llstart String to start the last table line, defaults to :lstart.
4089 :lend String to end a table line
4090 :llend String to end the last table line, defaults to :lend.
4092 Each in the following group may be a string, a function of one
4093 argument (the field or line) returning a string, or a plist
4094 mapping columns to either of the above:
4095 :lfmt Format for entire line, with enough %s to capture all fields.
4096 If this is present, :lstart, :lend, and :sep are ignored.
4097 :llfmt Format for the entire last line, defaults to :lfmt.
4098 :fmt A format to be used to wrap the field, should contain
4099 %s for the original field value. For example, to wrap
4100 everything in dollars, you could use :fmt \"$%s$\".
4101 This may also be a property list with column numbers and
4102 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4104 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4105 Same as above, specific for the header lines in the table.
4106 All lines before the first hline are treated as header.
4107 If any of these is not present, the data line value is used.
4109 This may be either a string or a function of two arguments:
4110 :efmt Use this format to print numbers with exponentials.
4111 The format should have %s twice for inserting mantissa
4112 and exponent, for example \"%s\\\\times10^{%s}\". This
4113 may also be a property list with column numbers and
4114 formats. :fmt will still be applied after :efmt.
4116 In addition to this, the parameters :skip and :skipcols are always handled
4117 directly by `orgtbl-send-table'. See manual."
4118 (interactive)
4120 (let* ((splicep (plist-get params :splice))
4121 (hline (plist-get params :hline))
4122 (remove-nil-linesp (plist-get params :remove-nil-lines))
4123 (remove-newlines (plist-get params :remove-newlines))
4124 (*orgtbl-hline* hline)
4125 (*orgtbl-table* table)
4126 (*orgtbl-sep* (plist-get params :sep))
4127 (*orgtbl-efmt* (plist-get params :efmt))
4128 (*orgtbl-lstart* (plist-get params :lstart))
4129 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4130 (*orgtbl-lend* (plist-get params :lend))
4131 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4132 (*orgtbl-lfmt* (plist-get params :lfmt))
4133 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4134 (*orgtbl-fmt* (plist-get params :fmt))
4135 *orgtbl-rtn*)
4137 ;; Put header
4138 (unless splicep
4139 (when (plist-member params :tstart)
4140 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4141 (if tstart (push tstart *orgtbl-rtn*)))))
4143 ;; Do we have a heading section? If so, format it and handle the
4144 ;; trailing hline.
4145 (if (and (not splicep)
4146 (or (consp (car *orgtbl-table*))
4147 (consp (nth 1 *orgtbl-table*)))
4148 (memq 'hline (cdr *orgtbl-table*)))
4149 (progn
4150 (when (eq 'hline (car *orgtbl-table*))
4151 ;; there is a hline before the first data line
4152 (and hline (push hline *orgtbl-rtn*))
4153 (pop *orgtbl-table*))
4154 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4155 *orgtbl-lstart*))
4156 (*orgtbl-llstart* (or (plist-get params :hllstart)
4157 *orgtbl-llstart*))
4158 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4159 (*orgtbl-llend* (or (plist-get params :hllend)
4160 (plist-get params :hlend) *orgtbl-llend*))
4161 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4162 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4163 (plist-get params :hlfmt) *orgtbl-llfmt*))
4164 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4165 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4166 (orgtbl-format-section 'hline))
4167 (if hline (push hline *orgtbl-rtn*))
4168 (pop *orgtbl-table*)))
4170 ;; Now format the main section.
4171 (orgtbl-format-section nil)
4173 (unless splicep
4174 (when (plist-member params :tend)
4175 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4176 (if tend (push tend *orgtbl-rtn*)))))
4178 (mapconcat (if remove-newlines
4179 (lambda (tend)
4180 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4181 'identity)
4182 (nreverse (if remove-nil-linesp
4183 (remq nil *orgtbl-rtn*)
4184 *orgtbl-rtn*)) "\n")))
4186 (defun orgtbl-to-tsv (table params)
4187 "Convert the orgtbl-mode table to TAB separated material."
4188 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4189 (defun orgtbl-to-csv (table params)
4190 "Convert the orgtbl-mode table to CSV material.
4191 This does take care of the proper quoting of fields with comma or quotes."
4192 (orgtbl-to-generic table (org-combine-plists
4193 '(:sep "," :fmt org-quote-csv-field)
4194 params)))
4196 (defun orgtbl-to-latex (table params)
4197 "Convert the orgtbl-mode TABLE to LaTeX.
4198 TABLE is a list, each entry either the symbol `hline' for a horizontal
4199 separator line, or a list of fields for that line.
4200 PARAMS is a property list of parameters that can influence the conversion.
4201 Supports all parameters from `orgtbl-to-generic'. Most important for
4202 LaTeX are:
4204 :splice When set to t, return only table body lines, don't wrap
4205 them into a tabular environment. Default is nil.
4207 :fmt A format to be used to wrap the field, should contain %s for the
4208 original field value. For example, to wrap everything in dollars,
4209 use :fmt \"$%s$\". This may also be a property list with column
4210 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4211 The format may also be a function that formats its one argument.
4213 :efmt Format for transforming numbers with exponentials. The format
4214 should have %s twice for inserting mantissa and exponent, for
4215 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4216 This may also be a property list with column numbers and formats.
4217 The format may also be a function that formats its two arguments.
4219 :llend If you find too much space below the last line of a table,
4220 pass a value of \"\" for :llend to suppress the final \\\\.
4222 The general parameters :skip and :skipcols have already been applied when
4223 this function is called."
4224 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4225 org-table-last-alignment ""))
4226 (params2
4227 (list
4228 :tstart (concat "\\begin{tabular}{" alignment "}")
4229 :tend "\\end{tabular}"
4230 :lstart "" :lend " \\\\" :sep " & "
4231 :efmt "%s\\,(%s)" :hline "\\hline")))
4232 (orgtbl-to-generic table (org-combine-plists params2 params))))
4234 (defun orgtbl-to-html (table params)
4235 "Convert the orgtbl-mode TABLE to HTML.
4236 TABLE is a list, each entry either the symbol `hline' for a horizontal
4237 separator line, or a list of fields for that line.
4238 PARAMS is a property list of parameters that can influence the conversion.
4239 Currently this function recognizes the following parameters:
4241 :splice When set to t, return only table body lines, don't wrap
4242 them into a <table> environment. Default is nil.
4244 The general parameters :skip and :skipcols have already been applied when
4245 this function is called. The function does *not* use `orgtbl-to-generic',
4246 so you cannot specify parameters for it."
4247 (let* ((splicep (plist-get params :splice))
4248 (html-table-tag org-export-html-table-tag)
4249 html)
4250 ;; Just call the formatter we already have
4251 ;; We need to make text lines for it, so put the fields back together.
4252 (setq html (org-format-org-table-html
4253 (mapcar
4254 (lambda (x)
4255 (if (eq x 'hline)
4256 "|----+----|"
4257 (concat "| " (mapconcat 'identity x " | ") " |")))
4258 table)
4259 splicep))
4260 (if (string-match "\n+\\'" html)
4261 (setq html (replace-match "" t t html)))
4262 html))
4264 (defun orgtbl-to-texinfo (table params)
4265 "Convert the orgtbl-mode TABLE to TeXInfo.
4266 TABLE is a list, each entry either the symbol `hline' for a horizontal
4267 separator line, or a list of fields for that line.
4268 PARAMS is a property list of parameters that can influence the conversion.
4269 Supports all parameters from `orgtbl-to-generic'. Most important for
4270 TeXInfo are:
4272 :splice nil/t When set to t, return only table body lines, don't wrap
4273 them into a multitable environment. Default is nil.
4275 :fmt fmt A format to be used to wrap the field, should contain
4276 %s for the original field value. For example, to wrap
4277 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4278 This may also be a property list with column numbers and
4279 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4280 Each format also may be a function that formats its one
4281 argument.
4283 :cf \"f1 f2..\" The column fractions for the table. By default these
4284 are computed automatically from the width of the columns
4285 under org-mode.
4287 The general parameters :skip and :skipcols have already been applied when
4288 this function is called."
4289 (let* ((total (float (apply '+ org-table-last-column-widths)))
4290 (colfrac (or (plist-get params :cf)
4291 (mapconcat
4292 (lambda (x) (format "%.3f" (/ (float x) total)))
4293 org-table-last-column-widths " ")))
4294 (params2
4295 (list
4296 :tstart (concat "@multitable @columnfractions " colfrac)
4297 :tend "@end multitable"
4298 :lstart "@item " :lend "" :sep " @tab "
4299 :hlstart "@headitem ")))
4300 (orgtbl-to-generic table (org-combine-plists params2 params))))
4302 (defun orgtbl-to-orgtbl (table params)
4303 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4304 Useful when slicing one table into many. The :hline, :sep,
4305 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4306 and :tend suppress strings without splicing; they can be set to
4307 provide ORGTBL directives for the generated table."
4308 (let* ((params2
4309 (list
4310 :remove-newlines t
4311 :tstart nil :tend nil
4312 :hline "|---"
4313 :sep " | "
4314 :lstart "| "
4315 :lend " |"))
4316 (params (org-combine-plists params2 params)))
4317 (orgtbl-to-generic table params)))
4319 (defun org-table-get-remote-range (name-or-id form)
4320 "Get a field value or a list of values in a range from table at ID.
4322 NAME-OR-ID may be the name of a table in the current file as set by
4323 a \"#+TBLNAME:\" directive. The first table following this line
4324 will then be used. Alternatively, it may be an ID referring to
4325 any entry, also in a different file. In this case, the first table
4326 in that entry will be referenced.
4327 FORM is a field or range descriptor like \"@2$3\" or or \"B3\" or
4328 \"@I$2..@II$2\". All the references must be absolute, not relative.
4330 The return value is either a single string for a single field, or a
4331 list of the fields in the rectangle ."
4332 (save-match-data
4333 (let ((id-loc nil)
4334 org-table-column-names org-table-column-name-regexp
4335 org-table-local-parameters org-table-named-field-locations
4336 org-table-current-line-types org-table-current-begin-line
4337 org-table-current-begin-pos org-table-dlines
4338 org-table-hlines org-table-last-alignment
4339 org-table-last-column-widths org-table-last-alignment
4340 org-table-last-column-widths tbeg
4341 buffer loc)
4342 (setq form (org-table-convert-refs-to-rc form))
4343 (save-excursion
4344 (save-restriction
4345 (widen)
4346 (save-excursion
4347 (goto-char (point-min))
4348 (if (re-search-forward
4349 (concat "^[ \t]*#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4350 nil t)
4351 (setq buffer (current-buffer) loc (match-beginning 0))
4352 (setq id-loc (org-id-find name-or-id 'marker))
4353 (unless (and id-loc (markerp id-loc))
4354 (error "Can't find remote table \"%s\"" name-or-id))
4355 (setq buffer (marker-buffer id-loc)
4356 loc (marker-position id-loc))
4357 (move-marker id-loc nil)))
4358 (with-current-buffer buffer
4359 (save-excursion
4360 (save-restriction
4361 (widen)
4362 (goto-char loc)
4363 (forward-char 1)
4364 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4365 (not (match-beginning 1)))
4366 (error "Cannot find a table at NAME or ID %s" name-or-id))
4367 (setq tbeg (point-at-bol))
4368 (org-table-get-specials)
4369 (setq form (org-table-formula-substitute-names form))
4370 (if (and (string-match org-table-range-regexp form)
4371 (> (length (match-string 0 form)) 1))
4372 (save-match-data
4373 (org-table-get-range (match-string 0 form) tbeg 1))
4374 form)))))))))
4376 (provide 'org-table)
4378 ;; arch-tag: 4d21cfdd-0268-440a-84b0-09237a0fe0ef
4380 ;;; org-table.el ends here