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