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