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