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