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