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