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