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