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