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