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