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