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