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