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