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