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