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