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