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