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