Minor fix
[org-mode.git] / lisp / org-table.el
blob7f96cca5b86776a8d045696b89befba2a980012f
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 'from
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-lastrc (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 "\\`$>" a)
1979 ;; Fake a high number to make sure this is sorted at the end.
1980 (setq a (org-table-formula-handle-lastrc a))
1981 (setq a (format "$%d" (+ 10000 (string-to-number (substring a 1))))))
1982 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
1983 (concat
1984 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
1985 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
1986 (if (match-end 5) (concat "@@" (match-string 5 a))))))
1988 (defun org-table-formula-less-p (a b)
1989 "Compare two formulas for sorting."
1990 (let ((as (org-table-formula-make-cmp-string (car a)))
1991 (bs (org-table-formula-make-cmp-string (car b))))
1992 (and as bs (string< as bs))))
1994 (defun org-table-get-stored-formulas (&optional noerror)
1995 "Return an alist with the stored formulas directly after current table."
1996 (interactive)
1997 (let (scol eq eq-alist strings string seen)
1998 (save-excursion
1999 (goto-char (org-table-end))
2000 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
2001 (setq strings (org-split-string (org-match-string-no-properties 2)
2002 " *:: *"))
2003 (while (setq string (pop strings))
2004 (when (string-match "\\`\\(@[-+I>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|>\\(?:[-+][0-9]+\\)?\\)\\) *= *\\(.*[^ \t]\\)" string)
2005 (setq scol (if (match-end 2)
2006 (match-string 2 string)
2007 (match-string 1 string))
2008 scol (if (= (string-to-char scol) ?>) (concat "$" scol) scol)
2009 eq (match-string 3 string)
2010 eq-alist (cons (cons scol eq) eq-alist))
2011 (if (member scol seen)
2012 (if noerror
2013 (progn
2014 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
2015 (ding)
2016 (sit-for 2))
2017 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
2018 (push scol seen))))))
2019 (nreverse eq-alist)))
2021 (defun org-table-fix-formulas (key replace &optional limit delta remove)
2022 "Modify the equations after the table structure has been edited.
2023 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2024 For all numbers larger than LIMIT, shift them by DELTA."
2025 (save-excursion
2026 (goto-char (org-table-end))
2027 (when (looking-at "[ \t]*#\\+TBLFM:")
2028 (let ((re (concat key "\\([0-9]+\\)"))
2029 (re2
2030 (when remove
2031 (if (or (equal key "$") (equal key "$LR"))
2032 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2033 (regexp-quote key) remove)
2034 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
2035 s n a)
2036 (when remove
2037 (while (re-search-forward re2 (point-at-eol) t)
2038 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2039 (replace-match ""))))
2040 (while (re-search-forward re (point-at-eol) t)
2041 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2042 (setq s (match-string 1) n (string-to-number s))
2043 (cond
2044 ((setq a (assoc s replace))
2045 (replace-match (concat key (cdr a)) t t))
2046 ((and limit (> n limit))
2047 (replace-match (concat key (int-to-string (+ n delta)))
2048 t t)))))))))
2050 (defun org-table-get-specials ()
2051 "Get the column names and local parameters for this table."
2052 (save-excursion
2053 (let ((beg (org-table-begin)) (end (org-table-end))
2054 names name fields fields1 field cnt
2055 c v l line col types dlines hlines last-dline)
2056 (setq org-table-column-names nil
2057 org-table-local-parameters nil
2058 org-table-named-field-locations nil
2059 org-table-current-begin-line nil
2060 org-table-current-begin-pos nil
2061 org-table-current-line-types nil
2062 org-table-current-ncol 0)
2063 (goto-char beg)
2064 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
2065 (setq names (org-split-string (match-string 1) " *| *")
2066 cnt 1)
2067 (while (setq name (pop names))
2068 (setq cnt (1+ cnt))
2069 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
2070 (push (cons name (int-to-string cnt)) org-table-column-names))))
2071 (setq org-table-column-names (nreverse org-table-column-names))
2072 (setq org-table-column-name-regexp
2073 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
2074 (goto-char beg)
2075 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
2076 (setq fields (org-split-string (match-string 1) " *| *"))
2077 (while (setq field (pop fields))
2078 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
2079 (push (cons (match-string 1 field) (match-string 2 field))
2080 org-table-local-parameters))))
2081 (goto-char beg)
2082 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
2083 (setq c (match-string 1)
2084 fields (org-split-string (match-string 2) " *| *"))
2085 (save-excursion
2086 (beginning-of-line (if (equal c "_") 2 0))
2087 (setq line (org-current-line) col 1)
2088 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2089 (setq fields1 (org-split-string (match-string 1) " *| *"))))
2090 (while (and fields1 (setq field (pop fields)))
2091 (setq v (pop fields1) col (1+ col))
2092 (when (and (stringp field) (stringp v)
2093 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
2094 (push (cons field v) org-table-local-parameters)
2095 (push (list field line col) org-table-named-field-locations))))
2096 ;; Analyse the line types
2097 (goto-char beg)
2098 (setq org-table-current-begin-line (org-current-line)
2099 org-table-current-begin-pos (point)
2100 l org-table-current-begin-line)
2101 (while (looking-at "[ \t]*|\\(-\\)?")
2102 (push (if (match-end 1) 'hline 'dline) types)
2103 (if (match-end 1) (push l hlines) (push l dlines))
2104 (beginning-of-line 2)
2105 (setq l (1+ l)))
2106 (push 'hline types) ;; add an imaginary extra hline to the end
2107 (setq org-table-current-line-types (apply 'vector (nreverse types))
2108 last-dline (car dlines)
2109 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
2110 org-table-hlines (apply 'vector (cons nil (nreverse hlines))))
2111 (org-goto-line last-dline)
2112 (let* ((l last-dline)
2113 (fields (org-split-string
2114 (buffer-substring (point-at-bol) (point-at-eol))
2115 "[ \t]*|[ \t]*"))
2116 (nfields (length fields))
2117 al al2)
2118 (setq org-table-current-ncol nfields)
2119 (loop for i from 1 to nfields do
2120 (push (list (format "LR%d" i) l i) al)
2121 (push (cons (format "LR%d" i) (nth (1- i) fields)) al2))
2122 (setq org-table-named-field-locations
2123 (append org-table-named-field-locations al))
2124 (setq org-table-local-parameters
2125 (append org-table-local-parameters al2))))))
2127 (defun org-table-maybe-eval-formula ()
2128 "Check if the current field starts with \"=\" or \":=\".
2129 If yes, store the formula and apply it."
2130 ;; We already know we are in a table. Get field will only return a formula
2131 ;; when appropriate. It might return a separator line, but no problem.
2132 (when org-table-formula-evaluate-inline
2133 (let* ((field (org-trim (or (org-table-get-field) "")))
2134 named eq)
2135 (when (string-match "^:?=\\(.*\\)" field)
2136 (setq named (equal (string-to-char field) ?:)
2137 eq (match-string 1 field))
2138 (if (or (fboundp 'calc-eval)
2139 (equal (substring eq 0 (min 2 (length eq))) "'("))
2140 (org-table-eval-formula (if named '(4) nil)
2141 (org-table-formula-from-user eq))
2142 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2144 (defvar org-recalc-commands nil
2145 "List of commands triggering the recalculation of a line.
2146 Will be filled automatically during use.")
2148 (defvar org-recalc-marks
2149 '((" " . "Unmarked: no special line, no automatic recalculation")
2150 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2151 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
2152 ("!" . "Column name definition line. Reference in formula as $name.")
2153 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
2154 ("_" . "Names for values in row below this one.")
2155 ("^" . "Names for values in row above this one.")))
2157 (defun org-table-rotate-recalc-marks (&optional newchar)
2158 "Rotate the recalculation mark in the first column.
2159 If in any row, the first field is not consistent with a mark,
2160 insert a new column for the markers.
2161 When there is an active region, change all the lines in the region,
2162 after prompting for the marking character.
2163 After each change, a message will be displayed indicating the meaning
2164 of the new mark."
2165 (interactive)
2166 (unless (org-at-table-p) (error "Not at a table"))
2167 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
2168 (beg (org-table-begin))
2169 (end (org-table-end))
2170 (l (org-current-line))
2171 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2172 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2173 (have-col
2174 (save-excursion
2175 (goto-char beg)
2176 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
2177 (col (org-table-current-column))
2178 (forcenew (car (assoc newchar org-recalc-marks)))
2179 epos new)
2180 (when l1
2181 (message "Change region to what mark? Type # * ! $ or SPC: ")
2182 (setq newchar (char-to-string (read-char-exclusive))
2183 forcenew (car (assoc newchar org-recalc-marks))))
2184 (if (and newchar (not forcenew))
2185 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2186 newchar))
2187 (if l1 (org-goto-line l1))
2188 (save-excursion
2189 (beginning-of-line 1)
2190 (unless (looking-at org-table-dataline-regexp)
2191 (error "Not at a table data line")))
2192 (unless have-col
2193 (org-table-goto-column 1)
2194 (org-table-insert-column)
2195 (org-table-goto-column (1+ col)))
2196 (setq epos (point-at-eol))
2197 (save-excursion
2198 (beginning-of-line 1)
2199 (org-table-get-field
2200 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2201 (concat " "
2202 (setq new (or forcenew
2203 (cadr (member (match-string 1) marks))))
2204 " ")
2205 " # ")))
2206 (if (and l1 l2)
2207 (progn
2208 (org-goto-line l1)
2209 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
2210 (and (looking-at org-table-dataline-regexp)
2211 (org-table-get-field 1 (concat " " new " "))))
2212 (org-goto-line l1)))
2213 (if (not (= epos (point-at-eol))) (org-table-align))
2214 (org-goto-line l)
2215 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
2217 (defun org-table-maybe-recalculate-line ()
2218 "Recompute the current line if marked for it, and if we haven't just done it."
2219 (interactive)
2220 (and org-table-allow-automatic-line-recalculation
2221 (not (and (memq last-command org-recalc-commands)
2222 (equal org-last-recalc-line (org-current-line))))
2223 (save-excursion (beginning-of-line 1)
2224 (looking-at org-table-auto-recalculate-regexp))
2225 (org-table-recalculate) t))
2227 (defvar modes)
2228 (defsubst org-set-calc-mode (var &optional value)
2229 (if (stringp var)
2230 (setq var (assoc var '(("D" calc-angle-mode deg)
2231 ("R" calc-angle-mode rad)
2232 ("F" calc-prefer-frac t)
2233 ("S" calc-symbolic-mode t)))
2234 value (nth 2 var) var (nth 1 var)))
2235 (if (memq var modes)
2236 (setcar (cdr (memq var modes)) value)
2237 (cons var (cons value modes)))
2238 modes)
2240 (defun org-table-eval-formula (&optional arg equation
2241 suppress-align suppress-const
2242 suppress-store suppress-analysis)
2243 "Replace the table field value at the cursor by the result of a calculation.
2245 This function makes use of Dave Gillespie's Calc package, in my view the
2246 most exciting program ever written for GNU Emacs. So you need to have Calc
2247 installed in order to use this function.
2249 In a table, this command replaces the value in the current field with the
2250 result of a formula. It also installs the formula as the \"current\" column
2251 formula, by storing it in a special line below the table. When called
2252 with a `C-u' prefix, the current field must be a named field, and the
2253 formula is installed as valid in only this specific field.
2255 When called with two `C-u' prefixes, insert the active equation
2256 for the field back into the current field, so that it can be
2257 edited there. This is useful in order to use \\[org-table-show-reference]
2258 to check the referenced fields.
2260 When called, the command first prompts for a formula, which is read in
2261 the minibuffer. Previously entered formulas are available through the
2262 history list, and the last used formula is offered as a default.
2263 These stored formulas are adapted correctly when moving, inserting, or
2264 deleting columns with the corresponding commands.
2266 The formula can be any algebraic expression understood by the Calc package.
2267 For details, see the Org-mode manual.
2269 This function can also be called from Lisp programs and offers
2270 additional arguments: EQUATION can be the formula to apply. If this
2271 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2272 used to speed-up recursive calls by by-passing unnecessary aligns.
2273 SUPPRESS-CONST suppresses the interpretation of constants in the
2274 formula, assuming that this has been done already outside the function.
2275 SUPPRESS-STORE means the formula should not be stored, either because
2276 it is already stored, or because it is a modified equation that should
2277 not overwrite the stored one."
2278 (interactive "P")
2279 (org-table-check-inside-data-field)
2280 (or suppress-analysis (org-table-get-specials))
2281 (if (equal arg '(16))
2282 (let ((eq (org-table-current-field-formula)))
2283 (or eq (error "No equation active for current field"))
2284 (org-table-get-field nil eq)
2285 (org-table-align)
2286 (setq org-table-may-need-update t))
2287 (let* (fields
2288 (ndown (if (integerp arg) arg 1))
2289 (org-table-automatic-realign nil)
2290 (case-fold-search nil)
2291 (down (> ndown 1))
2292 (formula (if (and equation suppress-store)
2293 equation
2294 (org-table-get-formula equation (equal arg '(4)))))
2295 (n0 (org-table-current-column))
2296 (modes (copy-sequence org-calc-default-modes))
2297 (numbers nil) ; was a variable, now fixed default
2298 (keep-empty nil)
2299 n form form0 bw fmt x ev orig c lispp literal)
2300 ;; Parse the format string. Since we have a lot of modes, this is
2301 ;; a lot of work. However, I think calc still uses most of the time.
2302 (if (string-match ";" formula)
2303 (let ((tmp (org-split-string formula ";")))
2304 (setq formula (car tmp)
2305 fmt (concat (cdr (assoc "%" org-table-local-parameters))
2306 (nth 1 tmp)))
2307 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
2308 (setq c (string-to-char (match-string 1 fmt))
2309 n (string-to-number (match-string 2 fmt)))
2310 (if (= c ?p)
2311 (setq modes (org-set-calc-mode 'calc-internal-prec n))
2312 (setq modes (org-set-calc-mode
2313 'calc-float-format
2314 (list (cdr (assoc c '((?n . float) (?f . fix)
2315 (?s . sci) (?e . eng))))
2316 n))))
2317 (setq fmt (replace-match "" t t fmt)))
2318 (if (string-match "[NT]" fmt)
2319 (setq numbers (equal (match-string 0 fmt) "N")
2320 fmt (replace-match "" t t fmt)))
2321 (if (string-match "L" fmt)
2322 (setq literal t
2323 fmt (replace-match "" t t fmt)))
2324 (if (string-match "E" fmt)
2325 (setq keep-empty t
2326 fmt (replace-match "" t t fmt)))
2327 (while (string-match "[DRFS]" fmt)
2328 (setq modes (org-set-calc-mode (match-string 0 fmt)))
2329 (setq fmt (replace-match "" t t fmt)))
2330 (unless (string-match "\\S-" fmt)
2331 (setq fmt nil))))
2332 (if (and (not suppress-const) org-table-formula-use-constants)
2333 (setq formula (org-table-formula-substitute-names formula)))
2334 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
2335 (while (> ndown 0)
2336 (setq fields (org-split-string
2337 (org-no-properties
2338 (buffer-substring (point-at-bol) (point-at-eol)))
2339 " *| *"))
2340 (if (eq numbers t)
2341 (setq fields (mapcar
2342 (lambda (x) (number-to-string (string-to-number x)))
2343 fields)))
2344 (setq ndown (1- ndown))
2345 (setq form (copy-sequence formula)
2346 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
2347 (if (and lispp literal) (setq lispp 'literal))
2349 ;; Insert row and column number of formula result field
2350 (while (string-match "[@$]#" form)
2351 (setq form
2352 (replace-match
2353 (format "%d"
2354 (save-match-data
2355 (if (equal (substring form (match-beginning 0)
2356 (1+ (match-beginning 0)))
2357 "@")
2358 (org-table-current-dline)
2359 (org-table-current-column))))
2360 t t form)))
2362 ;; Check for old vertical references
2363 (setq form (org-table-rewrite-old-row-references form))
2364 ;; Insert remote references
2365 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
2366 (setq form
2367 (replace-match
2368 (save-match-data
2369 (org-table-make-reference
2370 (org-table-get-remote-range
2371 (match-string 1 form) (match-string 2 form))
2372 keep-empty numbers lispp))
2373 t t form)))
2374 ;; Insert complex ranges
2375 (while (and (string-match org-table-range-regexp form)
2376 (> (length (match-string 0 form)) 1))
2377 (setq form
2378 (replace-match
2379 (save-match-data
2380 (org-table-make-reference
2381 (org-table-get-range (match-string 0 form) nil n0)
2382 keep-empty numbers lispp))
2383 t t form)))
2384 ;; Insert simple ranges
2385 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
2386 (setq form
2387 (replace-match
2388 (save-match-data
2389 (org-table-make-reference
2390 (org-sublist
2391 fields (string-to-number (match-string 1 form))
2392 (string-to-number (match-string 2 form)))
2393 keep-empty numbers lispp))
2394 t t form)))
2395 (setq form0 form)
2396 ;; Insert the references to fields in same row
2397 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
2398 (setq n (+ (string-to-number (match-string 1 form))
2399 (if (match-end 2) n0 0))
2400 x (nth (1- (if (= n 0) n0 (max n 1))) fields))
2401 (unless x (error "Invalid field specifier \"%s\""
2402 (match-string 0 form)))
2403 (setq form (replace-match
2404 (save-match-data
2405 (org-table-make-reference x nil numbers lispp))
2406 t t form)))
2408 (if lispp
2409 (setq ev (condition-case nil
2410 (eval (eval (read form)))
2411 (error "#ERROR"))
2412 ev (if (numberp ev) (number-to-string ev) ev))
2413 (or (fboundp 'calc-eval)
2414 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2415 (setq ev (calc-eval (cons form modes)
2416 (if numbers 'num))))
2418 (when org-table-formula-debug
2419 (with-output-to-temp-buffer "*Substitution History*"
2420 (princ (format "Substitution history of formula
2421 Orig: %s
2422 $xyz-> %s
2423 @r$c-> %s
2424 $1-> %s\n" orig formula form0 form))
2425 (if (listp ev)
2426 (princ (format " %s^\nError: %s"
2427 (make-string (car ev) ?\-) (nth 1 ev)))
2428 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2429 ev (or fmt "NONE")
2430 (if fmt (format fmt (string-to-number ev)) ev)))))
2431 (setq bw (get-buffer-window "*Substitution History*"))
2432 (org-fit-window-to-buffer bw)
2433 (unless (and (interactive-p) (not ndown))
2434 (unless (let (inhibit-redisplay)
2435 (y-or-n-p "Debugging Formula. Continue to next? "))
2436 (org-table-align)
2437 (error "Abort"))
2438 (delete-window bw)
2439 (message "")))
2440 (if (listp ev) (setq fmt nil ev "#ERROR"))
2441 (org-table-justify-field-maybe
2442 (if fmt (format fmt (string-to-number ev)) ev))
2443 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
2444 (call-interactively 'org-return)
2445 (setq ndown 0)))
2446 (and down (org-table-maybe-recalculate-line))
2447 (or suppress-align (and org-table-may-need-update
2448 (org-table-align))))))
2450 (defun org-table-put-field-property (prop value)
2451 (save-excursion
2452 (put-text-property (progn (skip-chars-backward "^|") (point))
2453 (progn (skip-chars-forward "^|") (point))
2454 prop value)))
2456 (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
2457 "Get a calc vector from a column, according to descriptor DESC.
2458 Optional arguments TBEG and COL can give the beginning of the table and
2459 the current column, to avoid unnecessary parsing.
2461 HIGHLIGHT means just highlight the range.
2463 When CORNERS-ONLY is set, only return the corners of the range as
2464 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2465 in the buffer and column1 and column2 are table column numbers."
2466 (if (not (equal (string-to-char desc) ?@))
2467 (setq desc (concat "@" desc)))
2468 (save-excursion
2469 (or tbeg (setq tbeg (org-table-begin)))
2470 (or col (setq col (org-table-current-column)))
2471 (let ((thisline (org-current-line))
2472 beg end c1 c2 r1 r2 rangep tmp)
2473 (unless (string-match org-table-range-regexp desc)
2474 (error "Invalid table range specifier `%s'" desc))
2475 (setq rangep (match-end 3)
2476 r1 (and (match-end 1) (match-string 1 desc))
2477 r2 (and (match-end 4) (match-string 4 desc))
2478 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
2479 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
2481 (and c1 (setq c1 (+ (string-to-number c1)
2482 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
2483 (and c2 (setq c2 (+ (string-to-number c2)
2484 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
2485 (if (equal r1 "") (setq r1 nil))
2486 (if (equal r2 "") (setq r2 nil))
2487 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
2488 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
2489 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2490 (if (not r1) (setq r1 thisline))
2491 (if (not r2) (setq r2 thisline))
2492 (if (not c1) (setq c1 col))
2493 (if (not c2) (setq c2 col))
2494 (if (and (not corners-only)
2495 (or (not rangep) (and (= r1 r2) (= c1 c2))))
2496 ;; just one field
2497 (progn
2498 (org-goto-line r1)
2499 (while (not (looking-at org-table-dataline-regexp))
2500 (beginning-of-line 2))
2501 (prog1 (org-trim (org-table-get-field c1))
2502 (if highlight (org-table-highlight-rectangle (point) (point)))))
2503 ;; A range, return a vector
2504 ;; First sort the numbers to get a regular ractangle
2505 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
2506 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
2507 (if corners-only
2508 ;; Only return the corners of the range
2509 (list r1 c1 r2 c2)
2510 ;; Copy the range values into a list
2511 (org-goto-line r1)
2512 (while (not (looking-at org-table-dataline-regexp))
2513 (beginning-of-line 2))
2514 (org-table-goto-column c1)
2515 (setq beg (point))
2516 (org-goto-line r2)
2517 (while (not (looking-at org-table-dataline-regexp))
2518 (beginning-of-line 0))
2519 (org-table-goto-column c2)
2520 (setq end (point))
2521 (if highlight
2522 (org-table-highlight-rectangle
2523 beg (progn (skip-chars-forward "^|\n") (point))))
2524 ;; return string representation of calc vector
2525 (mapcar 'org-trim
2526 (apply 'append (org-table-copy-region beg end))))))))
2528 (defun org-table-get-descriptor-line (desc &optional cline bline table)
2529 "Analyze descriptor DESC and retrieve the corresponding line number.
2530 The cursor is currently in line CLINE, the table begins in line BLINE,
2531 and TABLE is a vector with line types."
2532 (if (string-match "^[0-9]+$" desc)
2533 (aref org-table-dlines (string-to-number desc))
2534 (setq cline (or cline (org-current-line))
2535 bline (or bline org-table-current-begin-line)
2536 table (or table org-table-current-line-types))
2537 (if (or
2538 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
2539 ;; 1 2 3 4 5 6
2540 (and (not (match-end 3)) (not (match-end 6)))
2541 (and (match-end 3) (match-end 6) (not (match-end 5))))
2542 (error "Invalid row descriptor `%s'" desc))
2543 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
2544 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
2545 (odir (and (match-end 5) (match-string 5 desc)))
2546 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
2547 (i (- cline bline))
2548 (rel (and (match-end 6)
2549 (or (and (match-end 1) (not (match-end 3)))
2550 (match-end 5)))))
2551 (if (and hn (not hdir))
2552 (progn
2553 (setq i 0 hdir "+")
2554 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
2555 (if (and (not hn) on (not odir))
2556 (error "Should never happen");;(aref org-table-dlines on)
2557 (if (and hn (> hn 0))
2558 (setq i (org-table-find-row-type table i 'hline (equal hdir "-")
2559 nil hn cline desc)))
2560 (if on
2561 (setq i (org-table-find-row-type table i 'dline (equal odir "-")
2562 rel on cline desc)))
2563 (+ bline i)))))
2565 (defun org-table-find-row-type (table i type backwards relative n cline desc)
2566 "FIXME: Needs more documentation."
2567 (let ((l (length table)))
2568 (while (> n 0)
2569 (while (and (setq i (+ i (if backwards -1 1)))
2570 (>= i 0) (< i l)
2571 (not (eq (aref table i) type))
2572 (if (and relative (eq (aref table i) 'hline))
2573 (cond
2574 ((eq org-table-relative-ref-may-cross-hline t) t)
2575 ((eq org-table-relative-ref-may-cross-hline 'error)
2576 (error "Row descriptor %s used in line %d crosses hline" desc cline))
2577 (t (setq i (- i (if backwards -1 1))
2578 n 1)
2579 nil))
2580 t)))
2581 (setq n (1- n)))
2582 (if (or (< i 0) (>= i l))
2583 (error "Row descriptor %s used in line %d leads outside table"
2584 desc cline)
2585 i)))
2587 (defun org-table-rewrite-old-row-references (s)
2588 (if (string-match "&[-+0-9I]" s)
2589 (error "Formula contains old &row reference, please rewrite using @-syntax")
2592 (defun org-table-make-reference (elements keep-empty numbers lispp)
2593 "Convert list ELEMENTS to something appropriate to insert into formula.
2594 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2595 NUMBERS indicates that everything should be converted to numbers.
2596 LISPP means to return something appropriate for a Lisp list."
2597 (if (stringp elements) ; just a single val
2598 (if lispp
2599 (if (eq lispp 'literal)
2600 elements
2601 (prin1-to-string (if numbers (string-to-number elements) elements)))
2602 (if (equal elements "") (setq elements "0"))
2603 (if numbers (setq elements (number-to-string (string-to-number elements))))
2604 (concat "(" elements ")"))
2605 (unless keep-empty
2606 (setq elements
2607 (delq nil
2608 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
2609 elements))))
2610 (setq elements (or elements '("0")))
2611 (if lispp
2612 (mapconcat
2613 (lambda (x)
2614 (if (eq lispp 'literal)
2616 (prin1-to-string (if numbers (string-to-number x) x))))
2617 elements " ")
2618 (concat "[" (mapconcat
2619 (lambda (x)
2620 (if numbers (number-to-string (string-to-number x)) x))
2621 elements
2622 ",") "]"))))
2624 (defun org-table-recalculate (&optional all noalign)
2625 "Recalculate the current table line by applying all stored formulas.
2626 With prefix arg ALL, do this for all lines in the table.
2627 With the prefix argument ALL is `(16)' \
2628 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2629 it is the symbol `iterate', recompute the table until it no longer changes.
2630 If NOALIGN is not nil, do not re-align the table after the computations
2631 are done. This is typically used internally to save time, if it is
2632 known that the table will be realigned a little later anyway."
2633 (interactive "P")
2634 (or (memq this-command org-recalc-commands)
2635 (setq org-recalc-commands (cons this-command org-recalc-commands)))
2636 (unless (org-at-table-p) (error "Not at a table"))
2637 (if (or (eq all 'iterate) (equal all '(16)))
2638 (org-table-iterate)
2639 (org-table-get-specials)
2640 (let* ((eqlist (sort (org-table-get-stored-formulas)
2641 (lambda (a b) (string< (car a) (car b)))))
2642 (eqlist1 (copy-sequence eqlist))
2643 (inhibit-redisplay (not debug-on-error))
2644 (line-re org-table-dataline-regexp)
2645 (thisline (org-current-line))
2646 (thiscol (org-table-current-column))
2647 seen-fields lhs1
2648 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name name1)
2649 ;; Insert constants in all formulas
2650 (setq eqlist
2651 (mapcar (lambda (x)
2652 (when (string-match "\\`$>" (car x))
2653 (setq lhs1 (car x))
2654 (setq x (cons (substring
2655 (org-table-formula-handle-lastrc
2656 (car x)) 1)
2657 (cdr x)))
2658 (if (assoc (car x) eqlist1)
2659 (error "\"%s=\" formula tries to overwrite existing formula for column %s"
2660 lhs1 (car x))))
2661 (cons
2662 (org-table-formula-handle-lastrc (car x))
2663 (org-table-formula-substitute-names
2664 (org-table-formula-handle-lastrc (cdr x)))))
2665 eqlist))
2666 ;; Split the equation list
2667 (while (setq eq (pop eqlist))
2668 (if (<= (string-to-char (car eq)) ?9)
2669 (push eq eqlnum)
2670 (push eq eqlname)))
2671 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
2672 ;; Expand ranges in lhs of formulas
2673 (setq eqlname (org-table-expand-lhs-ranges eqlname))
2675 ;; Get the correct line range to process
2676 (if all
2677 (progn
2678 (setq end (move-marker (make-marker) (1+ (org-table-end))))
2679 (goto-char (setq beg (org-table-begin)))
2680 (if (re-search-forward org-table-calculate-mark-regexp end t)
2681 ;; This is a table with marked lines, compute selected lines
2682 (setq line-re org-table-recalculate-regexp)
2683 ;; Move forward to the first non-header line
2684 (if (and (re-search-forward org-table-dataline-regexp end t)
2685 (re-search-forward org-table-hline-regexp end t)
2686 (re-search-forward org-table-dataline-regexp end t))
2687 (setq beg (match-beginning 0))
2688 nil))) ;; just leave beg where it is
2689 (setq beg (point-at-bol)
2690 end (move-marker (make-marker) (1+ (point-at-eol)))))
2691 (goto-char beg)
2692 (and all (message "Re-applying formulas to full table..."))
2694 ;; First find the named fields, and mark them untouchable.
2695 ;; Also check if several field/range formulas try to set the same field.
2696 (remove-text-properties beg end '(org-untouchable t))
2697 (while (setq eq (pop eqlname))
2698 (setq name (car eq)
2699 a (assoc name org-table-named-field-locations))
2700 (setq name1 name)
2701 (if a (setq name1 (format "@%d$%d" (org-table-line-to-dline (nth 1 a))
2702 (nth 2 a))))
2703 (when (member name1 seen-fields)
2704 (error "Several field/range formulas try to set %s" name1))
2705 (push name1 seen-fields)
2707 (and (not a)
2708 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
2709 (setq a (list name
2710 (condition-case nil
2711 (aref org-table-dlines
2712 (string-to-number (match-string 1 name)))
2713 (error (error "Invalid row number in %s"
2714 name)))
2715 (string-to-number (match-string 2 name)))))
2716 (when (and a (or all (equal (nth 1 a) thisline)))
2717 (message "Re-applying formula to field: %s" name)
2718 (org-goto-line (nth 1 a))
2719 (org-table-goto-column (nth 2 a))
2720 (push (append a (list (cdr eq))) eqlname1)
2721 (org-table-put-field-property :org-untouchable t)))
2722 (setq eqlname1 (nreverse eqlname1))
2724 ;; Now evaluate the column formulas, but skip fields covered by
2725 ;; field formulas
2726 (goto-char beg)
2727 (while (re-search-forward line-re end t)
2728 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2729 ;; Unprotected line, recalculate
2730 (and all (message "Re-applying formulas to full table...(line %d)"
2731 (setq cnt (1+ cnt))))
2732 (setq org-last-recalc-line (org-current-line))
2733 (setq eql eqlnum)
2734 (while (setq entry (pop eql))
2735 (org-goto-line org-last-recalc-line)
2736 (org-table-goto-column (string-to-number (car entry)) nil 'force)
2737 (unless (get-text-property (point) :org-untouchable)
2738 (org-table-eval-formula nil (cdr entry)
2739 'noalign 'nocst 'nostore 'noanalysis)))))
2741 ;; Now evaluate the field formulas
2742 (while (setq eq (pop eqlname1))
2743 (message "Re-applying formula to field: %s" (car eq))
2744 (org-goto-line (nth 1 eq))
2745 (org-table-goto-column (nth 2 eq))
2746 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
2747 'nostore 'noanalysis))
2749 (org-goto-line thisline)
2750 (org-table-goto-column thiscol)
2751 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
2752 (or noalign (and org-table-may-need-update (org-table-align))
2753 (and all (message "Re-applying formulas to %d lines...done" cnt)))
2755 ;; back to initial position
2756 (message "Re-applying formulas...done")
2757 (org-goto-line thisline)
2758 (org-table-goto-column thiscol)
2759 (or noalign (and org-table-may-need-update (org-table-align))
2760 (and all (message "Re-applying formulas...done"))))))
2762 (defun org-table-iterate (&optional arg)
2763 "Recalculate the table until it does not change anymore.
2764 The maximun number of iterations is 10, but you can chose a different value
2765 with the prefix ARG."
2766 (interactive "P")
2767 (let ((imax (if arg (prefix-numeric-value arg) 10))
2768 (i 0)
2769 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2770 thistbl)
2771 (catch 'exit
2772 (while (< i imax)
2773 (setq i (1+ i))
2774 (org-table-recalculate 'all)
2775 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
2776 (if (not (string= lasttbl thistbl))
2777 (setq lasttbl thistbl)
2778 (if (> i 1)
2779 (message "Convergence after %d iterations" i)
2780 (message "Table was already stable"))
2781 (throw 'exit t)))
2782 (error "No convergence after %d iterations" i))))
2784 (defun org-table-recalculate-buffer-tables ()
2785 "Recalculate all tables in the current buffer."
2786 (interactive)
2787 (save-excursion
2788 (save-restriction
2789 (widen)
2790 (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
2792 (defun org-table-iterate-buffer-tables ()
2793 "Iterate all tables in the buffer, to converge inter-table dependencies."
2794 (interactive)
2795 (let* ((imax 10)
2796 (checksum (md5 (buffer-string)))
2799 (i imax))
2800 (save-excursion
2801 (save-restriction
2802 (widen)
2803 (catch 'exit
2804 (while (> i 0)
2805 (setq i (1- i))
2806 (org-table-map-tables (lambda () (org-table-recalculate t)) t)
2807 (if (equal checksum (setq c1 (md5 (buffer-string))))
2808 (progn
2809 (message "Convergence after %d iterations" (- imax i))
2810 (throw 'exit t))
2811 (setq checksum c1)))
2812 (error "No convergence after %d iterations" imax))))))
2814 (defun org-table-expand-lhs-ranges (equations)
2815 "Expand list of formulas.
2816 If some of the RHS in the formulas are ranges or a row reference, expand
2817 them to individual field equations for each field."
2818 (let (e res lhs rhs range r1 r2 c1 c2)
2819 (while (setq e (pop equations))
2820 (setq lhs (car e) rhs (cdr e))
2821 (cond
2822 ((string-match "^@-?[-+I0-9]+\\$-?[0-9]+$" lhs)
2823 ;; This just refers to one fixed field
2824 (push e res))
2825 ((string-match "^[a-zA-Z][a-zA-Z0-9]*$" lhs)
2826 ;; This just refers to one fixed named field
2827 (push e res))
2828 ((string-match "^@[0-9]+$" lhs)
2829 (loop for ic from 1 to org-table-current-ncol do
2830 (push (cons (format "%s$%d" lhs ic) rhs) res)
2831 (put-text-property 0 (length (caar res))
2832 :orig-eqn e (caar res))))
2834 (setq range (org-table-get-range lhs org-table-current-begin-pos
2835 1 nil 'corners))
2836 (setq r1 (nth 0 range) c1 (nth 1 range)
2837 r2 (nth 2 range) c2 (nth 3 range))
2838 (setq r1 (org-table-line-to-dline r1))
2839 (setq r2 (org-table-line-to-dline r2 'above))
2840 (loop for ir from r1 to r2 do
2841 (loop for ic from c1 to c2 do
2842 (push (cons (format "@%d$%d" ir ic) rhs) res)
2843 (put-text-property 0 (length (caar res))
2844 :orig-eqn e (caar res)))))))
2845 (nreverse res)))
2847 (defun org-table-formula-handle-lastrc (s)
2848 "Replace @> / $> with the last row/column of the table."
2849 (while (string-match "\\([@$]\\)>\\(-[0-9]+\\)?" s)
2850 (setq s (replace-match
2851 (format "%s%d"
2852 (match-string 1 s)
2853 (+ (if (equal (match-string 1 s) "@")
2854 (1- (length org-table-dlines))
2855 org-table-current-ncol)
2856 (if (match-end 2)
2857 (string-to-number (match-string 2 s))
2858 0)))
2859 t t s)))
2862 (defun org-table-formula-substitute-names (f)
2863 "Replace $const with values in string F."
2864 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
2865 ;; First, check for column names
2866 (while (setq start (string-match org-table-column-name-regexp f start))
2867 (setq start (1+ start))
2868 (setq a (assoc (match-string 1 f) org-table-column-names))
2869 (setq f (replace-match (concat "$" (cdr a)) t t f)))
2870 ;; Parameters and constants
2871 (setq start 0)
2872 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start))
2873 (if (match-end 2)
2874 (setq start (match-end 2))
2875 (setq start (1+ start))
2876 (if (setq a (save-match-data
2877 (org-table-get-constant (match-string 1 f))))
2878 (setq f (replace-match
2879 (concat (if pp "(") a (if pp ")")) t t f)))))
2880 (if org-table-formula-debug
2881 (put-text-property 0 (length f) :orig-formula f1 f))
2884 (defun org-table-get-constant (const)
2885 "Find the value for a parameter or constant in a formula.
2886 Parameters get priority."
2887 (or (cdr (assoc const org-table-local-parameters))
2888 (cdr (assoc const org-table-formula-constants-local))
2889 (cdr (assoc const org-table-formula-constants))
2890 (and (fboundp 'constants-get) (constants-get const))
2891 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
2892 (org-entry-get nil (substring const 5) 'inherit))
2893 "#UNDEFINED_NAME"))
2895 (defvar org-table-fedit-map
2896 (let ((map (make-sparse-keymap)))
2897 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
2898 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
2899 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
2900 (org-defkey map "\C-c'" 'org-table-fedit-finish)
2901 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
2902 (org-defkey map "\C-c?" 'org-table-show-reference)
2903 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
2904 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
2905 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
2906 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
2907 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
2908 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
2909 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
2910 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
2911 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
2912 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
2913 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
2914 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
2915 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
2916 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
2917 map))
2919 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
2920 '("Edit-Formulas"
2921 ["Finish and Install" org-table-fedit-finish t]
2922 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
2923 ["Abort" org-table-fedit-abort t]
2924 "--"
2925 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
2926 ["Complete Lisp Symbol" lisp-complete-symbol t]
2927 "--"
2928 "Shift Reference at Point"
2929 ["Up" org-table-fedit-ref-up t]
2930 ["Down" org-table-fedit-ref-down t]
2931 ["Left" org-table-fedit-ref-left t]
2932 ["Right" org-table-fedit-ref-right t]
2934 "Change Test Row for Column Formulas"
2935 ["Up" org-table-fedit-line-up t]
2936 ["Down" org-table-fedit-line-down t]
2937 "--"
2938 ["Scroll Table Window" org-table-fedit-scroll t]
2939 ["Scroll Table Window down" org-table-fedit-scroll-down t]
2940 ["Show Table Grid" org-table-fedit-toggle-coordinates
2941 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
2942 org-table-overlay-coordinates)]
2943 "--"
2944 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
2945 :style toggle :selected org-table-buffer-is-an]))
2947 (defvar org-pos)
2949 (defun org-table-edit-formulas ()
2950 "Edit the formulas of the current table in a separate buffer."
2951 (interactive)
2952 (when (save-excursion (beginning-of-line 1) (looking-at "[ \t]*#\\+TBLFM"))
2953 (beginning-of-line 0))
2954 (unless (org-at-table-p) (error "Not at a table"))
2955 (org-table-get-specials)
2956 (let ((key (org-table-current-field-formula 'key 'noerror))
2957 (eql (sort (org-table-get-stored-formulas 'noerror)
2958 'org-table-formula-less-p))
2959 (pos (move-marker (make-marker) (point)))
2960 (startline 1)
2961 (wc (current-window-configuration))
2962 (sel-win (selected-window))
2963 (titles '((column . "# Column Formulas\n")
2964 (field . "# Field and Range Formulas\n")
2965 (named . "# Named Field Formulas\n")))
2966 entry s type title)
2967 (org-switch-to-buffer-other-window "*Edit Formulas*")
2968 (erase-buffer)
2969 ;; Keep global-font-lock-mode from turning on font-lock-mode
2970 (let ((font-lock-global-modes '(not fundamental-mode)))
2971 (fundamental-mode))
2972 (org-set-local 'font-lock-global-modes (list 'not major-mode))
2973 (org-set-local 'org-pos pos)
2974 (org-set-local 'org-window-configuration wc)
2975 (org-set-local 'org-selected-window sel-win)
2976 (use-local-map org-table-fedit-map)
2977 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
2978 (easy-menu-add org-table-fedit-menu)
2979 (setq startline (org-current-line))
2980 (while (setq entry (pop eql))
2981 (setq type (cond
2982 ((string-match "\\`$>" (car entry)) 'column)
2983 ((equal (string-to-char (car entry)) ?@) 'field)
2984 ((string-match "^[0-9]" (car entry)) 'column)
2985 (t 'named)))
2986 (when (setq title (assq type titles))
2987 (or (bobp) (insert "\n"))
2988 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
2989 (setq titles (remove title titles)))
2990 (if (equal key (car entry)) (setq startline (org-current-line)))
2991 (setq s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
2992 (car entry) " = " (cdr entry) "\n"))
2993 (remove-text-properties 0 (length s) '(face nil) s)
2994 (insert s))
2995 (if (eq org-table-use-standard-references t)
2996 (org-table-fedit-toggle-ref-type))
2997 (org-goto-line startline)
2998 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3000 (defun org-table-fedit-post-command ()
3001 (when (not (memq this-command '(lisp-complete-symbol)))
3002 (let ((win (selected-window)))
3003 (save-excursion
3004 (condition-case nil
3005 (org-table-show-reference)
3006 (error nil))
3007 (select-window win)))))
3009 (defun org-table-formula-to-user (s)
3010 "Convert a formula from internal to user representation."
3011 (if (eq org-table-use-standard-references t)
3012 (org-table-convert-refs-to-an s)
3015 (defun org-table-formula-from-user (s)
3016 "Convert a formula from user to internal representation."
3017 (if org-table-use-standard-references
3018 (org-table-convert-refs-to-rc s)
3021 (defun org-table-convert-refs-to-rc (s)
3022 "Convert spreadsheet references from A7 to @7$28.
3023 Works for single references, but also for entire formulas and even the
3024 full TBLFM line."
3025 (let ((start 0))
3026 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^)]*)\\)" s start)
3027 (cond
3028 ((match-end 3)
3029 ;; format match, just advance
3030 (setq start (match-end 0)))
3031 ((and (> (match-beginning 0) 0)
3032 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
3033 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
3034 ;; 3.e5 or something like this.
3035 (setq start (match-end 0)))
3036 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3037 ;; (member (match-string 1 s)
3038 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3040 ;; function name, just advance
3041 (setq start (match-end 0)))
3043 (setq start (match-beginning 0)
3044 s (replace-match
3045 (if (equal (match-string 2 s) "&")
3046 (format "$%d" (org-letters-to-number (match-string 1 s)))
3047 (format "@%d$%d"
3048 (string-to-number (match-string 2 s))
3049 (org-letters-to-number (match-string 1 s))))
3050 t t s)))))
3053 (defun org-table-convert-refs-to-an (s)
3054 "Convert spreadsheet references from to @7$28 to AB7.
3055 Works for single references, but also for entire formulas and even the
3056 full TBLFM line."
3057 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
3058 (setq s (replace-match
3059 (format "%s%d"
3060 (org-number-to-letters
3061 (string-to-number (match-string 2 s)))
3062 (string-to-number (match-string 1 s)))
3063 t t s)))
3064 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
3065 (setq s (replace-match (concat "\\1"
3066 (org-number-to-letters
3067 (string-to-number (match-string 2 s))) "&")
3068 t nil s)))
3071 (defun org-letters-to-number (s)
3072 "Convert a base 26 number represented by letters into an integer.
3073 For example: AB -> 28."
3074 (let ((n 0))
3075 (setq s (upcase s))
3076 (while (> (length s) 0)
3077 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
3078 s (substring s 1)))
3081 (defun org-number-to-letters (n)
3082 "Convert an integer into a base 26 number represented by letters.
3083 For example: 28 -> AB."
3084 (let ((s ""))
3085 (while (> n 0)
3086 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
3087 n (/ (1- n) 26)))
3090 (defun org-table-fedit-convert-buffer (function)
3091 "Convert all references in this buffer, using FUNCTION."
3092 (let ((line (org-current-line)))
3093 (goto-char (point-min))
3094 (while (not (eobp))
3095 (insert (funcall function (buffer-substring (point) (point-at-eol))))
3096 (delete-region (point) (point-at-eol))
3097 (or (eobp) (forward-char 1)))
3098 (org-goto-line line)))
3100 (defun org-table-fedit-toggle-ref-type ()
3101 "Convert all references in the buffer from B3 to @3$2 and back."
3102 (interactive)
3103 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
3104 (org-table-fedit-convert-buffer
3105 (if org-table-buffer-is-an
3106 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
3107 (message "Reference type switched to %s"
3108 (if org-table-buffer-is-an "A1 etc" "@row$column")))
3110 (defun org-table-fedit-ref-up ()
3111 "Shift the reference at point one row/hline up."
3112 (interactive)
3113 (org-table-fedit-shift-reference 'up))
3114 (defun org-table-fedit-ref-down ()
3115 "Shift the reference at point one row/hline down."
3116 (interactive)
3117 (org-table-fedit-shift-reference 'down))
3118 (defun org-table-fedit-ref-left ()
3119 "Shift the reference at point one field to the left."
3120 (interactive)
3121 (org-table-fedit-shift-reference 'left))
3122 (defun org-table-fedit-ref-right ()
3123 "Shift the reference at point one field to the right."
3124 (interactive)
3125 (org-table-fedit-shift-reference 'right))
3127 (defun org-table-fedit-shift-reference (dir)
3128 (cond
3129 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3130 (if (memq dir '(left right))
3131 (org-rematch-and-replace 1 (eq dir 'left))
3132 (error "Cannot shift reference in this direction")))
3133 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3134 ;; A B3-like reference
3135 (if (memq dir '(up down))
3136 (org-rematch-and-replace 2 (eq dir 'up))
3137 (org-rematch-and-replace 1 (eq dir 'left))))
3138 ((org-at-regexp-p
3139 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3140 ;; An internal reference
3141 (if (memq dir '(up down))
3142 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
3143 (org-rematch-and-replace 5 (eq dir 'left))))))
3145 (defun org-rematch-and-replace (n &optional decr hline)
3146 "Re-match the group N, and replace it with the shifted reference."
3147 (or (match-end n) (error "Cannot shift reference in this direction"))
3148 (goto-char (match-beginning n))
3149 (and (looking-at (regexp-quote (match-string n)))
3150 (replace-match (org-table-shift-refpart (match-string 0) decr hline)
3151 t t)))
3153 (defun org-table-shift-refpart (ref &optional decr hline)
3154 "Shift a reference part REF.
3155 If DECR is set, decrease the references row/column, else increase.
3156 If HLINE is set, this may be a hline reference, it certainly is not
3157 a translation reference."
3158 (save-match-data
3159 (let* ((sign (string-match "^[-+]" ref)) n)
3161 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
3162 (cond
3163 ((and hline (string-match "^I+" ref))
3164 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
3165 (setq n (+ n (if decr -1 1)))
3166 (if (= n 0) (setq n (+ n (if decr -1 1))))
3167 (if sign
3168 (setq sign (if (< n 0) "-" "+") n (abs n))
3169 (setq n (max 1 n)))
3170 (concat sign (make-string n ?I)))
3172 ((string-match "^[0-9]+" ref)
3173 (setq n (string-to-number (concat sign ref)))
3174 (setq n (+ n (if decr -1 1)))
3175 (if sign
3176 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
3177 (number-to-string (max 1 n))))
3179 ((string-match "^[a-zA-Z]+" ref)
3180 (org-number-to-letters
3181 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
3183 (t (error "Cannot shift reference"))))))
3185 (defun org-table-fedit-toggle-coordinates ()
3186 "Toggle the display of coordinates in the referenced table."
3187 (interactive)
3188 (let ((pos (marker-position org-pos)))
3189 (with-current-buffer (marker-buffer org-pos)
3190 (save-excursion
3191 (goto-char pos)
3192 (org-table-toggle-coordinate-overlays)))))
3194 (defun org-table-fedit-finish (&optional arg)
3195 "Parse the buffer for formula definitions and install them.
3196 With prefix ARG, apply the new formulas to the table."
3197 (interactive "P")
3198 (org-table-remove-rectangle-highlight)
3199 (if org-table-use-standard-references
3200 (progn
3201 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
3202 (setq org-table-buffer-is-an nil)))
3203 (let ((pos org-pos) (sel-win org-selected-window) eql var form)
3204 (goto-char (point-min))
3205 (while (re-search-forward
3206 "^\\(@[-+I>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|>[-+0-9]*\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3207 nil t)
3208 (setq var (if (match-end 2) (match-string 2) (match-string 1))
3209 form (match-string 3))
3210 (setq form (org-trim form))
3211 (when (not (equal form ""))
3212 (while (string-match "[ \t]*\n[ \t]*" form)
3213 (setq form (replace-match " " t t form)))
3214 (when (assoc var eql)
3215 (error "Double formulas for %s" var))
3216 (push (cons var form) eql)))
3217 (setq org-pos nil)
3218 (set-window-configuration org-window-configuration)
3219 (select-window sel-win)
3220 (goto-char pos)
3221 (unless (org-at-table-p)
3222 (error "Lost table position - cannot install formulas"))
3223 (org-table-store-formulas eql)
3224 (move-marker pos nil)
3225 (kill-buffer "*Edit Formulas*")
3226 (if arg
3227 (org-table-recalculate 'all)
3228 (message "New formulas installed - press C-u C-c C-c to apply."))))
3230 (defun org-table-fedit-abort ()
3231 "Abort editing formulas, without installing the changes."
3232 (interactive)
3233 (org-table-remove-rectangle-highlight)
3234 (let ((pos org-pos) (sel-win org-selected-window))
3235 (set-window-configuration org-window-configuration)
3236 (select-window sel-win)
3237 (goto-char pos)
3238 (move-marker pos nil)
3239 (message "Formula editing aborted without installing changes")))
3241 (defun org-table-fedit-lisp-indent ()
3242 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3243 (interactive)
3244 (let ((pos (point)) beg end ind)
3245 (beginning-of-line 1)
3246 (cond
3247 ((looking-at "[ \t]")
3248 (goto-char pos)
3249 (call-interactively 'lisp-indent-line))
3250 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
3251 ((not (fboundp 'pp-buffer))
3252 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3253 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3254 (goto-char (- (match-end 0) 2))
3255 (setq beg (point))
3256 (setq ind (make-string (current-column) ?\ ))
3257 (condition-case nil (forward-sexp 1)
3258 (error
3259 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3260 (setq end (point))
3261 (save-restriction
3262 (narrow-to-region beg end)
3263 (if (eq last-command this-command)
3264 (progn
3265 (goto-char (point-min))
3266 (setq this-command nil)
3267 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
3268 (replace-match " ")))
3269 (pp-buffer)
3270 (untabify (point-min) (point-max))
3271 (goto-char (1+ (point-min)))
3272 (while (re-search-forward "^." nil t)
3273 (beginning-of-line 1)
3274 (insert ind))
3275 (goto-char (point-max))
3276 (backward-delete-char 1)))
3277 (goto-char beg))
3278 (t nil))))
3280 (defvar org-show-positions nil)
3282 (defun org-table-show-reference (&optional local)
3283 "Show the location/value of the $ expression at point."
3284 (interactive)
3285 (org-table-remove-rectangle-highlight)
3286 (catch 'exit
3287 (let ((pos (if local (point) org-pos))
3288 (face2 'highlight)
3289 (org-inhibit-highlight-removal t)
3290 (win (selected-window))
3291 (org-show-positions nil)
3292 var name e what match dest)
3293 (if local (org-table-get-specials))
3294 (setq what (cond
3295 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3296 (setq match (concat (substring (match-string 0) 0 -1)
3297 "$1.."
3298 (substring (match-string 0) 0 -1)
3299 "$100"))
3300 'range)
3301 ((or (org-at-regexp-p org-table-range-regexp2)
3302 (org-at-regexp-p org-table-translate-regexp)
3303 (org-at-regexp-p org-table-range-regexp))
3304 (setq match
3305 (save-match-data
3306 (org-table-convert-refs-to-rc (match-string 0))))
3307 'range)
3308 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
3309 ((org-at-regexp-p "\\$[0-9]+") 'column)
3310 ((not local) nil)
3311 (t (error "No reference at point")))
3312 match (and what (or match (match-string 0))))
3313 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
3314 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3315 'secondary-selection))
3316 (org-add-hook 'before-change-functions
3317 'org-table-remove-rectangle-highlight)
3318 (if (eq what 'name) (setq var (substring match 1)))
3319 (when (eq what 'range)
3320 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
3321 (setq match (org-table-formula-substitute-names match)))
3322 (unless local
3323 (save-excursion
3324 (end-of-line 1)
3325 (re-search-backward "^\\S-" nil t)
3326 (beginning-of-line 1)
3327 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3328 (setq dest
3329 (save-match-data
3330 (org-table-convert-refs-to-rc (match-string 1))))
3331 (org-table-add-rectangle-overlay
3332 (match-beginning 1) (match-end 1) face2))))
3333 (if (and (markerp pos) (marker-buffer pos))
3334 (if (get-buffer-window (marker-buffer pos))
3335 (select-window (get-buffer-window (marker-buffer pos)))
3336 (org-switch-to-buffer-other-window (get-buffer-window
3337 (marker-buffer pos)))))
3338 (goto-char pos)
3339 (org-table-force-dataline)
3340 (when dest
3341 (setq name (substring dest 1))
3342 (cond
3343 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
3344 (setq e (assoc name org-table-named-field-locations))
3345 (org-goto-line (nth 1 e))
3346 (org-table-goto-column (nth 2 e)))
3347 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
3348 (let ((l (string-to-number (match-string 1 dest)))
3349 (c (string-to-number (match-string 2 dest))))
3350 (org-goto-line (aref org-table-dlines l))
3351 (org-table-goto-column c)))
3352 (t (org-table-goto-column (string-to-number name))))
3353 (move-marker pos (point))
3354 (org-table-highlight-rectangle nil nil face2))
3355 (cond
3356 ((equal dest match))
3357 ((not match))
3358 ((eq what 'range)
3359 (condition-case nil
3360 (save-excursion
3361 (org-table-get-range match nil nil 'highlight))
3362 (error nil)))
3363 ((setq e (assoc var org-table-named-field-locations))
3364 (org-goto-line (nth 1 e))
3365 (org-table-goto-column (nth 2 e))
3366 (org-table-highlight-rectangle (point) (point))
3367 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
3368 ((setq e (assoc var org-table-column-names))
3369 (org-table-goto-column (string-to-number (cdr e)))
3370 (org-table-highlight-rectangle (point) (point))
3371 (goto-char (org-table-begin))
3372 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
3373 (org-table-end) t)
3374 (progn
3375 (goto-char (match-beginning 1))
3376 (org-table-highlight-rectangle)
3377 (message "Named column (column %s)" (cdr e)))
3378 (error "Column name not found")))
3379 ((eq what 'column)
3380 ;; column number
3381 (org-table-goto-column (string-to-number (substring match 1)))
3382 (org-table-highlight-rectangle (point) (point))
3383 (message "Column %s" (substring match 1)))
3384 ((setq e (assoc var org-table-local-parameters))
3385 (goto-char (org-table-begin))
3386 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
3387 (progn
3388 (goto-char (match-beginning 1))
3389 (org-table-highlight-rectangle)
3390 (message "Local parameter."))
3391 (error "Parameter not found")))
3393 (cond
3394 ((not var) (error "No reference at point"))
3395 ((setq e (assoc var org-table-formula-constants-local))
3396 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3397 var (cdr e)))
3398 ((setq e (assoc var org-table-formula-constants))
3399 (message "Constant: $%s=%s in `org-table-formula-constants'."
3400 var (cdr e)))
3401 ((setq e (and (fboundp 'constants-get) (constants-get var)))
3402 (message "Constant: $%s=%s, from `constants.el'%s."
3403 var e (format " (%s units)" constants-unit-system)))
3404 (t (error "Undefined name $%s" var)))))
3405 (goto-char pos)
3406 (when (and org-show-positions
3407 (not (memq this-command '(org-table-fedit-scroll
3408 org-table-fedit-scroll-down))))
3409 (push pos org-show-positions)
3410 (push org-table-current-begin-pos org-show-positions)
3411 (let ((min (apply 'min org-show-positions))
3412 (max (apply 'max org-show-positions)))
3413 (goto-char min) (recenter 0)
3414 (goto-char max)
3415 (or (pos-visible-in-window-p max) (recenter -1))))
3416 (select-window win))))
3418 (defun org-table-force-dataline ()
3419 "Make sure the cursor is in a dataline in a table."
3420 (unless (save-excursion
3421 (beginning-of-line 1)
3422 (looking-at org-table-dataline-regexp))
3423 (let* ((re org-table-dataline-regexp)
3424 (p1 (save-excursion (re-search-forward re nil 'move)))
3425 (p2 (save-excursion (re-search-backward re nil 'move))))
3426 (cond ((and p1 p2)
3427 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
3428 p1 p2)))
3429 ((or p1 p2) (goto-char (or p1 p2)))
3430 (t (error "No table dataline around here"))))))
3432 (defun org-table-fedit-line-up ()
3433 "Move cursor one line up in the window showing the table."
3434 (interactive)
3435 (org-table-fedit-move 'previous-line))
3437 (defun org-table-fedit-line-down ()
3438 "Move cursor one line down in the window showing the table."
3439 (interactive)
3440 (org-table-fedit-move 'next-line))
3442 (defun org-table-fedit-move (command)
3443 "Move the cursor in the window showing the table.
3444 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3445 (let ((org-table-allow-automatic-line-recalculation nil)
3446 (pos org-pos) (win (selected-window)) p)
3447 (select-window (get-buffer-window (marker-buffer org-pos)))
3448 (setq p (point))
3449 (call-interactively command)
3450 (while (and (org-at-table-p)
3451 (org-at-table-hline-p))
3452 (call-interactively command))
3453 (or (org-at-table-p) (goto-char p))
3454 (move-marker pos (point))
3455 (select-window win)))
3457 (defun org-table-fedit-scroll (N)
3458 (interactive "p")
3459 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
3460 (scroll-other-window N)))
3462 (defun org-table-fedit-scroll-down (N)
3463 (interactive "p")
3464 (org-table-fedit-scroll (- N)))
3466 (defvar org-table-rectangle-overlays nil)
3468 (defun org-table-add-rectangle-overlay (beg end &optional face)
3469 "Add a new overlay."
3470 (let ((ov (make-overlay beg end)))
3471 (overlay-put ov 'face (or face 'secondary-selection))
3472 (push ov org-table-rectangle-overlays)))
3474 (defun org-table-highlight-rectangle (&optional beg end face)
3475 "Highlight rectangular region in a table."
3476 (setq beg (or beg (point)) end (or end (point)))
3477 (let ((b (min beg end))
3478 (e (max beg end))
3479 l1 c1 l2 c2 tmp)
3480 (and (boundp 'org-show-positions)
3481 (setq org-show-positions (cons b (cons e org-show-positions))))
3482 (goto-char (min beg end))
3483 (setq l1 (org-current-line)
3484 c1 (org-table-current-column))
3485 (goto-char (max beg end))
3486 (setq l2 (org-current-line)
3487 c2 (org-table-current-column))
3488 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
3489 (org-goto-line l1)
3490 (beginning-of-line 1)
3491 (loop for line from l1 to l2 do
3492 (when (looking-at org-table-dataline-regexp)
3493 (org-table-goto-column c1)
3494 (skip-chars-backward "^|\n") (setq beg (point))
3495 (org-table-goto-column c2)
3496 (skip-chars-forward "^|\n") (setq end (point))
3497 (org-table-add-rectangle-overlay beg end face))
3498 (beginning-of-line 2))
3499 (goto-char b))
3500 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
3502 (defun org-table-remove-rectangle-highlight (&rest ignore)
3503 "Remove the rectangle overlays."
3504 (unless org-inhibit-highlight-removal
3505 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
3506 (mapc 'delete-overlay org-table-rectangle-overlays)
3507 (setq org-table-rectangle-overlays nil)))
3509 (defvar org-table-coordinate-overlays nil
3510 "Collects the coordinate grid overlays, so that they can be removed.")
3511 (make-variable-buffer-local 'org-table-coordinate-overlays)
3513 (defun org-table-overlay-coordinates ()
3514 "Add overlays to the table at point, to show row/column coordinates."
3515 (interactive)
3516 (mapc 'delete-overlay org-table-coordinate-overlays)
3517 (setq org-table-coordinate-overlays nil)
3518 (save-excursion
3519 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
3520 (goto-char (org-table-begin))
3521 (while (org-at-table-p)
3522 (setq eol (point-at-eol))
3523 (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
3524 (push ov org-table-coordinate-overlays)
3525 (setq hline (looking-at org-table-hline-regexp))
3526 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
3527 (format "%4d" (setq id (1+ id)))))
3528 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
3529 (when hline
3530 (setq ic 0)
3531 (while (re-search-forward "[+|]\\(-+\\)" eol t)
3532 (setq beg (1+ (match-beginning 0))
3533 ic (1+ ic)
3534 s1 (concat "$" (int-to-string ic))
3535 s2 (org-number-to-letters ic)
3536 str (if (eq org-table-use-standard-references t) s2 s1))
3537 (setq ov (make-overlay beg (+ beg (length str))))
3538 (push ov org-table-coordinate-overlays)
3539 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
3540 (beginning-of-line 2)))))
3542 (defun org-table-toggle-coordinate-overlays ()
3543 "Toggle the display of Row/Column numbers in tables."
3544 (interactive)
3545 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
3546 (message "Row/Column number display turned %s"
3547 (if org-table-overlay-coordinates "on" "off"))
3548 (if (and (org-at-table-p) org-table-overlay-coordinates)
3549 (org-table-align))
3550 (unless org-table-overlay-coordinates
3551 (mapc 'delete-overlay org-table-coordinate-overlays)
3552 (setq org-table-coordinate-overlays nil)))
3554 (defun org-table-toggle-formula-debugger ()
3555 "Toggle the formula debugger in tables."
3556 (interactive)
3557 (setq org-table-formula-debug (not org-table-formula-debug))
3558 (message "Formula debugging has been turned %s"
3559 (if org-table-formula-debug "on" "off")))
3561 ;;; The orgtbl minor mode
3563 ;; Define a minor mode which can be used in other modes in order to
3564 ;; integrate the org-mode table editor.
3566 ;; This is really a hack, because the org-mode table editor uses several
3567 ;; keys which normally belong to the major mode, for example the TAB and
3568 ;; RET keys. Here is how it works: The minor mode defines all the keys
3569 ;; necessary to operate the table editor, but wraps the commands into a
3570 ;; function which tests if the cursor is currently inside a table. If that
3571 ;; is the case, the table editor command is executed. However, when any of
3572 ;; those keys is used outside a table, the function uses `key-binding' to
3573 ;; look up if the key has an associated command in another currently active
3574 ;; keymap (minor modes, major mode, global), and executes that command.
3575 ;; There might be problems if any of the keys used by the table editor is
3576 ;; otherwise used as a prefix key.
3578 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3579 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3580 ;; addresses this by checking explicitly for both bindings.
3582 ;; The optimized version (see variable `orgtbl-optimized') takes over
3583 ;; all keys which are bound to `self-insert-command' in the *global map*.
3584 ;; Some modes bind other commands to simple characters, for example
3585 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3586 ;; active, this binding is ignored inside tables and replaced with a
3587 ;; modified self-insert.
3590 (defvar orgtbl-mode-map (make-keymap)
3591 "Keymap for `orgtbl-mode'.")
3593 ;;;###autoload
3594 (defun turn-on-orgtbl ()
3595 "Unconditionally turn on `orgtbl-mode'."
3596 (orgtbl-mode 1))
3598 (defvar org-old-auto-fill-inhibit-regexp nil
3599 "Local variable used by `orgtbl-mode'.")
3601 (defconst orgtbl-line-start-regexp
3602 "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\|TBLNAME\\):\\)"
3603 "Matches a line belonging to an orgtbl.")
3605 (defconst orgtbl-extra-font-lock-keywords
3606 (list (list (concat "^" orgtbl-line-start-regexp ".*")
3607 0 (quote 'org-table) 'prepend))
3608 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
3610 ;; Install it as a minor mode.
3611 (put 'orgtbl-mode :included t)
3612 (put 'orgtbl-mode :menu-tag "Org Table Mode")
3614 ;;;###autoload
3615 (define-minor-mode orgtbl-mode
3616 "The `org-mode' table editor as a minor mode for use in other modes."
3617 :lighter " OrgTbl" :keymap orgtbl-mode-map
3618 (org-load-modules-maybe)
3619 (cond
3620 ((org-mode-p)
3621 ;; Exit without error, in case some hook functions calls this
3622 ;; by accident in org-mode.
3623 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
3624 (orgtbl-mode
3625 (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
3626 ;; Make sure we are first in minor-mode-map-alist
3627 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
3628 ;; FIXME: maybe it should use emulation-mode-map-alists?
3629 (and c (setq minor-mode-map-alist
3630 (cons c (delq c minor-mode-map-alist)))))
3631 (org-set-local (quote org-table-may-need-update) t)
3632 (org-add-hook 'before-change-functions 'org-before-change-function
3633 nil 'local)
3634 (org-set-local 'org-old-auto-fill-inhibit-regexp
3635 auto-fill-inhibit-regexp)
3636 (org-set-local 'auto-fill-inhibit-regexp
3637 (if auto-fill-inhibit-regexp
3638 (concat orgtbl-line-start-regexp "\\|"
3639 auto-fill-inhibit-regexp)
3640 orgtbl-line-start-regexp))
3641 (add-to-invisibility-spec '(org-cwidth))
3642 (when (fboundp 'font-lock-add-keywords)
3643 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
3644 (org-restart-font-lock))
3645 (easy-menu-add orgtbl-mode-menu))
3647 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
3648 (org-table-cleanup-narrow-column-properties)
3649 (org-remove-from-invisibility-spec '(org-cwidth))
3650 (remove-hook 'before-change-functions 'org-before-change-function t)
3651 (when (fboundp 'font-lock-remove-keywords)
3652 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
3653 (org-restart-font-lock))
3654 (easy-menu-remove orgtbl-mode-menu)
3655 (force-mode-line-update 'all))))
3657 (defun org-table-cleanup-narrow-column-properties ()
3658 "Remove all properties related to narrow-column invisibility."
3659 (let ((s 1))
3660 (while (setq s (text-property-any s (point-max)
3661 'display org-narrow-column-arrow))
3662 (remove-text-properties s (1+ s) '(display t)))
3663 (setq s 1)
3664 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
3665 (remove-text-properties s (1+ s) '(org-cwidth t)))
3666 (setq s 1)
3667 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
3668 (remove-text-properties s (1+ s) '(invisible t)))))
3670 (defun orgtbl-make-binding (fun n &rest keys)
3671 "Create a function for binding in the table minor mode.
3672 FUN is the command to call inside a table. N is used to create a unique
3673 command name. KEYS are keys that should be checked in for a command
3674 to execute outside of tables."
3675 (eval
3676 (list 'defun
3677 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
3678 '(arg)
3679 (concat "In tables, run `" (symbol-name fun) "'.\n"
3680 "Outside of tables, run the binding of `"
3681 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
3682 "'.")
3683 '(interactive "p")
3684 (list 'if
3685 '(org-at-table-p)
3686 (list 'call-interactively (list 'quote fun))
3687 (list 'let '(orgtbl-mode)
3688 (list 'call-interactively
3689 (append '(or)
3690 (mapcar (lambda (k)
3691 (list 'key-binding k))
3692 keys)
3693 '('orgtbl-error))))))))
3695 (defun orgtbl-error ()
3696 "Error when there is no default binding for a table key."
3697 (interactive)
3698 (error "This key has no function outside tables"))
3700 (defun orgtbl-setup ()
3701 "Setup orgtbl keymaps."
3702 (let ((nfunc 0)
3703 (bindings
3704 '(([(meta shift left)] org-table-delete-column)
3705 ([(meta left)] org-table-move-column-left)
3706 ([(meta right)] org-table-move-column-right)
3707 ([(meta shift right)] org-table-insert-column)
3708 ([(meta shift up)] org-table-kill-row)
3709 ([(meta shift down)] org-table-insert-row)
3710 ([(meta up)] org-table-move-row-up)
3711 ([(meta down)] org-table-move-row-down)
3712 ("\C-c\C-w" org-table-cut-region)
3713 ("\C-c\M-w" org-table-copy-region)
3714 ("\C-c\C-y" org-table-paste-rectangle)
3715 ("\C-c-" org-table-insert-hline)
3716 ("\C-c}" org-table-toggle-coordinate-overlays)
3717 ("\C-c{" org-table-toggle-formula-debugger)
3718 ("\C-m" org-table-next-row)
3719 ([(shift return)] org-table-copy-down)
3720 ("\C-c?" org-table-field-info)
3721 ("\C-c " org-table-blank-field)
3722 ("\C-c+" org-table-sum)
3723 ("\C-c=" org-table-eval-formula)
3724 ("\C-c'" org-table-edit-formulas)
3725 ("\C-c`" org-table-edit-field)
3726 ("\C-c*" org-table-recalculate)
3727 ("\C-c^" org-table-sort-lines)
3728 ("\M-a" org-table-beginning-of-field)
3729 ("\M-e" org-table-end-of-field)
3730 ([(control ?#)] org-table-rotate-recalc-marks)))
3731 elt key fun cmd)
3732 (while (setq elt (pop bindings))
3733 (setq nfunc (1+ nfunc))
3734 (setq key (org-key (car elt))
3735 fun (nth 1 elt)
3736 cmd (orgtbl-make-binding fun nfunc key))
3737 (org-defkey orgtbl-mode-map key cmd))
3739 ;; Special treatment needed for TAB and RET
3740 (org-defkey orgtbl-mode-map [(return)]
3741 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
3742 (org-defkey orgtbl-mode-map "\C-m"
3743 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
3745 (org-defkey orgtbl-mode-map [(tab)]
3746 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
3747 (org-defkey orgtbl-mode-map "\C-i"
3748 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
3750 (org-defkey orgtbl-mode-map [(shift tab)]
3751 (orgtbl-make-binding 'org-table-previous-field 104
3752 [(shift tab)] [(tab)] "\C-i"))
3755 (unless (featurep 'xemacs)
3756 (org-defkey orgtbl-mode-map [S-iso-lefttab]
3757 (orgtbl-make-binding 'org-table-previous-field 107
3758 [S-iso-lefttab] [backtab] [(shift tab)]
3759 [(tab)] "\C-i")))
3761 (org-defkey orgtbl-mode-map [backtab]
3762 (orgtbl-make-binding 'org-table-previous-field 108
3763 [backtab] [S-iso-lefttab] [(shift tab)]
3764 [(tab)] "\C-i"))
3766 (org-defkey orgtbl-mode-map "\M-\C-m"
3767 (orgtbl-make-binding 'org-table-wrap-region 105
3768 "\M-\C-m" [(meta return)]))
3769 (org-defkey orgtbl-mode-map [(meta return)]
3770 (orgtbl-make-binding 'org-table-wrap-region 106
3771 [(meta return)] "\M-\C-m"))
3773 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
3774 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
3776 (when orgtbl-optimized
3777 ;; If the user wants maximum table support, we need to hijack
3778 ;; some standard editing functions
3779 (org-remap orgtbl-mode-map
3780 'self-insert-command 'orgtbl-self-insert-command
3781 'delete-char 'org-delete-char
3782 'delete-backward-char 'org-delete-backward-char)
3783 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
3784 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
3785 '("OrgTbl"
3786 ["Create or convert" org-table-create-or-convert-from-region
3787 :active (not (org-at-table-p)) :keys "C-c |" ]
3788 "--"
3789 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
3790 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
3791 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
3792 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
3793 "--"
3794 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
3795 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
3796 ["Copy Field from Above"
3797 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
3798 "--"
3799 ("Column"
3800 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
3801 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
3802 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
3803 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
3804 ("Row"
3805 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
3806 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
3807 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
3808 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
3809 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
3810 "--"
3811 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
3812 ("Rectangle"
3813 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
3814 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
3815 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
3816 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
3817 "--"
3818 ("Radio tables"
3819 ["Insert table template" orgtbl-insert-radio-table
3820 (assq major-mode orgtbl-radio-table-templates)]
3821 ["Comment/uncomment table" orgtbl-toggle-comment t])
3822 "--"
3823 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
3824 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
3825 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
3826 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
3827 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
3828 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
3829 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
3830 ["Sum Column/Rectangle" org-table-sum
3831 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
3832 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
3833 ["Debug Formulas"
3834 org-table-toggle-formula-debugger :active (org-at-table-p)
3835 :keys "C-c {"
3836 :style toggle :selected org-table-formula-debug]
3837 ["Show Col/Row Numbers"
3838 org-table-toggle-coordinate-overlays :active (org-at-table-p)
3839 :keys "C-c }"
3840 :style toggle :selected org-table-overlay-coordinates]
3844 (defun orgtbl-ctrl-c-ctrl-c (arg)
3845 "If the cursor is inside a table, realign the table.
3846 If it is a table to be sent away to a receiver, do it.
3847 With prefix arg, also recompute table."
3848 (interactive "P")
3849 (let ((pos (point)) action consts-str consts cst const-str)
3850 (save-excursion
3851 (beginning-of-line 1)
3852 (setq action (cond
3853 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
3854 ((looking-at "[ \t]*|") pos)
3855 ((looking-at "[ \t]*#\\+TBLFM:") 'recalc))))
3856 (cond
3857 ((integerp action)
3858 (goto-char action)
3859 (org-table-maybe-eval-formula)
3860 (if arg
3861 (call-interactively 'org-table-recalculate)
3862 (org-table-maybe-recalculate-line))
3863 (call-interactively 'org-table-align)
3864 (when (orgtbl-send-table 'maybe)
3865 (run-hooks 'orgtbl-after-send-table-hook)))
3866 ((eq action 'recalc)
3867 (save-excursion
3868 (goto-char (point-min))
3869 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t)
3870 (setq const-str (substring-no-properties (match-string 1)))
3871 (setq consts (append consts (org-split-string const-str "[ \t]+")))
3872 (when consts
3873 (let (e)
3874 (while (setq e (pop consts))
3875 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3876 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3877 (setq org-table-formula-constants-local cst)))))
3878 (save-excursion
3879 (beginning-of-line 1)
3880 (skip-chars-backward " \r\n\t")
3881 (if (org-at-table-p)
3882 (org-call-with-arg 'org-table-recalculate t))))
3883 (t (let (orgtbl-mode)
3884 (call-interactively (key-binding "\C-c\C-c")))))))
3886 (defun orgtbl-create-or-convert-from-region (arg)
3887 "Create table or convert region to table, if no conflicting binding.
3888 This installs the table binding `C-c |', but only if there is no
3889 conflicting binding to this key outside orgtbl-mode."
3890 (interactive "P")
3891 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
3892 (if cmd
3893 (call-interactively cmd)
3894 (call-interactively 'org-table-create-or-convert-from-region))))
3896 (defun orgtbl-tab (arg)
3897 "Justification and field motion for `orgtbl-mode'."
3898 (interactive "P")
3899 (if arg (org-table-edit-field t)
3900 (org-table-justify-field-maybe)
3901 (org-table-next-field)))
3903 (defun orgtbl-ret ()
3904 "Justification and field motion for `orgtbl-mode'."
3905 (interactive)
3906 (if (bobp)
3907 (newline)
3908 (org-table-justify-field-maybe)
3909 (org-table-next-row)))
3911 (defun orgtbl-self-insert-command (N)
3912 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
3913 If the cursor is in a table looking at whitespace, the whitespace is
3914 overwritten, and the table is not marked as requiring realignment."
3915 (interactive "p")
3916 (if (and (org-at-table-p)
3918 (and org-table-auto-blank-field
3919 (member last-command
3920 '(orgtbl-hijacker-command-100
3921 orgtbl-hijacker-command-101
3922 orgtbl-hijacker-command-102
3923 orgtbl-hijacker-command-103
3924 orgtbl-hijacker-command-104
3925 orgtbl-hijacker-command-105
3926 yas/expand))
3927 (org-table-blank-field))
3929 (eq N 1)
3930 (looking-at "[^|\n]* +|"))
3931 (let (org-table-may-need-update)
3932 (goto-char (1- (match-end 0)))
3933 (delete-backward-char 1)
3934 (goto-char (match-beginning 0))
3935 (self-insert-command N))
3936 (setq org-table-may-need-update t)
3937 (let* (orgtbl-mode
3939 (cmd (or (key-binding
3940 (or (and (listp function-key-map)
3941 (setq a (assoc last-input-event function-key-map))
3942 (cdr a))
3943 (vector last-input-event)))
3944 'self-insert-command)))
3945 (call-interactively cmd)
3946 (if (and org-self-insert-cluster-for-undo
3947 (eq cmd 'self-insert-command))
3948 (if (not (eq last-command 'orgtbl-self-insert-command))
3949 (setq org-self-insert-command-undo-counter 1)
3950 (if (>= org-self-insert-command-undo-counter 20)
3951 (setq org-self-insert-command-undo-counter 1)
3952 (and (> org-self-insert-command-undo-counter 0)
3953 buffer-undo-list
3954 (not (cadr buffer-undo-list)) ; remove nil entry
3955 (setcdr buffer-undo-list (cddr buffer-undo-list)))
3956 (setq org-self-insert-command-undo-counter
3957 (1+ org-self-insert-command-undo-counter))))))))
3959 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
3960 "Regular expression matching exponentials as produced by calc.")
3962 (defun orgtbl-export (table target)
3963 (require 'org-exp)
3964 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
3965 (lines (org-split-string table "[ \t]*\n[ \t]*"))
3966 org-table-last-alignment org-table-last-column-widths
3967 maxcol column)
3968 (if (not (fboundp func))
3969 (error "Cannot export orgtbl table to %s" target))
3970 (setq lines (org-table-clean-before-export lines))
3971 (setq table
3972 (mapcar
3973 (lambda (x)
3974 (if (string-match org-table-hline-regexp x)
3975 'hline
3976 (org-split-string (org-trim x) "\\s-*|\\s-*")))
3977 lines))
3978 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
3979 table)))
3980 (loop for i from (1- maxcol) downto 0 do
3981 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
3982 (setq column (delq nil column))
3983 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
3984 (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))
3985 (funcall func table nil)))
3987 (defun orgtbl-gather-send-defs ()
3988 "Gather a plist of :name, :transform, :params for each destination before
3989 a radio table."
3990 (save-excursion
3991 (goto-char (org-table-begin))
3992 (let (rtn)
3993 (beginning-of-line 0)
3994 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
3995 (let ((name (org-no-properties (match-string 1)))
3996 (transform (intern (match-string 2)))
3997 (params (if (match-end 3)
3998 (read (concat "(" (match-string 3) ")")))))
3999 (push (list :name name :transform transform :params params)
4000 rtn)
4001 (beginning-of-line 0)))
4002 rtn)))
4004 (defun orgtbl-send-replace-tbl (name txt)
4005 "Find and replace table NAME with TXT."
4006 (save-excursion
4007 (goto-char (point-min))
4008 (unless (re-search-forward
4009 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4010 (error "Don't know where to insert translated table"))
4011 (goto-char (match-beginning 0))
4012 (beginning-of-line 2)
4013 (save-excursion
4014 (let ((beg (point)))
4015 (unless (re-search-forward
4016 (concat "END RECEIVE ORGTBL +" name) nil t)
4017 (error "Cannot find end of insertion region"))
4018 (beginning-of-line 1)
4019 (delete-region beg (point))))
4020 (insert txt "\n")))
4022 ;;;###autoload
4023 (defun org-table-to-lisp (&optional txt)
4024 "Convert the table at point to a Lisp structure.
4025 The structure will be a list. Each item is either the symbol `hline'
4026 for a horizontal separator line, or a list of field values as strings.
4027 The table is taken from the parameter TXT, or from the buffer at point."
4028 (unless txt
4029 (unless (org-at-table-p)
4030 (error "No table at point")))
4031 (let* ((txt (or txt
4032 (buffer-substring-no-properties (org-table-begin)
4033 (org-table-end))))
4034 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4036 (mapcar
4037 (lambda (x)
4038 (if (string-match org-table-hline-regexp x)
4039 'hline
4040 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4041 lines)))
4043 (defun orgtbl-send-table (&optional maybe)
4044 "Send a transformed version of this table to the receiver position.
4045 With argument MAYBE, fail quietly if no transformation is defined for
4046 this table."
4047 (interactive)
4048 (catch 'exit
4049 (unless (org-at-table-p) (error "Not at a table"))
4050 ;; when non-interactive, we assume align has just happened.
4051 (when (interactive-p) (org-table-align))
4052 (let ((dests (orgtbl-gather-send-defs))
4053 (txt (buffer-substring-no-properties (org-table-begin)
4054 (org-table-end)))
4055 (ntbl 0))
4056 (unless dests (if maybe (throw 'exit nil)
4057 (error "Don't know how to transform this table")))
4058 (dolist (dest dests)
4059 (let* ((name (plist-get dest :name))
4060 (transform (plist-get dest :transform))
4061 (params (plist-get dest :params))
4062 (skip (plist-get params :skip))
4063 (skipcols (plist-get params :skipcols))
4065 (lines (org-table-clean-before-export
4066 (nthcdr (or skip 0)
4067 (org-split-string txt "[ \t]*\n[ \t]*"))))
4068 (i0 (if org-table-clean-did-remove-column 2 1))
4069 (table (mapcar
4070 (lambda (x)
4071 (if (string-match org-table-hline-regexp x)
4072 'hline
4073 (org-remove-by-index
4074 (org-split-string (org-trim x) "\\s-*|\\s-*")
4075 skipcols i0)))
4076 lines))
4077 (fun (if (= i0 2) 'cdr 'identity))
4078 (org-table-last-alignment
4079 (org-remove-by-index (funcall fun org-table-last-alignment)
4080 skipcols i0))
4081 (org-table-last-column-widths
4082 (org-remove-by-index (funcall fun org-table-last-column-widths)
4083 skipcols i0))
4084 (txt (if (fboundp transform)
4085 (funcall transform table params)
4086 (error "No such transformation function %s" transform))))
4087 (orgtbl-send-replace-tbl name txt))
4088 (setq ntbl (1+ ntbl)))
4089 (message "Table converted and installed at %d receiver location%s"
4090 ntbl (if (> ntbl 1) "s" ""))
4091 (if (> ntbl 0)
4092 ntbl
4093 nil))))
4095 (defun org-remove-by-index (list indices &optional i0)
4096 "Remove the elements in LIST with indices in INDICES.
4097 First element has index 0, or I0 if given."
4098 (if (not indices)
4099 list
4100 (if (integerp indices) (setq indices (list indices)))
4101 (setq i0 (1- (or i0 0)))
4102 (delq :rm (mapcar (lambda (x)
4103 (setq i0 (1+ i0))
4104 (if (memq i0 indices) :rm x))
4105 list))))
4107 (defun orgtbl-toggle-comment ()
4108 "Comment or uncomment the orgtbl at point."
4109 (interactive)
4110 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4111 (re2 (concat "^" orgtbl-line-start-regexp))
4112 (commented (save-excursion (beginning-of-line 1)
4113 (cond ((looking-at re1) t)
4114 ((looking-at re2) nil)
4115 (t (error "Not at an org table")))))
4116 (re (if commented re1 re2))
4117 beg end)
4118 (save-excursion
4119 (beginning-of-line 1)
4120 (while (looking-at re) (beginning-of-line 0))
4121 (beginning-of-line 2)
4122 (setq beg (point))
4123 (while (looking-at re) (beginning-of-line 2))
4124 (setq end (point)))
4125 (comment-region beg end (if commented '(4) nil))))
4127 (defun orgtbl-insert-radio-table ()
4128 "Insert a radio table template appropriate for this major mode."
4129 (interactive)
4130 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4131 (txt (nth 1 e))
4132 name pos)
4133 (unless e (error "No radio table setup defined for %s" major-mode))
4134 (setq name (read-string "Table name: "))
4135 (while (string-match "%n" txt)
4136 (setq txt (replace-match name t t txt)))
4137 (or (bolp) (insert "\n"))
4138 (setq pos (point))
4139 (insert txt)
4140 (goto-char pos)))
4142 ;; Dynamically bound input and output for table formatting.
4143 (defvar *orgtbl-table* nil
4144 "Carries the current table through formatting routines.")
4145 (defvar *orgtbl-rtn* nil
4146 "Formatting routines push the output lines here.")
4147 ;; Formatting parameters for the current table section.
4148 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4149 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4150 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4151 (defvar *orgtbl-fmt* nil "Format for each entry.")
4152 (defvar *orgtbl-efmt* nil "Format for numbers.")
4153 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4154 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4155 (defvar *orgtbl-lstart* nil "Text starting a row.")
4156 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4157 (defvar *orgtbl-lend* nil "Text ending a row.")
4158 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4160 (defsubst orgtbl-get-fmt (fmt i)
4161 "Retrieve the format from FMT corresponding to the Ith column."
4162 (if (and (not (functionp fmt)) (consp fmt))
4163 (plist-get fmt i)
4164 fmt))
4166 (defsubst orgtbl-apply-fmt (fmt &rest args)
4167 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4168 (cond ((functionp fmt) (apply fmt args))
4169 (fmt (apply 'format fmt args))
4170 (args (car args))
4171 (t args)))
4173 (defsubst orgtbl-eval-str (str)
4174 "If STR is a function, evaluate it with no arguments."
4175 (if (functionp str)
4176 (funcall str)
4177 str))
4179 (defun orgtbl-format-line (line)
4180 "Format LINE as a table row."
4181 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4182 (let* ((i 0)
4183 (line
4184 (mapcar
4185 (lambda (f)
4186 (setq i (1+ i))
4187 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4188 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4189 (orgtbl-apply-fmt efmt (match-string 1 f)
4190 (match-string 2 f))
4191 f)))
4192 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4193 *orgtbl-default-fmt*)
4194 f)))
4195 line)))
4196 (push (if *orgtbl-lfmt*
4197 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4198 (concat (orgtbl-eval-str *orgtbl-lstart*)
4199 (mapconcat 'identity line *orgtbl-sep*)
4200 (orgtbl-eval-str *orgtbl-lend*)))
4201 *orgtbl-rtn*))))
4203 (defun orgtbl-format-section (section-stopper)
4204 "Format lines until the first occurrence of SECTION-STOPPER."
4205 (let (prevline)
4206 (progn
4207 (while (not (eq (car *orgtbl-table*) section-stopper))
4208 (if prevline (orgtbl-format-line prevline))
4209 (setq prevline (pop *orgtbl-table*)))
4210 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4211 (*orgtbl-lend* *orgtbl-llend*)
4212 (*orgtbl-lfmt* *orgtbl-llfmt*))
4213 (orgtbl-format-line prevline))))))
4215 (defun orgtbl-to-generic (table params)
4216 "Convert the orgtbl-mode TABLE to some other format.
4217 This generic routine can be used for many standard cases.
4218 TABLE is a list, each entry either the symbol `hline' for a horizontal
4219 separator line, or a list of fields for that line.
4220 PARAMS is a property list of parameters that can influence the conversion.
4221 For the generic converter, some parameters are obligatory: You need to
4222 specify either :lfmt, or all of (:lstart :lend :sep).
4224 Valid parameters are
4226 :splice When set to t, return only table body lines, don't wrap
4227 them into :tstart and :tend. Default is nil. When :splice
4228 is non-nil, this also means that the exporter should not look
4229 for and interpret header and footer sections.
4231 :hline String to be inserted on horizontal separation lines.
4232 May be nil to ignore hlines.
4234 :sep Separator between two fields
4235 :remove-nil-lines Do not include lines that evaluate to nil.
4238 Each in the following group may be either a string or a function
4239 of no arguments returning a string:
4240 :tstart String to start the table. Ignored when :splice is t.
4241 :tend String to end the table. Ignored when :splice is t.
4242 :lstart String to start a new table line.
4243 :llstart String to start the last table line, defaults to :lstart.
4244 :lend String to end a table line
4245 :llend String to end the last table line, defaults to :lend.
4247 Each in the following group may be a string, a function of one
4248 argument (the field or line) returning a string, or a plist
4249 mapping columns to either of the above:
4250 :lfmt Format for entire line, with enough %s to capture all fields.
4251 If this is present, :lstart, :lend, and :sep are ignored.
4252 :llfmt Format for the entire last line, defaults to :lfmt.
4253 :fmt A format to be used to wrap the field, should contain
4254 %s for the original field value. For example, to wrap
4255 everything in dollars, you could use :fmt \"$%s$\".
4256 This may also be a property list with column numbers and
4257 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4259 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4260 Same as above, specific for the header lines in the table.
4261 All lines before the first hline are treated as header.
4262 If any of these is not present, the data line value is used.
4264 This may be either a string or a function of two arguments:
4265 :efmt Use this format to print numbers with exponentials.
4266 The format should have %s twice for inserting mantissa
4267 and exponent, for example \"%s\\\\times10^{%s}\". This
4268 may also be a property list with column numbers and
4269 formats. :fmt will still be applied after :efmt.
4271 In addition to this, the parameters :skip and :skipcols are always handled
4272 directly by `orgtbl-send-table'. See manual."
4273 (interactive)
4275 (let* ((splicep (plist-get params :splice))
4276 (hline (plist-get params :hline))
4277 (remove-nil-linesp (plist-get params :remove-nil-lines))
4278 (remove-newlines (plist-get params :remove-newlines))
4279 (*orgtbl-hline* hline)
4280 (*orgtbl-table* table)
4281 (*orgtbl-sep* (plist-get params :sep))
4282 (*orgtbl-efmt* (plist-get params :efmt))
4283 (*orgtbl-lstart* (plist-get params :lstart))
4284 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4285 (*orgtbl-lend* (plist-get params :lend))
4286 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4287 (*orgtbl-lfmt* (plist-get params :lfmt))
4288 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4289 (*orgtbl-fmt* (plist-get params :fmt))
4290 *orgtbl-rtn*)
4292 ;; Put header
4293 (unless splicep
4294 (when (plist-member params :tstart)
4295 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4296 (if tstart (push tstart *orgtbl-rtn*)))))
4298 ;; Do we have a heading section? If so, format it and handle the
4299 ;; trailing hline.
4300 (if (and (not splicep)
4301 (or (consp (car *orgtbl-table*))
4302 (consp (nth 1 *orgtbl-table*)))
4303 (memq 'hline (cdr *orgtbl-table*)))
4304 (progn
4305 (when (eq 'hline (car *orgtbl-table*))
4306 ;; there is a hline before the first data line
4307 (and hline (push hline *orgtbl-rtn*))
4308 (pop *orgtbl-table*))
4309 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4310 *orgtbl-lstart*))
4311 (*orgtbl-llstart* (or (plist-get params :hllstart)
4312 *orgtbl-llstart*))
4313 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4314 (*orgtbl-llend* (or (plist-get params :hllend)
4315 (plist-get params :hlend) *orgtbl-llend*))
4316 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4317 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4318 (plist-get params :hlfmt) *orgtbl-llfmt*))
4319 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4320 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4321 (orgtbl-format-section 'hline))
4322 (if hline (push hline *orgtbl-rtn*))
4323 (pop *orgtbl-table*)))
4325 ;; Now format the main section.
4326 (orgtbl-format-section nil)
4328 (unless splicep
4329 (when (plist-member params :tend)
4330 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4331 (if tend (push tend *orgtbl-rtn*)))))
4333 (mapconcat (if remove-newlines
4334 (lambda (tend)
4335 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4336 'identity)
4337 (nreverse (if remove-nil-linesp
4338 (remq nil *orgtbl-rtn*)
4339 *orgtbl-rtn*)) "\n")))
4341 (defun orgtbl-to-tsv (table params)
4342 "Convert the orgtbl-mode table to TAB separated material."
4343 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4344 (defun orgtbl-to-csv (table params)
4345 "Convert the orgtbl-mode table to CSV material.
4346 This does take care of the proper quoting of fields with comma or quotes."
4347 (orgtbl-to-generic table (org-combine-plists
4348 '(:sep "," :fmt org-quote-csv-field)
4349 params)))
4351 (defun orgtbl-to-latex (table params)
4352 "Convert the orgtbl-mode TABLE to LaTeX.
4353 TABLE is a list, each entry either the symbol `hline' for a horizontal
4354 separator line, or a list of fields for that line.
4355 PARAMS is a property list of parameters that can influence the conversion.
4356 Supports all parameters from `orgtbl-to-generic'. Most important for
4357 LaTeX are:
4359 :splice When set to t, return only table body lines, don't wrap
4360 them into a tabular environment. Default is nil.
4362 :fmt A format to be used to wrap the field, should contain %s for the
4363 original field value. For example, to wrap everything in dollars,
4364 use :fmt \"$%s$\". This may also be a property list with column
4365 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4366 The format may also be a function that formats its one argument.
4368 :efmt Format for transforming numbers with exponentials. The format
4369 should have %s twice for inserting mantissa and exponent, for
4370 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4371 This may also be a property list with column numbers and formats.
4372 The format may also be a function that formats its two arguments.
4374 :llend If you find too much space below the last line of a table,
4375 pass a value of \"\" for :llend to suppress the final \\\\.
4377 The general parameters :skip and :skipcols have already been applied when
4378 this function is called."
4379 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4380 org-table-last-alignment ""))
4381 (params2
4382 (list
4383 :tstart (concat "\\begin{tabular}{" alignment "}")
4384 :tend "\\end{tabular}"
4385 :lstart "" :lend " \\\\" :sep " & "
4386 :efmt "%s\\,(%s)" :hline "\\hline")))
4387 (orgtbl-to-generic table (org-combine-plists params2 params))))
4389 (defun orgtbl-to-html (table params)
4390 "Convert the orgtbl-mode TABLE to HTML.
4391 TABLE is a list, each entry either the symbol `hline' for a horizontal
4392 separator line, or a list of fields for that line.
4393 PARAMS is a property list of parameters that can influence the conversion.
4394 Currently this function recognizes the following parameters:
4396 :splice When set to t, return only table body lines, don't wrap
4397 them into a <table> environment. Default is nil.
4399 The general parameters :skip and :skipcols have already been applied when
4400 this function is called. The function does *not* use `orgtbl-to-generic',
4401 so you cannot specify parameters for it."
4402 (let* ((splicep (plist-get params :splice))
4403 (html-table-tag org-export-html-table-tag)
4404 html)
4405 ;; Just call the formatter we already have
4406 ;; We need to make text lines for it, so put the fields back together.
4407 (setq html (org-format-org-table-html
4408 (mapcar
4409 (lambda (x)
4410 (if (eq x 'hline)
4411 "|----+----|"
4412 (concat "| " (mapconcat 'org-html-expand x " | ") " |")))
4413 table)
4414 splicep))
4415 (if (string-match "\n+\\'" html)
4416 (setq html (replace-match "" t t html)))
4417 html))
4419 (defun orgtbl-to-texinfo (table params)
4420 "Convert the orgtbl-mode TABLE to TeXInfo.
4421 TABLE is a list, each entry either the symbol `hline' for a horizontal
4422 separator line, or a list of fields for that line.
4423 PARAMS is a property list of parameters that can influence the conversion.
4424 Supports all parameters from `orgtbl-to-generic'. Most important for
4425 TeXInfo are:
4427 :splice nil/t When set to t, return only table body lines, don't wrap
4428 them into a multitable environment. Default is nil.
4430 :fmt fmt A format to be used to wrap the field, should contain
4431 %s for the original field value. For example, to wrap
4432 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4433 This may also be a property list with column numbers and
4434 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4435 Each format also may be a function that formats its one
4436 argument.
4438 :cf \"f1 f2..\" The column fractions for the table. By default these
4439 are computed automatically from the width of the columns
4440 under org-mode.
4442 The general parameters :skip and :skipcols have already been applied when
4443 this function is called."
4444 (let* ((total (float (apply '+ org-table-last-column-widths)))
4445 (colfrac (or (plist-get params :cf)
4446 (mapconcat
4447 (lambda (x) (format "%.3f" (/ (float x) total)))
4448 org-table-last-column-widths " ")))
4449 (params2
4450 (list
4451 :tstart (concat "@multitable @columnfractions " colfrac)
4452 :tend "@end multitable"
4453 :lstart "@item " :lend "" :sep " @tab "
4454 :hlstart "@headitem ")))
4455 (orgtbl-to-generic table (org-combine-plists params2 params))))
4457 (defun orgtbl-to-orgtbl (table params)
4458 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4459 Useful when slicing one table into many. The :hline, :sep,
4460 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4461 and :tend suppress strings without splicing; they can be set to
4462 provide ORGTBL directives for the generated table."
4463 (let* ((params2
4464 (list
4465 :remove-newlines t
4466 :tstart nil :tend nil
4467 :hline "|---"
4468 :sep " | "
4469 :lstart "| "
4470 :lend " |"))
4471 (params (org-combine-plists params2 params)))
4472 (orgtbl-to-generic table params)))
4474 (defun org-table-get-remote-range (name-or-id form)
4475 "Get a field value or a list of values in a range from table at ID.
4477 NAME-OR-ID may be the name of a table in the current file as set by
4478 a \"#+TBLNAME:\" directive. The first table following this line
4479 will then be used. Alternatively, it may be an ID referring to
4480 any entry, also in a different file. In this case, the first table
4481 in that entry will be referenced.
4482 FORM is a field or range descriptor like \"@2$3\" or or \"B3\" or
4483 \"@I$2..@II$2\". All the references must be absolute, not relative.
4485 The return value is either a single string for a single field, or a
4486 list of the fields in the rectangle ."
4487 (save-match-data
4488 (let ((id-loc nil)
4489 org-table-column-names org-table-column-name-regexp
4490 org-table-local-parameters org-table-named-field-locations
4491 org-table-current-line-types org-table-current-begin-line
4492 org-table-current-begin-pos org-table-dlines
4493 org-table-current-ncol
4494 org-table-hlines org-table-last-alignment
4495 org-table-last-column-widths org-table-last-alignment
4496 org-table-last-column-widths tbeg
4497 buffer loc)
4498 (setq form (org-table-convert-refs-to-rc form))
4499 (save-excursion
4500 (save-restriction
4501 (widen)
4502 (save-excursion
4503 (goto-char (point-min))
4504 (if (re-search-forward
4505 (concat "^[ \t]*#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4506 nil t)
4507 (setq buffer (current-buffer) loc (match-beginning 0))
4508 (setq id-loc (org-id-find name-or-id 'marker))
4509 (unless (and id-loc (markerp id-loc))
4510 (error "Can't find remote table \"%s\"" name-or-id))
4511 (setq buffer (marker-buffer id-loc)
4512 loc (marker-position id-loc))
4513 (move-marker id-loc nil)))
4514 (with-current-buffer buffer
4515 (save-excursion
4516 (save-restriction
4517 (widen)
4518 (goto-char loc)
4519 (forward-char 1)
4520 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4521 (not (match-beginning 1)))
4522 (error "Cannot find a table at NAME or ID %s" name-or-id))
4523 (setq tbeg (point-at-bol))
4524 (org-table-get-specials)
4525 (setq form (org-table-formula-substitute-names form))
4526 (if (and (string-match org-table-range-regexp form)
4527 (> (length (match-string 0 form)) 1))
4528 (save-match-data
4529 (org-table-get-range (match-string 0 form) tbeg 1))
4530 form)))))))))
4532 (provide 'org-table)
4534 ;; arch-tag: 4d21cfdd-0268-440a-84b0-09237a0fe0ef
4536 ;;; org-table.el ends here