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