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