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