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