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