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