1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004-2013 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;; This file contains the table editor and spreadsheet for Org-mode.
29 ;; Watch out: Here we are talking about two different kind of tables.
30 ;; Most of the code is for the tables created with the Org-mode table editor.
31 ;; Sometimes, we talk about tables created and edited with the table.el
32 ;; Emacs package. We call the former org-type tables, and the latter
33 ;; table.el-type tables.
41 (declare-function org-export-string-as
"ox"
42 (string backend
&optional body-only ext-plist
))
43 (declare-function aa2u
"ext:ascii-art-to-unicode" ())
44 (defvar orgtbl-mode
) ; defined below
45 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
46 (defvar org-export-html-table-tag
) ; defined in org-exp.el
47 (defvar constants-unit-system
)
48 (defvar org-table-follow-field-mode
)
50 (defvar orgtbl-after-send-table-hook nil
51 "Hook for functions attaching to `C-c C-c', if the table is sent.
52 This can be used to add additional functionality after the table is sent
53 to the receiver position, otherwise, if table is not sent, the functions
56 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
57 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
58 In the optimized version, the table editor takes over all simple keys that
59 normally just insert a character. In tables, the characters are inserted
60 in a way to minimize disturbing the table structure (i.e. in overwrite mode
61 for empty fields). Outside tables, the correct binding of the keys is
64 The default for this option is t if the optimized version is also used in
65 Org-mode. See the variable `org-enable-table-editor' for details. Changing
66 this variable requires a restart of Emacs to become effective."
70 (defcustom orgtbl-radio-table-templates
71 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
72 % END RECEIVE ORGTBL %n
74 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
77 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
78 @c END RECEIVE ORGTBL %n
80 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
83 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
84 <!-- END RECEIVE ORGTBL %n -->
86 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
89 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
90 #+ END RECEIVE ORGTBL %n
92 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
95 "Templates for radio tables in different major modes.
96 All occurrences of %n in a template will be replaced with the name of the
97 table, obtained by prompting the user."
100 (list (symbol :tag
"Major mode")
101 (string :tag
"Format"))))
103 (defgroup org-table-settings nil
104 "Settings for tables in Org-mode."
105 :tag
"Org Table Settings"
108 (defcustom org-table-default-size
"5x2"
109 "The default size for newly created tables, Columns x Rows."
110 :group
'org-table-settings
113 (defcustom org-table-number-regexp
114 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
115 "Regular expression for recognizing numbers in table columns.
116 If a table column contains mostly numbers, it will be aligned to the
117 right. If not, it will be aligned to the left.
119 The default value of this option is a regular expression which allows
120 anything which looks remotely like a number as used in scientific
121 context. For example, all of the following will be considered a
123 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
125 Other options offered by the customize interface are more restrictive."
126 :group
'org-table-settings
128 (const :tag
"Positive Integers"
130 (const :tag
"Integers"
132 (const :tag
"Floating Point Numbers"
133 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
134 (const :tag
"Floating Point Number or Integer"
135 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
136 (const :tag
"Exponential, Floating point, Integer"
137 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
138 (const :tag
"Very General Number-Like, including hex and Calc radix"
139 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
140 (const :tag
"Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
141 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
142 (string :tag
"Regexp:")))
144 (defcustom org-table-number-fraction
0.5
145 "Fraction of numbers in a column required to make the column align right.
146 In a column all non-white fields are considered. If at least
147 this fraction of fields is matched by `org-table-number-regexp',
148 alignment to the right border applies."
149 :group
'org-table-settings
152 (defgroup org-table-editing nil
153 "Behavior of tables during editing in Org-mode."
154 :tag
"Org Table Editing"
157 (defcustom org-table-automatic-realign t
158 "Non-nil means automatically re-align table when pressing TAB or RETURN.
159 When nil, aligning is only done with \\[org-table-align], or after column
161 :group
'org-table-editing
164 (defcustom org-table-auto-blank-field t
165 "Non-nil means automatically blank table field when starting to type into it.
166 This only happens when typing immediately after a field motion
167 command (TAB, S-TAB or RET).
168 Only relevant when `org-enable-table-editor' is equal to `optimized'."
169 :group
'org-table-editing
172 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
173 "Non-nil means automatically exit the follow mode.
174 When nil, the follow mode will stay on and be active in any table
175 the cursor enters. Since the table follow filed mode messes with the
176 window configuration, it is not recommended to set this variable to nil,
177 except maybe locally in a special file that has mostly tables with long
183 (defcustom org-table-fix-formulas-confirm nil
184 "Whether the user should confirm when Org fixes formulas."
185 :group
'org-table-editing
188 (const :tag
"with yes-or-no" yes-or-no-p
)
189 (const :tag
"with y-or-n" y-or-n-p
)
190 (const :tag
"no confirmation" nil
)))
191 (put 'org-table-fix-formulas-confirm
193 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
195 (defcustom org-table-tab-jumps-over-hlines t
196 "Non-nil means tab in the last column of a table with jump over a hline.
197 If a horizontal separator line is following the current line,
198 `org-table-next-field' can either create a new row before that line, or jump
199 over the line. When this option is nil, a new line will be created before
201 :group
'org-table-editing
204 (defgroup org-table-calculation nil
205 "Options concerning tables in Org-mode."
206 :tag
"Org Table Calculation"
209 (defcustom org-table-use-standard-references
'from
210 "Should org-mode work with table references like B3 instead of @3$2?
213 from accept as input, do not present for editing
214 t accept as input and present for editing"
215 :group
'org-table-calculation
217 (const :tag
"Never, don't even check user input for them" nil
)
218 (const :tag
"Always, both as user input, and when editing" t
)
219 (const :tag
"Convert user input, don't offer during editing" from
)))
221 (defcustom org-table-copy-increment t
222 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
223 :group
'org-table-calculation
226 (defcustom org-calc-default-modes
227 '(calc-internal-prec 12
228 calc-float-format
(float 8)
231 calc-symbolic-mode nil
232 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
233 calc-display-working-message t
235 "List with Calc mode settings for use in `calc-eval' for table formulas.
236 The list must contain alternating symbols (Calc modes variables and values).
237 Don't remove any of the default settings, just change the values. Org-mode
238 relies on the variables to be present in the list."
239 :group
'org-table-calculation
242 (defcustom org-table-duration-custom-format
'hours
243 "Format for the output of calc computations like $1+$2;t.
244 The default value is 'hours, and will output the results as a
245 number of hours. Other allowed values are 'seconds, 'minutes and
246 'days, and the output will be a fraction of seconds, minutes or
248 :group
'org-table-calculation
250 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
251 (symbol :tag
"Minutes" 'minutes
)
252 (symbol :tag
"Hours " 'hours
)
253 (symbol :tag
"Days " 'days
)))
255 (defcustom org-table-formula-field-format
"%s"
256 "Format for fields which contain the result of a formula.
257 For example, using \"~%s~\" will display the result within tilde
258 characters. Beware that modifying the display can prevent the
259 field from being used in another formula."
260 :group
'org-table-settings
264 (defcustom org-table-formula-evaluate-inline t
265 "Non-nil means TAB and RET evaluate a formula in current table field.
266 If the current field starts with an equal sign, it is assumed to be a formula
267 which should be evaluated as described in the manual and in the documentation
268 string of the command `org-table-eval-formula'. This feature requires the
270 When this variable is nil, formula calculation is only available through
271 the command \\[org-table-eval-formula]."
272 :group
'org-table-calculation
275 (defcustom org-table-formula-use-constants t
276 "Non-nil means interpret constants in formulas in tables.
277 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
278 by the value given in `org-table-formula-constants', or by a value obtained
279 from the `constants.el' package."
280 :group
'org-table-calculation
283 (defcustom org-table-formula-constants nil
284 "Alist with constant names and values, for use in table formulas.
285 The car of each element is a name of a constant, without the `$' before it.
286 The cdr is the value as a string. For example, if you'd like to use the
287 speed of light in a formula, you would configure
289 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
291 and then use it in an equation like `$1*$c'.
293 Constants can also be defined on a per-file basis using a line like
295 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
296 :group
'org-table-calculation
298 (cons (string :tag
"name")
299 (string :tag
"value"))))
301 (defcustom org-table-allow-automatic-line-recalculation t
302 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
303 Automatically means when TAB or RET or C-c C-c are pressed in the line."
304 :group
'org-table-calculation
307 (defcustom org-table-error-on-row-ref-crossing-hline t
308 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
312 (defcustom org-table-relative-ref-may-cross-hline t
313 "Non-nil means relative formula references may cross hlines.
314 Here are the allowed values:
316 nil Relative references may not cross hlines. They will reference the
317 field next to the hline instead. Coming from below, the reference
318 will be to the field below the hline. Coming from above, it will be
320 t Relative references may cross hlines.
321 error An attempt to cross a hline will throw an error.
323 It is probably good to never set this variable to nil, for the sake of
324 portability of tables."
325 :group
'org-table-calculation
327 (const :tag
"Allow to cross" t
)
328 (const :tag
"Stick to hline" nil
)
329 (const :tag
"Error on attempt to cross" error
)))
331 (defgroup org-table-import-export nil
332 "Options concerning table import and export in Org-mode."
333 :tag
"Org Table Import Export"
336 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
337 "Default export parameters for `org-table-export'.
338 These can be overridden for a specific table by setting the
339 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
340 radio tables for the different export transformations and
341 available parameters."
342 :group
'org-table-import-export
345 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
346 "Detects a table line marked for automatic recalculation.")
347 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
348 "Detects a table line marked for automatic recalculation.")
349 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
350 "Detects a table line marked for automatic recalculation.")
351 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
352 "Searching from within a table (any type) this finds the first line outside the table.")
353 (defvar org-table-last-highlighted-reference nil
)
354 (defvar org-table-formula-history nil
)
356 (defvar org-table-column-names nil
357 "Alist with column names, derived from the `!' line.")
358 (defvar org-table-column-name-regexp nil
359 "Regular expression matching the current column names.")
360 (defvar org-table-local-parameters nil
361 "Alist with parameter names, derived from the `$' line.")
362 (defvar org-table-named-field-locations nil
363 "Alist with locations of named fields.")
365 (defvar org-table-current-line-types nil
366 "Table row types, non-nil only for the duration of a command.")
367 (defvar org-table-current-begin-line nil
368 "Table begin line, non-nil only for the duration of a command.")
369 (defvar org-table-current-begin-pos nil
370 "Table begin position, non-nil only for the duration of a command.")
371 (defvar org-table-current-ncol nil
372 "Number of columns in table, non-nil only for the duration of a command.")
373 (defvar org-table-dlines nil
374 "Vector of data line line numbers in the current table.")
375 (defvar org-table-hlines nil
376 "Vector of hline line numbers in the current table.")
378 (defconst org-table-range-regexp
379 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
381 "Regular expression for matching ranges in formulas.")
383 (defconst org-table-range-regexp2
385 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
387 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
388 "Match a range for reference display.")
390 (defun org-table-colgroup-line-p (line)
391 "Is this a table line colgroup information?"
393 (and (string-match "[<>]\\|&[lg]t;" line
)
394 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
400 (not (member s
'("" "<" ">" "<>" "<" ">" "<>"))))
401 (org-split-string (match-string 1 line
) "[ \t]*|[ \t]*")))))))
403 (defun org-table-cookie-line-p (line)
404 "Is this a table line with only alignment/width cookies?"
406 (and (string-match "[<>]\\|&[lg]t;" line
)
408 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line
)
409 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line
))
410 (not (delq nil
(mapcar
412 (not (or (equal s
"")
414 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s
)
416 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'"
418 (org-split-string (match-string 1 line
)
419 "[ \t]*|[ \t]*")))))))
421 (defvar org-table-colgroup-info nil
) ; Dynamically scoped.
422 (defun org-table-clean-before-export (lines &optional maybe-quoted
)
423 "Check if the table has a marking column.
424 If yes remove the column and the special lines."
425 (setq org-table-colgroup-info nil
)
428 (lambda (x) (or (string-match "^[ \t]*|-" x
)
431 "^[ \t]*| *\\\\?\\([\#!$*_^ /]\\) *|"
432 "^[ \t]*| *\\([\#!$*_^ /]\\) *|")
435 ;; No special marking column
437 (setq org-table-clean-did-remove-column nil
)
442 ((org-table-colgroup-line-p x
)
443 ;; This line contains colgroup info, extract it
444 ;; and then discard the line
445 (setq org-table-colgroup-info
447 (cond ((member x
'("<" "<")) :start
)
448 ((member x
'(">" ">")) :end
)
449 ((member x
'("<>" "<>")) :startend
)))
450 (org-split-string x
"[ \t]*|[ \t]*")))
452 ((org-table-cookie-line-p x
)
453 ;; This line contains formatting cookies, discard it
457 ;; there is a special marking column
458 (setq org-table-clean-did-remove-column t
)
463 ((org-table-colgroup-line-p x
)
464 ;; This line contains colgroup info, extract it
465 ;; and then discard the line
466 (setq org-table-colgroup-info
468 (cond ((member x
'("<" "<")) :start
)
469 ((member x
'(">" ">")) :end
)
470 ((member x
'("<>" "<>")) :startend
)))
471 (cdr (org-split-string x
"[ \t]*|[ \t]*"))))
473 ((org-table-cookie-line-p x
)
474 ;; This line contains formatting cookies, discard it
476 ((string-match "^[ \t]*| *\\([!_^/$]\\|\\\\\\$\\) *|" x
)
479 ((or (string-match "^\\([ \t]*\\)|-+\\+" x
)
480 (string-match "^\\([ \t]*\\)|[^|]*|" x
))
481 ;; remove the first column
482 (replace-match "\\1|" t nil x
))))
485 (defconst org-table-translate-regexp
486 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
487 "Match a reference that needs translation, for reference display.")
490 (defun org-table-create-with-table.el
()
491 "Use the table.el package to insert a new table.
492 If there is already a table at point, convert between Org-mode tables
493 and table.el tables."
498 (if (y-or-n-p "Convert table to Org-mode table? ")
499 (org-table-convert)))
501 (when (y-or-n-p "Convert table to table.el table? ")
503 (org-table-convert)))
504 (t (call-interactively 'table-insert
))))
507 (defun org-table-create-or-convert-from-region (arg)
508 "Convert region to table, or create an empty table.
509 If there is an active region, convert it to a table, using the function
510 `org-table-convert-region'. See the documentation of that function
511 to learn how the prefix argument is interpreted to determine the field
513 If there is no such region, create an empty table with `org-table-create'."
515 (if (org-region-active-p)
516 (org-table-convert-region (region-beginning) (region-end) arg
)
517 (org-table-create arg
)))
520 (defun org-table-create (&optional size
)
521 "Query for a size and insert a table skeleton.
522 SIZE is a string Columns x Rows like for example \"3x2\"."
525 (setq size
(read-string
526 (concat "Table size Columns x Rows [e.g. "
527 org-table-default-size
"]: ")
528 "" nil org-table-default-size
)))
531 (indent (make-string (current-column) ?\
))
532 (split (org-split-string size
" *x *"))
533 (rows (string-to-number (nth 1 split
)))
534 (columns (string-to-number (car split
)))
535 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
537 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
538 (point-at-bol) (point)))
539 (beginning-of-line 1)
541 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
542 (dotimes (i rows
) (insert line
))
545 ;; Insert a hline after the first row.
553 (defun org-table-convert-region (beg0 end0
&optional separator
)
554 "Convert region to a table.
555 The region goes from BEG0 to END0, but these borders will be moved
556 slightly, to make sure a beginning of line in the first line is included.
558 SEPARATOR specifies the field separator in the lines. It can have the
561 '(4) Use the comma as a field separator
562 '(16) Use a TAB as field separator
563 integer When a number, use that many spaces as field separator
564 nil When nil, the command tries to be smart and figure out the
565 separator in the following way:
566 - when each line contains a TAB, assume TAB-separated material
567 - when each line contains a comma, assume CSV material
568 - else, assume one or more SPACE characters as separator."
570 (let* ((beg (min beg0 end0
))
571 (end (max beg0 end0
))
574 (beginning-of-line 1)
575 (setq beg
(point-marker))
577 (if (bolp) (backward-char 1) (end-of-line 1))
578 (setq end
(point-marker))
579 ;; Get the right field separator
584 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
585 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
588 (if (equal separator
'(4))
589 (while (< (point) end
)
590 ;; parse the csv stuff
592 ((looking-at "^") (insert "| "))
593 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
594 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
595 (replace-match "\\1")
596 (if (looking-at "\"") (insert "\"")))
597 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
598 ((looking-at "[ \t]*,") (replace-match " | "))
599 (t (beginning-of-line 2))))
601 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
602 ((equal separator
'(16)) "^\\|\t")
603 ((integerp separator
)
605 (error "Number of spaces in separator must be >= 1")
606 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
607 (t (error "This should not happen"))))
608 (while (re-search-forward re end t
)
609 (replace-match "| " t t
)))
614 (defun org-table-import (file arg
)
615 "Import FILE as a table.
616 The file is assumed to be tab-separated. Such files can be produced by most
617 spreadsheet and database applications. If no tabs (at least one per line)
618 are found, lines will be split on whitespace into fields."
620 (or (bolp) (newline))
623 (insert-file-contents file
)
624 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
627 (defvar org-table-last-alignment
)
628 (defvar org-table-last-column-widths
)
630 (defun org-table-export (&optional file format
)
631 "Export table to a file, with configurable format.
632 Such a file can be imported into usual spreadsheet programs.
634 FILE can be the output file name. If not given, it will be taken
635 from a TABLE_EXPORT_FILE property in the current entry or higher
636 up in the hierarchy, or the user will be prompted for a file
637 name. FORMAT can be an export format, of the same kind as it
638 used when `orgtbl-mode' sends a table in a different format.
640 The command suggests a format depending on TABLE_EXPORT_FORMAT,
641 whether it is set locally or up in the hierarchy, then on the
642 extension of the given file name, and finally on the variable
643 `org-table-export-default-format'."
645 (unless (org-at-table-p) (error "No table at point"))
646 (org-table-align) ;; make sure we have everything we need
647 (let* ((beg (org-table-begin))
648 (end (org-table-end))
649 (txt (buffer-substring-no-properties beg end
))
650 (file (or file
(org-entry-get beg
"TABLE_EXPORT_FILE" t
)))
651 (formats '("orgtbl-to-tsv" "orgtbl-to-csv"
652 "orgtbl-to-latex" "orgtbl-to-html"
653 "orgtbl-to-generic" "orgtbl-to-texinfo"
656 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)))
657 buf deffmt-readable fileext
)
659 (setq file
(read-file-name "Export table to: "))
660 (unless (or (not (file-exists-p file
))
661 (y-or-n-p (format "Overwrite file %s? " file
)))
663 (if (file-directory-p file
)
664 (error "This is a directory path, not a file"))
665 (if (and (buffer-file-name)
666 (equal (file-truename file
)
667 (file-truename (buffer-file-name))))
668 (error "Please specify a file name that is different from current"))
669 (setq fileext
(concat (file-name-extension file
) "$"))
671 (setq deffmt-readable
672 (or (car (delq nil
(mapcar (lambda(f) (if (string-match fileext f
) f
)) formats
)))
673 org-table-export-default-format
))
674 (while (string-match "\t" deffmt-readable
)
675 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
676 (while (string-match "\n" deffmt-readable
)
677 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
678 (setq format
(org-completing-read "Format: " formats nil nil deffmt-readable
)))
679 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
680 (let* ((transform (intern (match-string 1 format
)))
681 (params (if (match-end 2)
682 (read (concat "(" (match-string 2 format
) ")"))))
683 (skip (plist-get params
:skip
))
684 (skipcols (plist-get params
:skipcols
))
685 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
686 (lines (org-table-clean-before-export lines
))
687 (i0 (if org-table-clean-did-remove-column
2 1))
690 (if (string-match org-table-hline-regexp x
)
693 (org-split-string (org-trim x
) "\\s-*|\\s-*")
696 (fun (if (= i0
2) 'cdr
'identity
))
697 (org-table-last-alignment
698 (org-remove-by-index (funcall fun org-table-last-alignment
)
700 (org-table-last-column-widths
701 (org-remove-by-index (funcall fun org-table-last-column-widths
)
704 (unless (fboundp transform
)
705 (error "No such transformation function %s" transform
))
706 (setq txt
(funcall transform table params
))
708 (with-current-buffer (find-file-noselect file
)
709 (setq buf
(current-buffer))
715 (message "Export done."))
716 (error "TABLE_EXPORT_FORMAT invalid"))))
718 (defvar org-table-aligned-begin-marker
(make-marker)
719 "Marker at the beginning of the table last aligned.
720 Used to check if cursor still is in that table, to minimize realignment.")
721 (defvar org-table-aligned-end-marker
(make-marker)
722 "Marker at the end of the table last aligned.
723 Used to check if cursor still is in that table, to minimize realignment.")
724 (defvar org-table-last-alignment nil
725 "List of flags for flushright alignment, from the last re-alignment.
726 This is being used to correctly align a single field after TAB or RET.")
727 (defvar org-table-last-column-widths nil
728 "List of max width of fields in each column.
729 This is being used to correctly align a single field after TAB or RET.")
730 (defvar org-table-formula-debug nil
731 "Non-nil means debug table formulas.
732 When nil, simply write \"#ERROR\" in corrupted fields.")
733 (make-variable-buffer-local 'org-table-formula-debug
)
734 (defvar org-table-overlay-coordinates nil
735 "Overlay coordinates after each align of a table.")
736 (make-variable-buffer-local 'org-table-overlay-coordinates
)
738 (defvar org-last-recalc-line nil
)
739 (defvar org-table-do-narrow t
) ; for dynamic scoping
740 (defconst org-narrow-column-arrow
"=>"
741 "Used as display property in narrowed table columns.")
744 (defun org-table-align ()
745 "Align the table at point by aligning all vertical bars."
749 (beg (org-table-begin))
750 (end (org-table-end))
751 ;; Current cursor position
752 (linepos (org-current-line))
753 (colpos (org-table-current-column))
754 (winstart (window-start))
755 (winstartline (org-current-line (min winstart
(1- (point-max)))))
756 lines
(new "") lengths l typenums ty fields maxfields i
764 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
766 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
767 emptystrings links dates emph raise narrow
768 falign falign1 fmax f1 len c e space
)
770 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
771 ;; Check if we have links or dates
773 (setq links
(re-search-forward org-bracket-link-regexp end t
))
775 (setq emph
(and org-hide-emphasis-markers
776 (re-search-forward org-emph-re end t
)))
778 (setq raise
(and org-use-sub-superscripts
779 (re-search-forward org-match-substring-regexp end t
)))
781 (setq dates
(and org-display-custom-times
782 (re-search-forward org-ts-regexp-both end t
)))
783 ;; Make sure the link properties are right
784 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
785 ;; Make sure the date properties are right
786 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
787 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
788 (when raise
(goto-char beg
) (while (org-raise-scripts end
)))
790 ;; Check if we are narrowing any columns
792 (setq narrow
(and org-table-do-narrow
793 org-format-transports-properties-p
794 (re-search-forward "<[lrc]?[0-9]+>" end t
)))
796 (setq falign
(re-search-forward "<[lrc][0-9]*>" end t
))
799 (setq lines
(org-split-string
800 (buffer-substring beg end
) "\n"))
801 ;; Store the indentation of the first line
802 (if (string-match "^ *" (car lines
))
803 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
804 ;; Mark the hlines by setting the corresponding element to nil
805 ;; At the same time, we remove trailing space.
806 (setq lines
(mapcar (lambda (l)
807 (if (string-match "^ *|-" l
)
809 (if (string-match "[ \t]+$" l
)
810 (substring l
0 (match-beginning 0))
813 ;; Get the data fields by splitting the lines.
816 (org-split-string l
" *| *"))
817 (delq nil
(copy-sequence lines
))))
818 ;; How many fields in the longest line?
820 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
822 (kill-region beg end
)
823 (org-table-create org-table-default-size
)
824 (error "Empty table - created default table")))
825 ;; A list of empty strings to fill any short rows on output
826 (setq emptystrings
(make-list maxfields
""))
827 ;; Check for special formatting.
829 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
830 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
831 ;; Check if there is an explicit width specified
833 (when (or narrow falign
)
834 (setq c column fmax nil falign1 nil
)
837 (when (and (stringp e
) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e
))
838 (if (match-end 1) (setq falign1
(match-string 1 e
)))
839 (if (and org-table-do-narrow
(match-end 2))
840 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
841 ;; Find fields that are wider than fmax, and shorten them
843 (loop for xx in column do
844 (when (and (stringp xx
)
845 (> (org-string-width xx
) fmax
))
846 (org-add-props xx nil
848 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
849 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
851 (error "Cannot narrow field starting with wide link \"%s\""
852 (match-string 0 xx
)))
853 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
854 (add-text-properties (- f1
2) f1
855 (list 'display org-narrow-column-arrow
)
857 ;; Get the maximum width for each column
858 (push (apply 'max
(or fmax
1) 1 (mapcar 'org-string-width column
))
860 ;; Get the fraction of numbers, to decide about alignment of the column
862 (push (equal (downcase falign1
) "r") typenums
)
863 (setq cnt
0 frac
0.0)
864 (loop for x in column do
867 (setq frac
( / (+ (* frac cnt
)
868 (if (string-match org-table-number-regexp x
) 1 0))
869 (setq cnt
(1+ cnt
))))))
870 (push (>= frac org-table-number-fraction
) typenums
)))
871 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
873 ;; Store the alignment of this table, for later editing of single fields
874 (setq org-table-last-alignment typenums
875 org-table-last-column-widths lengths
)
877 ;; With invisible characters, `format' does not get the field width right
878 ;; So we need to make these fields wide by hand.
879 (when (or links emph raise
)
880 (loop for i from
0 upto
(1- maxfields
) do
881 (setq len
(nth i lengths
))
882 (loop for j from
0 upto
(1- (length fields
)) do
883 (setq c
(nthcdr i
(car (nthcdr j fields
))))
884 (if (and (stringp (car c
))
885 (or (text-property-any 0 (length (car c
))
886 'invisible
'org-link
(car c
))
887 (text-property-any 0 (length (car c
))
888 'org-dwidth t
(car c
)))
889 (< (org-string-width (car c
)) len
))
891 (setq space
(make-string (- len
(org-string-width (car c
))) ?\
))
892 (setcar c
(if (nth i typenums
)
893 (concat space
(car c
))
894 (concat (car c
) space
))))))))
896 ;; Compute the formats needed for output of the table
897 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
898 (while (setq l
(pop lengths
))
899 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
900 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
901 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
902 (setq rfmt
(concat rfmt
"\n")
903 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
907 (if l
(apply 'format rfmt
908 (append (pop fields
) emptystrings
))
911 (move-marker org-table-aligned-begin-marker
(point))
913 ;; Replace the old one
914 (delete-region (point) end
)
915 (move-marker end nil
)
916 (move-marker org-table-aligned-end-marker
(point))
917 (when (and orgtbl-mode
(not (derived-mode-p 'org-mode
)))
918 (goto-char org-table-aligned-begin-marker
)
919 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
920 ;; Try to move to the old location
921 (org-goto-line winstartline
)
922 (setq winstart
(point-at-bol))
923 (org-goto-line linepos
)
924 (when (eq (window-buffer (selected-window)) (current-buffer))
925 (set-window-start (selected-window) winstart
'noforce
))
926 (org-table-goto-column colpos
)
927 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
928 (setq org-table-may-need-update nil
)
931 (defun org-table-begin (&optional table-type
)
932 "Find the beginning of the table and return its position.
933 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
935 (if (not (re-search-backward
936 (if table-type org-table-any-border-regexp
937 org-table-border-regexp
)
939 (progn (goto-char (point-min)) (point))
940 (goto-char (match-beginning 0))
941 (beginning-of-line 2)
944 (defun org-table-end (&optional table-type
)
945 "Find the end of the table and return its position.
946 With argument TABLE-TYPE, go to the end of a table.el-type table."
948 (if (not (re-search-forward
949 (if table-type org-table-any-border-regexp
950 org-table-border-regexp
)
952 (goto-char (point-max))
953 (goto-char (match-beginning 0)))
957 (defun org-table-justify-field-maybe (&optional new
)
958 "Justify the current field, text to left, number to right.
959 Optional argument NEW may specify text to replace the current field content."
961 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
962 ((org-at-table-hline-p))
964 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
966 (< (point) org-table-aligned-begin-marker
)
967 (>= (point) org-table-aligned-end-marker
)))
968 ;; This is not the same table, force a full re-align
969 (setq org-table-may-need-update t
))
970 (t ;; realign the current field, based on previous full realign
971 (let* ((pos (point)) s
972 (col (org-table-current-column))
973 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
976 (skip-chars-backward "^|\n")
977 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
979 (setq s
(match-string 1)
981 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
982 e
(not (= (match-beginning 2) (match-end 2))))
983 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
984 l
(if e
"|" (setq org-table-may-need-update t
) ""))
987 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
988 (setq n
(format f new
))
989 (setq n
(concat new
"|") org-table-may-need-update t
)))
990 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
992 (let (org-table-may-need-update)
993 (replace-match n t t
))))
994 (setq org-table-may-need-update t
))
998 (defun org-table-next-field ()
999 "Go to the next field in the current table, creating new lines as needed.
1000 Before doing so, re-align the table if necessary."
1002 (org-table-maybe-eval-formula)
1003 (org-table-maybe-recalculate-line)
1004 (if (and org-table-automatic-realign
1005 org-table-may-need-update
)
1007 (let ((end (org-table-end)))
1008 (if (org-at-table-hline-p)
1012 (re-search-forward "|" end
)
1013 (if (looking-at "[ \t]*$")
1014 (re-search-forward "|" end
))
1015 (if (and (looking-at "-")
1016 org-table-tab-jumps-over-hlines
1017 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
1018 (goto-char (match-beginning 1)))
1019 (if (looking-at "-")
1021 (beginning-of-line 0)
1022 (org-table-insert-row 'below
))
1023 (if (looking-at " ") (forward-char 1))))
1025 (org-table-insert-row 'below
)))))
1028 (defun org-table-previous-field ()
1029 "Go to the previous field in the table.
1030 Before doing so, re-align the table if necessary."
1032 (org-table-justify-field-maybe)
1033 (org-table-maybe-recalculate-line)
1034 (if (and org-table-automatic-realign
1035 org-table-may-need-update
)
1037 (if (org-at-table-hline-p)
1041 (re-search-backward "|" (org-table-begin))
1042 (re-search-backward "|" (org-table-begin)))
1043 (error (error "Cannot move to previous table field")))
1044 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1045 (re-search-backward "|" (org-table-begin)))
1046 (if (looking-at "| ?")
1047 (goto-char (match-end 0))))
1049 (defun org-table-beginning-of-field (&optional n
)
1050 "Move to the end of the current table field.
1051 If already at or after the end, move to the end of the next table field.
1052 With numeric argument N, move N-1 fields forward first."
1054 (let ((pos (point)))
1057 (org-table-previous-field))
1058 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1059 (error "No more table fields before the current")
1060 (goto-char (match-end 0))
1061 (and (looking-at " ") (forward-char 1)))
1062 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1064 (defun org-table-end-of-field (&optional n
)
1065 "Move to the beginning of the current table field.
1066 If already at or before the beginning, move to the beginning of the
1068 With numeric argument N, move N-1 fields backward first."
1070 (let ((pos (point)))
1073 (org-table-next-field))
1074 (when (re-search-forward "|" (point-at-eol 1) t
)
1076 (skip-chars-backward " ")
1077 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1079 (if (<= (point) pos
) (org-table-end-of-field 2))))
1082 (defun org-table-next-row ()
1083 "Go to the next row (same column) in the current table.
1084 Before doing so, re-align the table if necessary."
1086 (org-table-maybe-eval-formula)
1087 (org-table-maybe-recalculate-line)
1088 (if (or (looking-at "[ \t]*$")
1089 (save-excursion (skip-chars-backward " \t") (bolp)))
1091 (if (and org-table-automatic-realign
1092 org-table-may-need-update
)
1094 (let ((col (org-table-current-column)))
1095 (beginning-of-line 2)
1096 (if (or (not (org-at-table-p))
1097 (org-at-table-hline-p))
1099 (beginning-of-line 0)
1100 (org-table-insert-row 'below
)))
1101 (org-table-goto-column col
)
1102 (skip-chars-backward "^|\n\r")
1103 (if (looking-at " ") (forward-char 1)))))
1106 (defun org-table-copy-down (n)
1107 "Copy a field down in the current column.
1108 If the field at the cursor is empty, copy into it the content of
1109 the nearest non-empty field above. With argument N, use the Nth
1110 non-empty field. If the current field is not empty, it is copied
1111 down to the next row, and the cursor is moved with it.
1112 Therefore, repeating this command causes the column to be filled
1114 If the variable `org-table-copy-increment' is non-nil and the
1115 field is an integer or a timestamp, it will be incremented while
1116 copying. In the case of a timestamp, increment by one day."
1118 (let* ((colpos (org-table-current-column))
1119 (col (current-column))
1120 (field (org-table-get-field))
1121 (non-empty (string-match "[^ \t]" field
))
1122 (beg (org-table-begin))
1125 (org-table-check-inside-data-field)
1128 (setq txt
(org-trim field
))
1129 (org-table-next-row)
1130 (org-table-blank-field))
1134 (while (progn (beginning-of-line 1)
1135 (re-search-backward org-table-dataline-regexp
1137 (org-table-goto-column colpos t
)
1138 (if (and (looking-at
1139 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1140 (<= (setq n
(1- n
)) 0))
1141 (throw 'exit
(match-string 1))))))))
1144 (if (and org-table-copy-increment
1145 (not (equal orig-n
0))
1146 (string-match "^[0-9]+$" txt
)
1147 (< (string-to-number txt
) 100000000))
1148 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
1150 (org-move-to-column col
)
1151 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1152 (org-timestamp-up-day)
1153 (org-table-maybe-recalculate-line))
1155 (org-move-to-column col
))
1156 (error "No non-empty field found"))))
1158 (defun org-table-check-inside-data-field (&optional noerror
)
1159 "Is point inside a table data field?
1160 I.e. not on a hline or before the first or after the last column?
1161 This actually throws an error, so it aborts the current command."
1162 (if (or (not (org-at-table-p))
1163 (= (org-table-current-column) 0)
1164 (org-at-table-hline-p)
1165 (looking-at "[ \t]*$"))
1168 (error "Not in table data field"))
1171 (defvar org-table-clip nil
1172 "Clipboard for table regions.")
1174 (defun org-table-get (line column
)
1175 "Get the field in table line LINE, column COLUMN.
1176 If LINE is larger than the number of data lines in the table, the function
1177 returns nil. However, if COLUMN is too large, we will simply return an
1179 If LINE is nil, use the current line.
1180 If column is nil, use the current column."
1181 (setq column
(or column
(org-table-current-column)))
1183 (and (or (not line
) (org-table-goto-line line
))
1184 (org-trim (org-table-get-field column
)))))
1186 (defun org-table-put (line column value
&optional align
)
1187 "Put VALUE into line LINE, column COLUMN.
1188 When ALIGN is set, also realign the table."
1189 (setq column
(or column
(org-table-current-column)))
1190 (prog1 (save-excursion
1191 (and (or (not line
) (org-table-goto-line line
))
1192 (progn (org-table-goto-column column nil
'force
) t
)
1193 (org-table-get-field column value
)))
1194 (and align
(org-table-align))))
1196 (defun org-table-current-line ()
1197 "Return the index of the current data line."
1198 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1200 (goto-char (org-table-begin))
1201 (while (and (re-search-forward org-table-dataline-regexp end t
)
1203 (< (point-at-eol) pos
))))
1206 (defun org-table-goto-line (N)
1207 "Go to the Nth data line in the current table.
1208 Return t when the line exists, nil if it does not exist."
1209 (goto-char (org-table-begin))
1210 (let ((end (org-table-end)) (cnt 0))
1211 (while (and (re-search-forward org-table-dataline-regexp end t
)
1212 (< (setq cnt
(1+ cnt
)) N
)))
1215 (defun org-table-blank-field ()
1216 "Blank the current table field or active region."
1218 (org-table-check-inside-data-field)
1219 (if (and (org-called-interactively-p 'any
) (org-region-active-p))
1220 (let (org-table-clip)
1221 (org-table-cut-region (region-beginning) (region-end)))
1222 (skip-chars-backward "^|")
1224 (if (looking-at "|[^|\n]+")
1225 (let* ((pos (match-beginning 0))
1226 (match (match-string 0))
1227 (len (org-string-width match
)))
1228 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1229 (goto-char (+ 2 pos
))
1230 (substring match
1)))))
1232 (defun org-table-get-field (&optional n replace
)
1233 "Return the value of the field in column N of current row.
1234 N defaults to current field.
1235 If REPLACE is a string, replace field with this value. The return value
1236 is always the old value."
1237 (and n
(org-table-goto-column n
))
1238 (skip-chars-backward "^|\n")
1240 (if (looking-at "|[^|\r\n]*")
1241 (let* ((pos (match-beginning 0))
1242 (val (buffer-substring (1+ pos
) (match-end 0))))
1244 (replace-match (concat "|" (if (equal replace
"") " " replace
))
1246 (goto-char (min (point-at-eol) (+ 2 pos
)))
1248 (forward-char 1) ""))
1251 (defun org-table-field-info (arg)
1252 "Show info about the current field, and highlight any reference at point."
1254 (org-table-get-specials)
1256 (let* ((pos (point))
1257 (col (org-table-current-column))
1258 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1259 (name (car (rassoc (list (org-current-line) col
)
1260 org-table-named-field-locations
)))
1261 (eql (org-table-expand-lhs-ranges
1264 (cons (org-table-formula-handle-first/last-rc
1266 (org-table-get-stored-formulas))))
1267 (dline (org-table-current-dline))
1268 (ref (format "@%d$%d" dline col
))
1269 (ref1 (org-table-convert-refs-to-an ref
))
1270 (fequation (or (assoc name eql
) (assoc ref eql
)))
1271 (cequation (assoc (int-to-string col
) eql
))
1272 (eqn (or fequation cequation
)))
1273 (if (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))
1274 (setq eqn
(get-text-property 0 :orig-eqn
(car eqn
))))
1277 (org-table-show-reference 'local
)
1279 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1281 (if cname
(concat " or $" cname
) "")
1283 (if name
(concat " or $" name
) "")
1284 ;; FIXME: formula info not correct if special table line
1286 (concat ", formula: "
1287 (org-table-formula-to-user
1289 (if (string-match "^[$@]"(car eqn
)) "" "$")
1290 (car eqn
) "=" (cdr eqn
))))
1293 (defun org-table-current-column ()
1294 "Find out which column we are in."
1296 (if (org-called-interactively-p 'any
) (org-table-check-inside-data-field))
1298 (let ((cnt 0) (pos (point)))
1299 (beginning-of-line 1)
1300 (while (search-forward "|" pos t
)
1301 (setq cnt
(1+ cnt
)))
1302 (when (org-called-interactively-p 'interactive
)
1303 (message "In table column %d" cnt
))
1307 (defun org-table-current-dline ()
1308 "Find out what table data line we are in.
1309 Only data lines count for this."
1311 (when (org-called-interactively-p 'any
)
1312 (org-table-check-inside-data-field))
1314 (let ((cnt 0) (pos (point)))
1315 (goto-char (org-table-begin))
1316 (while (<= (point) pos
)
1317 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1318 (beginning-of-line 2))
1319 (when (org-called-interactively-p 'any
)
1320 (message "This is table line %d" cnt
))
1324 (defun org-table-goto-column (n &optional on-delim force
)
1325 "Move the cursor to the Nth column in the current table line.
1326 With optional argument ON-DELIM, stop with point before the left delimiter
1328 If there are less than N fields, just go to after the last delimiter.
1329 However, when FORCE is non-nil, create new columns if necessary."
1331 (beginning-of-line 1)
1333 (while (and (> (setq n
(1- n
)) -
1)
1334 (or (search-forward "|" (point-at-eol) t
)
1336 (progn (end-of-line 1)
1337 (skip-chars-backward "^|")
1340 (when (and force
(not (looking-at ".*|")))
1341 (save-excursion (end-of-line 1) (insert " | ")))
1344 (if (looking-at " ") (forward-char 1)))))
1347 (defun org-table-insert-column ()
1348 "Insert a new column into the table."
1350 (if (not (org-at-table-p))
1351 (error "Not at a table"))
1352 (org-table-find-dataline)
1353 (let* ((col (max 1 (org-table-current-column)))
1354 (beg (org-table-begin))
1355 (end (org-table-end))
1356 ;; Current cursor position
1357 (linepos (org-current-line))
1360 (while (< (point) end
)
1361 (if (org-at-table-hline-p)
1363 (org-table-goto-column col t
)
1365 (beginning-of-line 2))
1366 (move-marker end nil
)
1367 (org-goto-line linepos
)
1368 (org-table-goto-column colpos
)
1370 (when (or (not org-table-fix-formulas-confirm
)
1371 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1372 (org-table-fix-formulas "$" nil
(1- col
) 1)
1373 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1375 (defun org-table-find-dataline ()
1376 "Find a data line in the current table, which is needed for column commands."
1377 (if (and (org-at-table-p)
1378 (not (org-at-table-hline-p)))
1380 (let ((col (current-column))
1381 (end (org-table-end)))
1382 (org-move-to-column col
)
1383 (while (and (< (point) end
)
1384 (or (not (= (current-column) col
))
1385 (org-at-table-hline-p)))
1386 (beginning-of-line 2)
1387 (org-move-to-column col
))
1388 (if (and (org-at-table-p)
1389 (not (org-at-table-hline-p)))
1392 "Please position cursor in a data line for column operations")))))
1394 (defun org-table-line-to-dline (line &optional above
)
1395 "Turn a buffer line number into a data line number.
1396 If there is no data line in this line, return nil.
1397 If there is no matching dline (most likely te reference was a hline), the
1398 first dline below it is used. When ABOVE is non-nil, the one above is used."
1400 (let ((ll (length org-table-dlines
))
1406 (if (<= (aref org-table-dlines i
) line
)
1411 (if (>= (aref org-table-dlines i
) line
)
1417 (defun org-table-delete-column ()
1418 "Delete a column from the table."
1420 (if (not (org-at-table-p))
1421 (error "Not at a table"))
1422 (org-table-find-dataline)
1423 (org-table-check-inside-data-field)
1424 (let* ((col (org-table-current-column))
1425 (beg (org-table-begin))
1426 (end (org-table-end))
1427 ;; Current cursor position
1428 (linepos (org-current-line))
1431 (while (< (point) end
)
1432 (if (org-at-table-hline-p)
1434 (org-table-goto-column col t
)
1435 (and (looking-at "|[^|\n]+|")
1436 (replace-match "|")))
1437 (beginning-of-line 2))
1438 (move-marker end nil
)
1439 (org-goto-line linepos
)
1440 (org-table-goto-column colpos
)
1442 (when (or (not org-table-fix-formulas-confirm
)
1443 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1444 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1446 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1450 (defun org-table-move-column-right ()
1451 "Move column to the right."
1453 (org-table-move-column nil
))
1455 (defun org-table-move-column-left ()
1456 "Move column to the left."
1458 (org-table-move-column 'left
))
1461 (defun org-table-move-column (&optional left
)
1462 "Move the current column to the right. With arg LEFT, move to the left."
1464 (if (not (org-at-table-p))
1465 (error "Not at a table"))
1466 (org-table-find-dataline)
1467 (org-table-check-inside-data-field)
1468 (let* ((col (org-table-current-column))
1469 (col1 (if left
(1- col
) col
))
1470 (beg (org-table-begin))
1471 (end (org-table-end))
1472 ;; Current cursor position
1473 (linepos (org-current-line))
1474 (colpos (if left
(1- col
) (1+ col
))))
1475 (if (and left
(= col
1))
1476 (error "Cannot move column further left"))
1477 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1478 (error "Cannot move column further right"))
1480 (while (< (point) end
)
1481 (if (org-at-table-hline-p)
1483 (org-table-goto-column col1 t
)
1484 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1485 (replace-match "|\\2|\\1|")))
1486 (beginning-of-line 2))
1487 (move-marker end nil
)
1488 (org-goto-line linepos
)
1489 (org-table-goto-column colpos
)
1491 (when (or (not org-table-fix-formulas-confirm
)
1492 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1493 (org-table-fix-formulas
1494 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1495 (cons (number-to-string colpos
) (number-to-string col
))))
1496 (org-table-fix-formulas
1497 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1498 (cons (number-to-string colpos
) (number-to-string col
)))))))
1501 (defun org-table-move-row-down ()
1502 "Move table row down."
1504 (org-table-move-row nil
))
1506 (defun org-table-move-row-up ()
1507 "Move table row up."
1509 (org-table-move-row 'up
))
1512 (defun org-table-move-row (&optional up
)
1513 "Move the current table line down. With arg UP, move it up."
1515 (let* ((col (current-column))
1517 (hline1p (save-excursion (beginning-of-line 1)
1518 (looking-at org-table-hline-regexp
)))
1519 (dline1 (org-table-current-dline))
1520 (dline2 (+ dline1
(if up -
1 1)))
1523 (beginning-of-line tonew
)
1524 (unless (org-at-table-p)
1526 (error "Cannot move row further"))
1527 (setq hline2p
(looking-at org-table-hline-regexp
))
1529 (beginning-of-line 1)
1531 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1532 (delete-region (point) (1+ (point-at-eol)))
1533 (beginning-of-line tonew
)
1535 (beginning-of-line 0)
1536 (org-move-to-column col
)
1537 (unless (or hline1p hline2p
1538 (not (or (not org-table-fix-formulas-confirm
)
1539 (funcall org-table-fix-formulas-confirm
1540 "Fix formulas? "))))
1541 (org-table-fix-formulas
1542 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1543 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1546 (defun org-table-insert-row (&optional arg
)
1547 "Insert a new row above the current line into the table.
1548 With prefix ARG, insert below the current line."
1550 (if (not (org-at-table-p))
1551 (error "Not at a table"))
1552 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1553 (new (org-table-clean-line line
)))
1554 ;; Fix the first field if necessary
1555 (if (string-match "^[ \t]*| *[#$] *|" line
)
1556 (setq new
(replace-match (match-string 0 line
) t t new
)))
1557 (beginning-of-line (if arg
2 1))
1558 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1559 (beginning-of-line 0)
1560 (re-search-forward "| ?" (point-at-eol) t
)
1561 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1563 (when (or (not org-table-fix-formulas-confirm
)
1564 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1565 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1568 (defun org-table-insert-hline (&optional above
)
1569 "Insert a horizontal-line below the current line into the table.
1570 With prefix ABOVE, insert above the current line."
1572 (if (not (org-at-table-p))
1573 (error "Not at a table"))
1574 (when (eobp) (insert "\n") (backward-char 1))
1575 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1577 (let ((line (org-table-clean-line
1578 (buffer-substring (point-at-bol) (point-at-eol))))
1579 (col (current-column)))
1580 (while (string-match "|\\( +\\)|" line
)
1581 (setq line
(replace-match
1582 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1583 ?-
) "|") t t line
)))
1584 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1585 (beginning-of-line (if above
1 2))
1587 (beginning-of-line (if above
1 -
1))
1588 (org-move-to-column col
)
1589 (and org-table-overlay-coordinates
(org-table-align))))
1592 (defun org-table-hline-and-move (&optional same-column
)
1593 "Insert a hline and move to the row below that line."
1595 (let ((col (org-table-current-column)))
1596 (org-table-maybe-eval-formula)
1597 (org-table-maybe-recalculate-line)
1598 (org-table-insert-hline)
1600 (if (looking-at "\n[ \t]*|-")
1601 (progn (insert "\n|") (org-table-align))
1602 (org-table-next-field))
1603 (if same-column
(org-table-goto-column col
))))
1605 (defun org-table-clean-line (s)
1606 "Convert a table line S into a string with only \"|\" and space.
1607 In particular, this does handle wide and invisible characters."
1608 (if (string-match "^[ \t]*|-" s
)
1609 ;; It's a hline, just map the characters
1610 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1611 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1612 (setq s
(replace-match
1613 (concat "|" (make-string (org-string-width (match-string 1 s
))
1619 (defun org-table-kill-row ()
1620 "Delete the current row or horizontal line from the table."
1622 (if (not (org-at-table-p))
1623 (error "Not at a table"))
1624 (let ((col (current-column))
1625 (dline (org-table-current-dline)))
1626 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1627 (if (not (org-at-table-p)) (beginning-of-line 0))
1628 (org-move-to-column col
)
1629 (when (or (not org-table-fix-formulas-confirm
)
1630 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1631 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1635 (defun org-table-sort-lines (with-case &optional sorting-type
)
1636 "Sort table lines according to the column at point.
1638 The position of point indicates the column to be used for
1639 sorting, and the range of lines is the range between the nearest
1640 horizontal separator lines, or the entire table of no such lines
1641 exist. If point is before the first column, you will be prompted
1642 for the sorting column. If there is an active region, the mark
1643 specifies the first line and the sorting column, while point
1644 should be in the last line to be included into the sorting.
1646 The command then prompts for the sorting type which can be
1647 alphabetically, numerically, or by time (as given in a time stamp
1648 in the field). Sorting in reverse order is also possible.
1650 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1652 If SORTING-TYPE is specified when this function is called from a Lisp
1653 program, no prompting will take place. SORTING-TYPE must be a character,
1654 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1655 should be done in reverse order."
1657 (let* ((thisline (org-current-line))
1658 (thiscol (org-table-current-column))
1659 (otc org-table-overlay-coordinates
)
1660 beg end bcol ecol tend tbeg column lns pos
)
1661 (when (equal thiscol
0)
1662 (if (org-called-interactively-p 'any
)
1665 (read-string "Use column N for sorting: ")))
1667 (org-table-goto-column thiscol
))
1668 (org-table-check-inside-data-field)
1669 (if (org-region-active-p)
1671 (setq beg
(region-beginning) end
(region-end))
1673 (setq column
(org-table-current-column)
1676 (setq end
(point-at-bol 2)))
1677 (setq column
(org-table-current-column)
1679 tbeg
(org-table-begin)
1680 tend
(org-table-end))
1681 (if (re-search-backward org-table-hline-regexp tbeg t
)
1682 (setq beg
(point-at-bol 2))
1684 (setq beg
(point-at-bol 1)))
1686 (if (re-search-forward org-table-hline-regexp tend t
)
1687 (setq end
(point-at-bol 1))
1689 (setq end
(point-at-bol))))
1690 (setq beg
(move-marker (make-marker) beg
)
1691 end
(move-marker (make-marker) end
))
1694 (org-table-goto-column column
)
1695 (skip-chars-backward "^|")
1696 (setq bcol
(current-column))
1697 (org-table-goto-column (1+ column
))
1698 (skip-chars-backward "^|")
1699 (setq ecol
(1- (current-column)))
1700 (org-table-goto-column column
)
1701 (setq lns
(mapcar (lambda(x) (cons
1702 (org-sort-remove-invisible
1704 (org-split-string x
"[ \t]*|[ \t]*")))
1706 (org-split-string (buffer-substring beg end
) "\n")))
1707 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1708 (when org-table-overlay-coordinates
1709 (org-table-toggle-coordinate-overlays))
1710 (delete-region beg end
)
1711 (move-marker beg nil
)
1712 (move-marker end nil
)
1713 (insert (mapconcat 'cdr lns
"\n") "\n")
1714 (org-goto-line thisline
)
1715 (org-table-goto-column thiscol
)
1716 (when otc
(org-table-toggle-coordinate-overlays))
1717 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1720 (defun org-table-cut-region (beg end
)
1721 "Copy region in table to the clipboard and blank all relevant fields.
1722 If there is no active region, use just the field at point."
1724 (if (org-region-active-p) (region-beginning) (point))
1725 (if (org-region-active-p) (region-end) (point))))
1726 (org-table-copy-region beg end
'cut
))
1729 (defun org-table-copy-region (beg end
&optional cut
)
1730 "Copy rectangular region in table to clipboard.
1731 A special clipboard is used which can only be accessed
1732 with `org-table-paste-rectangle'."
1734 (if (org-region-active-p) (region-beginning) (point))
1735 (if (org-region-active-p) (region-end) (point))
1736 current-prefix-arg
))
1737 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1739 (rpl (if cut
" " nil
)))
1741 (org-table-check-inside-data-field)
1742 (setq l01
(org-current-line)
1743 c01
(org-table-current-column))
1745 (org-table-check-inside-data-field)
1746 (setq l02
(org-current-line)
1747 c02
(org-table-current-column))
1748 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1749 c1
(min c01 c02
) c2
(max c01 c02
))
1753 (if (> l1 l2
) (throw 'exit t
))
1755 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1756 (setq cols nil ic1 c1 ic2 c2
)
1757 (while (< ic1
(1+ ic2
))
1758 (push (org-table-get-field ic1 rpl
) cols
)
1759 (setq ic1
(1+ ic1
)))
1760 (push (nreverse cols
) region
)
1761 (setq l1
(1+ l1
)))))
1762 (setq org-table-clip
(nreverse region
))
1763 (if cut
(org-table-align))
1767 (defun org-table-paste-rectangle ()
1768 "Paste a rectangular region into a table.
1769 The upper right corner ends up in the current field. All involved fields
1770 will be overwritten. If the rectangle does not fit into the present table,
1771 the table is enlarged as needed. The process ignores horizontal separator
1774 (unless (and org-table-clip
(listp org-table-clip
))
1775 (error "First cut/copy a region to paste!"))
1776 (org-table-check-inside-data-field)
1777 (let* ((clip org-table-clip
)
1778 (line (org-current-line))
1779 (col (org-table-current-column))
1780 (org-enable-table-editor t
)
1781 (org-table-automatic-realign nil
)
1783 (while (setq cols
(pop clip
))
1784 (while (org-at-table-hline-p) (beginning-of-line 2))
1785 (if (not (org-at-table-p))
1786 (progn (end-of-line 0) (org-table-next-field)))
1788 (while (setq field
(pop cols
))
1789 (org-table-goto-column c nil
'force
)
1790 (org-table-get-field nil field
)
1792 (beginning-of-line 2))
1793 (org-goto-line line
)
1794 (org-table-goto-column col
)
1798 (defun org-table-convert ()
1799 "Convert from `org-mode' table to table.el and back.
1800 Obviously, this only works within limits. When an Org-mode table is
1801 converted to table.el, all horizontal separator lines get lost, because
1802 table.el uses these as cell boundaries and has no notion of horizontal lines.
1803 A table.el table can be converted to an Org-mode table only if it does not
1804 do row or column spanning. Multiline cells will become multiple cells.
1805 Beware, Org-mode does not test if the table can be successfully converted - it
1806 blindly applies a recipe that works for simple tables."
1809 (if (org-at-table.el-p
)
1810 ;; convert to Org-mode table
1811 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1812 (end (move-marker (make-marker) (org-table-end t
))))
1813 (table-unrecognize-region beg end
)
1815 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1818 (if (org-at-table-p)
1819 ;; convert to table.el table
1820 (let ((beg (move-marker (make-marker) (org-table-begin)))
1821 (end (move-marker (make-marker) (org-table-end))))
1822 ;; first, get rid of all horizontal lines
1824 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1826 ;; insert a hline before first
1828 (org-table-insert-hline 'above
)
1829 (beginning-of-line -
1)
1830 ;; insert a hline after each line
1831 (while (progn (beginning-of-line 3) (< (point) end
))
1832 (org-table-insert-hline))
1834 (setq end
(move-marker end
(org-table-end)))
1835 ;; replace "+" at beginning and ending of hlines
1836 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1837 (replace-match "\\1+-"))
1839 (while (re-search-forward "-|[ \t]*$" end t
)
1840 (replace-match "-+"))
1843 (defun org-table-transpose-table-at-point ()
1844 "Transpose orgmode table at point and eliminate hlines.
1852 will be transposed as
1859 Note that horizontal lines disappeared."
1862 (apply #'mapcar
* #'list
1863 ;; remove 'hline from list
1864 (delq nil
(mapcar (lambda (x) (when (listp x
) x
))
1865 (org-table-to-lisp))))))
1866 (delete-region (org-table-begin) (org-table-end))
1867 (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1872 (defun org-table-wrap-region (arg)
1873 "Wrap several fields in a column like a paragraph.
1874 This is useful if you'd like to spread the contents of a field over several
1875 lines, in order to keep the table compact.
1877 If there is an active region, and both point and mark are in the same column,
1878 the text in the column is wrapped to minimum width for the given number of
1879 lines. Generally, this makes the table more compact. A prefix ARG may be
1880 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1881 formats the selected text to two lines. If the region was longer than two
1882 lines, the remaining lines remain empty. A negative prefix argument reduces
1883 the current number of lines by that amount. The wrapped text is pasted back
1884 into the table. If you formatted it to more lines than it was before, fields
1885 further down in the table get overwritten - so you might need to make space in
1888 If there is no region, the current field is split at the cursor position and
1889 the text fragment to the right of the cursor is prepended to the field one
1892 If there is no region, but you specify a prefix ARG, the current field gets
1893 blank, and the content is appended to the field above."
1895 (org-table-check-inside-data-field)
1896 (if (org-region-active-p)
1897 ;; There is a region: fill as a paragraph
1898 (let* ((beg (region-beginning))
1899 (cline (save-excursion (goto-char beg
) (org-current-line)))
1900 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1902 (org-table-cut-region (region-beginning) (region-end))
1903 (if (> (length (car org-table-clip
)) 1)
1904 (error "Region must be limited to single column"))
1905 (setq nlines
(if arg
1907 (+ (length org-table-clip
) arg
)
1909 (length org-table-clip
)))
1910 (setq org-table-clip
1911 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1913 (org-goto-line cline
)
1914 (org-table-goto-column ccol
)
1915 (org-table-paste-rectangle))
1916 ;; No region, split the current field at point
1917 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1918 (skip-chars-forward "^\r\n|"))
1920 ;; combine with field above
1921 (let ((s (org-table-blank-field))
1922 (col (org-table-current-column)))
1923 (beginning-of-line 0)
1924 (while (org-at-table-hline-p) (beginning-of-line 0))
1925 (org-table-goto-column col
)
1926 (skip-chars-forward "^|")
1927 (skip-chars-backward " ")
1928 (insert " " (org-trim s
))
1931 (if (looking-at "\\([^|]+\\)+|")
1932 (let ((s (match-string 1)))
1933 (replace-match " |")
1934 (goto-char (match-beginning 0))
1935 (org-table-next-row)
1936 (insert (org-trim s
) " ")
1938 (org-table-next-row)))))
1940 (defvar org-field-marker nil
)
1943 (defun org-table-edit-field (arg)
1944 "Edit table field in a different window.
1945 This is mainly useful for fields that contain hidden parts.
1946 When called with a \\[universal-argument] prefix, just make the full field visible so that
1947 it can be edited in place."
1951 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
1953 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1954 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1955 (remove-text-properties b e
'(org-cwidth t invisible t
1956 display t intangible t
))
1957 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1958 (font-lock-fontify-block))))
1960 (let ((pos (point-marker))
1962 (if (eq org-table-use-standard-references t
)
1963 (concat (org-number-to-letters (org-table-current-column))
1964 (int-to-string (org-table-current-dline)))
1965 (concat "@" (int-to-string (org-table-current-dline))
1966 "$" (int-to-string (org-table-current-column)))))
1967 (field (org-table-get-field))
1968 (cw (current-window-configuration))
1971 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
1972 (when (and (local-variable-p 'org-field-marker
)
1973 (markerp org-field-marker
))
1974 (move-marker org-field-marker nil
))
1976 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
1977 (let ((org-inhibit-startup t
)) (org-mode))
1979 (setq truncate-lines nil
)
1981 (goto-char (setq p
(point-max)))
1982 (insert (org-trim field
))
1983 (remove-text-properties p
(point-max)
1984 '(invisible t org-cwidth t display t
1987 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1988 (org-set-local 'org-window-configuration cw
)
1989 (org-set-local 'org-field-marker pos
)
1990 (message "Edit and finish with C-c C-c")))))
1992 (defun org-table-finish-edit-field ()
1993 "Finish editing a table data field.
1994 Remove all newline characters, insert the result into the table, realign
1995 the table and kill the editing buffer."
1996 (let ((pos org-field-marker
)
1997 (cw org-window-configuration
)
1998 (cb (current-buffer))
2000 (goto-char (point-min))
2001 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
2002 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
2003 (replace-match " "))
2004 (setq text
(org-trim (buffer-string)))
2005 (set-window-configuration cw
)
2007 (select-window (get-buffer-window (marker-buffer pos
)))
2009 (move-marker pos nil
)
2010 (org-table-check-inside-data-field)
2011 (org-table-get-field nil text
)
2013 (message "New field value inserted")))
2015 (define-minor-mode org-table-follow-field-mode
2016 "Minor mode to make the table field editor window follow the cursor.
2017 When this mode is active, the field editor window will always show the
2018 current field. The mode exits automatically when the cursor leaves the
2019 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2020 nil
" TblFollow" nil
2021 (if org-table-follow-field-mode
2022 (org-add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2024 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2025 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2026 (win (and buf
(get-buffer-window buf
))))
2027 (when win
(delete-window win
))
2029 (with-current-buffer buf
2030 (move-marker org-field-marker nil
))
2031 (kill-buffer buf
)))))
2033 (defun org-table-follow-fields-with-editor ()
2034 (if (and org-table-exit-follow-field-mode-when-leaving-table
2035 (not (org-at-table-p)))
2036 ;; We have left the table, exit the follow mode
2037 (org-table-follow-field-mode -
1)
2038 (when (org-table-check-inside-data-field 'noerror
)
2039 (let ((win (selected-window)))
2040 (org-table-edit-field nil
)
2041 (org-fit-window-to-buffer)
2042 (select-window win
)))))
2044 (defvar org-timecnt
) ; dynamically scoped parameter
2047 (defun org-table-sum (&optional beg end nlast
)
2048 "Sum numbers in region of current table column.
2049 The result will be displayed in the echo area, and will be available
2050 as kill to be inserted with \\[yank].
2052 If there is an active region, it is interpreted as a rectangle and all
2053 numbers in that rectangle will be summed. If there is no active
2054 region and point is located in a table column, sum all numbers in that
2057 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2058 numbers are assumed to be times as well (in decimal hours) and the
2059 numbers are added as such.
2061 If NLAST is a number, only the NLAST fields will actually be summed."
2064 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2066 ((and beg end
)) ; beg and end given explicitly
2067 ((org-region-active-p)
2068 (setq beg
(region-beginning) end
(region-end)))
2070 (setq col
(org-table-current-column))
2071 (goto-char (org-table-begin))
2072 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2073 (error "No table data"))
2074 (org-table-goto-column col
)
2076 (goto-char (org-table-end))
2077 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2078 (error "No table data"))
2079 (org-table-goto-column col
)
2080 (setq end
(point))))
2081 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2082 (items1 (cond ((not nlast
) items
)
2083 ((>= nlast
(length items
)) items
)
2084 (t (setq items
(reverse items
))
2085 (setcdr (nthcdr (1- nlast
) items
) nil
)
2087 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2089 (res (apply '+ numbers
))
2090 (sres (if (= org-timecnt
0)
2091 (number-to-string res
)
2092 (setq diff
(* 3600 res
)
2093 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2094 m
(floor (/ diff
60)) diff
(mod diff
60)
2096 (format "%d:%02d:%02d" h m s
))))
2098 (if (org-called-interactively-p 'interactive
)
2100 (substitute-command-keys
2101 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2102 (length numbers
) sres
))))
2105 (defun org-table-get-number-for-summing (s)
2107 (if (string-match "^ *|? *" s
)
2108 (setq s
(replace-match "" nil nil s
)))
2109 (if (string-match " *|? *$" s
)
2110 (setq s
(replace-match "" nil nil s
)))
2111 (setq n
(string-to-number s
))
2113 ((and (string-match "0" s
)
2114 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2115 ((string-match "\\`[ \t]+\\'" s
) nil
)
2116 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2117 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2118 (m (string-to-number (or (match-string 2 s
) "0")))
2119 (s (string-to-number (or (match-string 4 s
) "0"))))
2120 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2121 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2125 (defun org-table-current-field-formula (&optional key noerror
)
2126 "Return the formula active for the current field.
2127 Assumes that specials are in place.
2128 If KEY is given, return the key to this formula.
2129 Otherwise return the formula preceded with \"=\" or \":=\"."
2130 (let* ((name (car (rassoc (list (org-current-line)
2131 (org-table-current-column))
2132 org-table-named-field-locations
)))
2133 (col (org-table-current-column))
2134 (scol (int-to-string col
))
2135 (ref (format "@%d$%d" (org-table-current-dline) col
))
2136 (stored-list (org-table-get-stored-formulas noerror
))
2137 (ass (or (assoc name stored-list
)
2138 (assoc ref stored-list
)
2139 (assoc scol stored-list
))))
2142 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
2145 (defun org-table-get-formula (&optional equation named
)
2146 "Read a formula from the minibuffer, offer stored formula as default.
2147 When NAMED is non-nil, look for a named equation."
2148 (let* ((stored-list (org-table-get-stored-formulas))
2149 (name (car (rassoc (list (org-current-line)
2150 (org-table-current-column))
2151 org-table-named-field-locations
)))
2152 (ref (format "@%d$%d" (org-table-current-dline)
2153 (org-table-current-column)))
2154 (refass (assoc ref stored-list
))
2155 (nameass (assoc name stored-list
))
2157 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
2160 (int-to-string (org-table-current-column))))
2161 (dummy (and (or nameass refass
) (not named
)
2162 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2164 (name (or name ref
))
2165 (org-table-may-need-update nil
)
2166 (stored (cdr (assoc scol stored-list
)))
2168 ((and stored equation
(string-match "^ *=? *$" equation
))
2172 (t (org-table-formula-from-user
2174 (org-table-formula-to-user
2175 (format "%s formula %s%s="
2176 (if named
"Field" "Column")
2177 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
2179 (if stored
(org-table-formula-to-user stored
) "")
2180 'org-table-formula-history
2183 (when (not (string-match "\\S-" eq
))
2185 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2186 (org-table-store-formulas stored-list
)
2187 (error "Formula removed"))
2188 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2189 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2190 (if (and name
(not named
))
2191 ;; We set the column equation, delete the named one.
2192 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2195 (setcdr (assoc scol stored-list
) eq
)
2196 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2197 (if (or mustsave
(not (equal stored eq
)))
2198 (org-table-store-formulas stored-list
))
2201 (defun org-table-store-formulas (alist)
2202 "Store the list of formulas below the current table."
2203 (setq alist
(sort alist
'org-table-formula-less-p
))
2204 (let ((case-fold-search t
))
2206 (goto-char (org-table-end))
2207 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2209 ;; don't overwrite TBLFM, we might use text properties to store stuff
2210 (goto-char (match-beginning 3))
2211 (delete-region (match-beginning 3) (match-end 0)))
2213 (insert (or (match-string 2) "#+TBLFM:")))
2215 (mapconcat (lambda (x)
2217 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2218 (car x
) "=" (cdr x
)))
2222 (defsubst org-table-formula-make-cmp-string
(a)
2223 (when (string-match "\\`$[<>]" a
)
2224 (let ((arrow (string-to-char (substring a
1))))
2225 ;; Fake a high number to make sure this is sorted at the end.
2226 (setq a
(org-table-formula-handle-first/last-rc a
))
2227 (setq a
(format "$%d" (+ 10000
2228 (if (= arrow ?
<) -
1000 0)
2229 (string-to-number (substring a
1)))))))
2231 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2235 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2237 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2239 (concat "@@" (match-string 5 a
))))))
2241 (defun org-table-formula-less-p (a b
)
2242 "Compare two formulas for sorting."
2243 (let ((as (org-table-formula-make-cmp-string (car a
)))
2244 (bs (org-table-formula-make-cmp-string (car b
))))
2245 (and as bs
(string< as bs
))))
2248 (defun org-table-get-stored-formulas (&optional noerror
)
2249 "Return an alist with the stored formulas directly after current table."
2250 (interactive) ;; FIXME interactive?
2251 (let ((case-fold-search t
) scol eq eq-alist strings string seen
)
2253 (goto-char (org-table-end))
2254 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2255 (setq strings
(org-split-string (org-match-string-no-properties 2)
2257 (while (setq string
(pop strings
))
2258 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2259 (setq scol
(if (match-end 2)
2260 (match-string 2 string
)
2261 (match-string 1 string
))
2262 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2263 (concat "$" scol
) scol
)
2264 eq
(match-string 3 string
)
2265 eq-alist
(cons (cons scol eq
) eq-alist
))
2266 (if (member scol seen
)
2269 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2272 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2273 (push scol seen
))))))
2274 (nreverse eq-alist
)))
2276 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2277 "Modify the equations after the table structure has been edited.
2278 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2279 For all numbers larger than LIMIT, shift them by DELTA."
2281 (goto-char (org-table-end))
2282 (when (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2283 (let ((msg "The formulas in #+TBLFM have been updated")
2284 (re (concat key
"\\([0-9]+\\)"))
2287 (if (or (equal key
"$") (equal key
"$LR"))
2288 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2289 (regexp-quote key
) remove
)
2290 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2293 (while (re-search-forward re2
(point-at-eol) t
)
2294 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2295 (if (equal (char-before (match-beginning 0)) ?.
)
2296 (error "Change makes TBLFM term %s invalid, use undo to recover"
2298 (replace-match "")))))
2299 (while (re-search-forward re
(point-at-eol) t
)
2300 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2301 (setq s
(match-string 1) n
(string-to-number s
))
2303 ((setq a
(assoc s replace
))
2304 (replace-match (concat key
(cdr a
)) t t
)
2306 ((and limit
(> n limit
))
2307 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2308 (message msg
)))))))))
2310 (defun org-table-get-specials ()
2311 "Get the column names and local parameters for this table."
2313 (let ((beg (org-table-begin)) (end (org-table-end))
2314 names name fields fields1 field cnt
2315 c v l line col types dlines hlines last-dline
)
2316 (setq org-table-column-names nil
2317 org-table-local-parameters nil
2318 org-table-named-field-locations nil
2319 org-table-current-begin-line nil
2320 org-table-current-begin-pos nil
2321 org-table-current-line-types nil
2322 org-table-current-ncol
0)
2324 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2325 (setq names
(org-split-string (match-string 1) " *| *")
2327 (while (setq name
(pop names
))
2329 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name
)
2330 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2331 (setq org-table-column-names
(nreverse org-table-column-names
))
2332 (setq org-table-column-name-regexp
2333 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2335 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2336 (setq fields
(org-split-string (match-string 1) " *| *"))
2337 (while (setq field
(pop fields
))
2338 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2339 (push (cons (match-string 1 field
) (match-string 2 field
))
2340 org-table-local-parameters
))))
2342 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2343 (setq c
(match-string 1)
2344 fields
(org-split-string (match-string 2) " *| *"))
2346 (beginning-of-line (if (equal c
"_") 2 0))
2347 (setq line
(org-current-line) col
1)
2348 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2349 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2350 (while (and fields1
(setq field
(pop fields
)))
2351 (setq v
(pop fields1
) col
(1+ col
))
2352 (when (and (stringp field
) (stringp v
)
2353 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field
))
2354 (push (cons field v
) org-table-local-parameters
)
2355 (push (list field line col
) org-table-named-field-locations
))))
2356 ;; Analyse the line types
2358 (setq org-table-current-begin-line
(org-current-line)
2359 org-table-current-begin-pos
(point)
2360 l org-table-current-begin-line
)
2361 (while (looking-at "[ \t]*|\\(-\\)?")
2362 (push (if (match-end 1) 'hline
'dline
) types
)
2363 (if (match-end 1) (push l hlines
) (push l dlines
))
2364 (beginning-of-line 2)
2366 (push 'hline types
) ;; add an imaginary extra hline to the end
2367 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2368 last-dline
(car dlines
)
2369 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2370 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2371 (org-goto-line last-dline
)
2372 (let* ((l last-dline
)
2373 (fields (org-split-string
2374 (buffer-substring (point-at-bol) (point-at-eol))
2376 (nfields (length fields
))
2378 (setq org-table-current-ncol nfields
)
2379 (loop for i from
1 to nfields do
2380 (push (list (format "LR%d" i
) l i
) al
)
2381 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2382 (setq org-table-named-field-locations
2383 (append org-table-named-field-locations al
))
2384 (setq org-table-local-parameters
2385 (append org-table-local-parameters al2
))))))
2388 (defun org-table-maybe-eval-formula ()
2389 "Check if the current field starts with \"=\" or \":=\".
2390 If yes, store the formula and apply it."
2391 ;; We already know we are in a table. Get field will only return a formula
2392 ;; when appropriate. It might return a separator line, but no problem.
2393 (when org-table-formula-evaluate-inline
2394 (let* ((field (org-trim (or (org-table-get-field) "")))
2396 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2397 (setq named
(equal (string-to-char field
) ?
:)
2398 eq
(match-string 1 field
))
2399 (if (or (fboundp 'calc-eval
)
2400 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2401 (org-table-eval-formula (if named
'(4) nil
)
2402 (org-table-formula-from-user eq
))
2403 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2405 (defvar org-recalc-commands nil
2406 "List of commands triggering the recalculation of a line.
2407 Will be filled automatically during use.")
2409 (defvar org-recalc-marks
2410 '((" " .
"Unmarked: no special line, no automatic recalculation")
2411 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2412 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2413 ("!" .
"Column name definition line. Reference in formula as $name.")
2414 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2415 ("_" .
"Names for values in row below this one.")
2416 ("^" .
"Names for values in row above this one.")))
2419 (defun org-table-rotate-recalc-marks (&optional newchar
)
2420 "Rotate the recalculation mark in the first column.
2421 If in any row, the first field is not consistent with a mark,
2422 insert a new column for the markers.
2423 When there is an active region, change all the lines in the region,
2424 after prompting for the marking character.
2425 After each change, a message will be displayed indicating the meaning
2428 (unless (org-at-table-p) (error "Not at a table"))
2429 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2430 (beg (org-table-begin))
2431 (end (org-table-end))
2432 (l (org-current-line))
2433 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2434 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2438 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2439 (col (org-table-current-column))
2440 (forcenew (car (assoc newchar org-recalc-marks
)))
2443 (message "Change region to what mark? Type # * ! $ or SPC: ")
2444 (setq newchar
(char-to-string (read-char-exclusive))
2445 forcenew
(car (assoc newchar org-recalc-marks
))))
2446 (if (and newchar
(not forcenew
))
2447 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2449 (if l1
(org-goto-line l1
))
2451 (beginning-of-line 1)
2452 (unless (looking-at org-table-dataline-regexp
)
2453 (error "Not at a table data line")))
2455 (org-table-goto-column 1)
2456 (org-table-insert-column)
2457 (org-table-goto-column (1+ col
)))
2458 (setq epos
(point-at-eol))
2460 (beginning-of-line 1)
2461 (org-table-get-field
2462 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2464 (setq new
(or forcenew
2465 (cadr (member (match-string 1) marks
))))
2471 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2472 (and (looking-at org-table-dataline-regexp
)
2473 (org-table-get-field 1 (concat " " new
" "))))
2474 (org-goto-line l1
)))
2475 (if (not (= epos
(point-at-eol))) (org-table-align))
2477 (and (org-called-interactively-p 'interactive
)
2478 (message "%s" (cdr (assoc new org-recalc-marks
))))))
2481 (defun org-table-maybe-recalculate-line ()
2482 "Recompute the current line if marked for it, and if we haven't just done it."
2484 (and org-table-allow-automatic-line-recalculation
2485 (not (and (memq last-command org-recalc-commands
)
2486 (equal org-last-recalc-line
(org-current-line))))
2487 (save-excursion (beginning-of-line 1)
2488 (looking-at org-table-auto-recalculate-regexp
))
2489 (org-table-recalculate) t
))
2491 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2492 (defsubst org-set-calc-mode
(var &optional value
)
2494 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2495 ("R" calc-angle-mode rad
)
2496 ("F" calc-prefer-frac t
)
2497 ("S" calc-symbolic-mode t
)))
2498 value
(nth 2 var
) var
(nth 1 var
)))
2499 (if (memq var org-tbl-calc-modes
)
2500 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2501 (cons var
(cons value org-tbl-calc-modes
)))
2505 (defun org-table-eval-formula (&optional arg equation
2506 suppress-align suppress-const
2507 suppress-store suppress-analysis
)
2508 "Replace the table field value at the cursor by the result of a calculation.
2510 This function makes use of Dave Gillespie's Calc package, in my view the
2511 most exciting program ever written for GNU Emacs. So you need to have Calc
2512 installed in order to use this function.
2514 In a table, this command replaces the value in the current field with the
2515 result of a formula. It also installs the formula as the \"current\" column
2516 formula, by storing it in a special line below the table. When called
2517 with a `C-u' prefix, the current field must be a named field, and the
2518 formula is installed as valid in only this specific field.
2520 When called with two `C-u' prefixes, insert the active equation
2521 for the field back into the current field, so that it can be
2522 edited there. This is useful in order to use \\[org-table-show-reference]
2523 to check the referenced fields.
2525 When called, the command first prompts for a formula, which is read in
2526 the minibuffer. Previously entered formulas are available through the
2527 history list, and the last used formula is offered as a default.
2528 These stored formulas are adapted correctly when moving, inserting, or
2529 deleting columns with the corresponding commands.
2531 The formula can be any algebraic expression understood by the Calc package.
2532 For details, see the Org-mode manual.
2534 This function can also be called from Lisp programs and offers
2535 additional arguments: EQUATION can be the formula to apply. If this
2536 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2537 used to speed-up recursive calls by by-passing unnecessary aligns.
2538 SUPPRESS-CONST suppresses the interpretation of constants in the
2539 formula, assuming that this has been done already outside the function.
2540 SUPPRESS-STORE means the formula should not be stored, either because
2541 it is already stored, or because it is a modified equation that should
2542 not overwrite the stored one."
2544 (org-table-check-inside-data-field)
2545 (or suppress-analysis
(org-table-get-specials))
2546 (if (equal arg
'(16))
2547 (let ((eq (org-table-current-field-formula)))
2548 (or eq
(error "No equation active for current field"))
2549 (org-table-get-field nil eq
)
2551 (setq org-table-may-need-update t
))
2553 (ndown (if (integerp arg
) arg
1))
2554 (org-table-automatic-realign nil
)
2555 (case-fold-search nil
)
2557 (formula (if (and equation suppress-store
)
2559 (org-table-get-formula equation
(equal arg
'(4)))))
2560 (n0 (org-table-current-column))
2561 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2562 (numbers nil
) ; was a variable, now fixed default
2564 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2565 duration duration-output-format
)
2566 ;; Parse the format string. Since we have a lot of modes, this is
2567 ;; a lot of work. However, I think calc still uses most of the time.
2568 (if (string-match ";" formula
)
2569 (let ((tmp (org-split-string formula
";")))
2570 (setq formula
(car tmp
)
2571 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2573 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2574 (setq c
(string-to-char (match-string 1 fmt
))
2575 n
(string-to-number (match-string 2 fmt
)))
2577 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2578 (setq org-tbl-calc-modes
2581 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2582 (?s . sci
) (?e . eng
))))
2584 (setq fmt
(replace-match "" t t fmt
)))
2585 (if (string-match "T" fmt
)
2586 (setq duration t numbers t
2587 duration-output-format nil
2588 fmt
(replace-match "" t t fmt
)))
2589 (if (string-match "t" fmt
)
2591 duration-output-format org-table-duration-custom-format
2593 fmt
(replace-match "" t t fmt
)))
2594 (if (string-match "N" fmt
)
2596 fmt
(replace-match "" t t fmt
)))
2597 (if (string-match "L" fmt
)
2599 fmt
(replace-match "" t t fmt
)))
2600 (if (string-match "E" fmt
)
2602 fmt
(replace-match "" t t fmt
)))
2603 (while (string-match "[DRFS]" fmt
)
2604 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2605 (setq fmt
(replace-match "" t t fmt
)))
2606 (unless (string-match "\\S-" fmt
)
2608 (if (and (not suppress-const
) org-table-formula-use-constants
)
2609 (setq formula
(org-table-formula-substitute-names formula
)))
2610 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2612 (setq fields
(org-split-string
2613 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2615 ;; replace fields with duration values if relevant
2618 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2621 (setq fields
(mapcar
2623 (if (string-match "\\S-" x
)
2624 (number-to-string (string-to-number x
))
2627 (setq ndown
(1- ndown
))
2628 (setq form
(copy-sequence formula
)
2629 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2630 (if (and lispp literal
) (setq lispp
'literal
))
2632 ;; Insert row and column number of formula result field
2633 (while (string-match "[@$]#" form
)
2638 (if (equal (substring form
(match-beginning 0)
2639 (1+ (match-beginning 0)))
2641 (org-table-current-dline)
2642 (org-table-current-column))))
2645 ;; Check for old vertical references
2646 (setq form
(org-table-rewrite-old-row-references form
))
2647 ;; Insert remote references
2648 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2652 (org-table-make-reference
2653 (let ((rmtrng (org-table-get-remote-range
2654 (match-string 1 form
) (match-string 2 form
))))
2657 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2658 (org-table-time-string-to-seconds rmtrng
))
2660 keep-empty numbers lispp
))
2662 ;; Insert complex ranges
2663 (while (and (string-match org-table-range-regexp form
)
2664 (> (length (match-string 0 form
)) 1))
2665 (setq formrg
(save-match-data
2666 (org-table-get-range (match-string 0 form
) nil n0
)))
2669 (org-table-make-reference
2670 ;; possibly handle durations
2673 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2674 (org-table-time-string-to-seconds formrg
))
2676 keep-empty numbers lispp
)))
2677 (if (not (save-match-data
2678 (string-match (regexp-quote form
) formrpl
)))
2679 (setq form
(replace-match formrpl t t form
))
2680 (error "Spreadsheet error: invalid reference \"%s\"" form
)))
2681 ;; Insert simple ranges
2682 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2686 (org-table-make-reference
2688 fields
(string-to-number (match-string 1 form
))
2689 (string-to-number (match-string 2 form
)))
2690 keep-empty numbers lispp
))
2693 ;; Insert the references to fields in same row
2694 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2695 (setq n
(+ (string-to-number (match-string 1 form
))
2696 (if (match-end 2) n0
0))
2697 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
))
2698 (unless x
(error "Invalid field specifier \"%s\""
2699 (match-string 0 form
)))
2700 (setq form
(replace-match
2702 (org-table-make-reference
2703 x keep-empty numbers lispp
))
2707 (setq ev
(condition-case nil
2708 (eval (eval (read form
)))
2710 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2711 ev
(if duration
(org-table-time-seconds-to-string
2712 (string-to-number ev
)
2713 duration-output-format
) ev
))
2714 (or (fboundp 'calc-eval
)
2715 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2716 ;; Use <...> time-stamps so that Calc can handle them
2717 (setq form
(replace-regexp-in-string org-ts-regexp3
"<\\1>" form
))
2718 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2719 (when (string-match org-ts-regexp2 form
)
2720 (let* ((ts (match-string 0 form
))
2721 (tsp (apply 'encode-time
(save-match-data (org-parse-time-string ts
))))
2722 (system-time-locale "C")
2723 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2724 (cdr org-time-stamp-formats
))
2725 (car org-time-stamp-formats
))))
2726 (setq form
(replace-match (format-time-string tf tsp
) t t form
))))
2728 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2730 (calc-eval (cons form org-tbl-calc-modes
)
2731 (when (and (not keep-empty
) numbers
) 'num
)))
2732 ev
(if duration
(org-table-time-seconds-to-string
2733 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2734 (string-to-number (org-table-time-string-to-seconds ev
))
2735 (string-to-number ev
))
2736 duration-output-format
)
2739 (when org-table-formula-debug
2740 (with-output-to-temp-buffer "*Substitution History*"
2741 (princ (format "Substitution history of formula
2745 $1-> %s\n" orig formula form0 form
))
2747 (princ (format " %s^\nError: %s"
2748 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2749 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2751 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2752 (setq bw
(get-buffer-window "*Substitution History*"))
2753 (org-fit-window-to-buffer bw
)
2754 (unless (and (org-called-interactively-p 'any
) (not ndown
))
2755 (unless (let (inhibit-redisplay)
2756 (y-or-n-p "Debugging Formula. Continue to next? "))
2761 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2762 (org-table-justify-field-maybe
2763 (format org-table-formula-field-format
2764 (if fmt
(format fmt
(string-to-number ev
)) ev
)))
2765 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2766 (call-interactively 'org-return
)
2768 (and down
(org-table-maybe-recalculate-line))
2769 (or suppress-align
(and org-table-may-need-update
2770 (org-table-align))))))
2772 (defun org-table-put-field-property (prop value
)
2774 (put-text-property (progn (skip-chars-backward "^|") (point))
2775 (progn (skip-chars-forward "^|") (point))
2778 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2779 "Get a calc vector from a column, according to descriptor DESC.
2780 Optional arguments TBEG and COL can give the beginning of the table and
2781 the current column, to avoid unnecessary parsing.
2783 HIGHLIGHT means just highlight the range.
2785 When CORNERS-ONLY is set, only return the corners of the range as
2786 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2787 in the buffer and column1 and column2 are table column numbers."
2788 (if (not (equal (string-to-char desc
) ?
@))
2789 (setq desc
(concat "@" desc
)))
2791 (or tbeg
(setq tbeg
(org-table-begin)))
2792 (or col
(setq col
(org-table-current-column)))
2793 (let ((thisline (org-current-line))
2794 beg end c1 c2 r1 r2 rangep tmp
)
2795 (unless (string-match org-table-range-regexp desc
)
2796 (error "Invalid table range specifier `%s'" desc
))
2797 (setq rangep
(match-end 3)
2798 r1
(and (match-end 1) (match-string 1 desc
))
2799 r2
(and (match-end 4) (match-string 4 desc
))
2800 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2801 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2803 (and c1
(setq c1
(+ (string-to-number c1
)
2804 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2805 (and c2
(setq c2
(+ (string-to-number c2
)
2806 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2807 (if (equal r1
"") (setq r1 nil
))
2808 (if (equal r2
"") (setq r2 nil
))
2809 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2810 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2811 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2812 (if (not r1
) (setq r1 thisline
))
2813 (if (not r2
) (setq r2 thisline
))
2814 (if (or (not c1
) (= 0 c1
)) (setq c1 col
))
2815 (if (or (not c2
) (= 0 c2
)) (setq c2 col
))
2816 (if (and (not corners-only
)
2817 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2821 (while (not (looking-at org-table-dataline-regexp
))
2822 (beginning-of-line 2))
2823 (prog1 (org-trim (org-table-get-field c1
))
2824 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2825 ;; A range, return a vector
2826 ;; First sort the numbers to get a regular rectangle
2827 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2828 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2830 ;; Only return the corners of the range
2832 ;; Copy the range values into a list
2834 (while (not (looking-at org-table-dataline-regexp
))
2835 (beginning-of-line 2))
2836 (org-table-goto-column c1
)
2839 (while (not (looking-at org-table-dataline-regexp
))
2840 (beginning-of-line 0))
2841 (org-table-goto-column c2
)
2844 (org-table-highlight-rectangle
2845 beg
(progn (skip-chars-forward "^|\n") (point))))
2846 ;; return string representation of calc vector
2848 (apply 'append
(org-table-copy-region beg end
))))))))
2850 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2851 "Analyze descriptor DESC and retrieve the corresponding line number.
2852 The cursor is currently in line CLINE, the table begins in line BLINE,
2853 and TABLE is a vector with line types."
2854 (if (string-match "^[0-9]+$" desc
)
2855 (aref org-table-dlines
(string-to-number desc
))
2856 (setq cline
(or cline
(org-current-line))
2857 bline
(or bline org-table-current-begin-line
)
2858 table
(or table org-table-current-line-types
))
2860 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2862 (and (not (match-end 3)) (not (match-end 6)))
2863 (and (match-end 3) (match-end 6) (not (match-end 5))))
2864 (error "Invalid row descriptor `%s'" desc
))
2865 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2866 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2867 (odir (and (match-end 5) (match-string 5 desc
)))
2868 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2870 (rel (and (match-end 6)
2871 (or (and (match-end 1) (not (match-end 3)))
2873 (if (and hn
(not hdir
))
2876 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2877 (if (and (not hn
) on
(not odir
))
2878 (error "Should never happen");;(aref org-table-dlines on)
2879 (if (and hn
(> hn
0))
2880 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2881 nil hn cline desc
)))
2883 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2884 rel on cline desc
)))
2887 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2888 "FIXME: Needs more documentation."
2889 (let ((l (length table
)))
2891 (while (and (setq i
(+ i
(if backwards -
1 1)))
2893 (not (eq (aref table i
) type
))
2894 (if (and relative
(eq (aref table i
) 'hline
))
2896 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2897 ((eq org-table-relative-ref-may-cross-hline
'error
)
2898 (error "Row descriptor %s used in line %d crosses hline" desc cline
))
2899 (t (setq i
(- i
(if backwards -
1 1))
2904 (if (or (< i
0) (>= i l
))
2905 (error "Row descriptor %s used in line %d leads outside table"
2909 (defun org-table-rewrite-old-row-references (s)
2910 (if (string-match "&[-+0-9I]" s
)
2911 (error "Formula contains old &row reference, please rewrite using @-syntax")
2914 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2915 "Convert list ELEMENTS to something appropriate to insert into formula.
2916 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2917 NUMBERS indicates that everything should be converted to numbers.
2918 LISPP non-nil means to return something appropriate for a Lisp
2919 list, 'literal is for the format specifier L."
2920 ;; Calc nan (not a number) is used for the conversion of the empty
2921 ;; field to a reference for several reasons: (i) It is accepted in a
2922 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
2923 ;; (ii) In a single field (not in range) it can be distinguished
2924 ;; from "(nan)" which is the reference made from a single field
2925 ;; containing "nan".
2926 (if (stringp elements
)
2929 (if (eq lispp
'literal
)
2931 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2932 (if (string-match "\\S-" elements
)
2934 (when numbers
(setq elements
(number-to-string
2935 (string-to-number elements
))))
2936 (concat "(" elements
")"))
2937 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
2942 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2944 (setq elements
(or elements
'("")))
2948 (if (eq lispp
'literal
)
2950 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2952 (concat "[" (mapconcat
2954 (if (string-match "\\S-" x
)
2956 (number-to-string (string-to-number x
))
2958 (if (or (not keep-empty
) numbers
) "0" "nan")))
2963 (defun org-table-recalculate (&optional all noalign
)
2964 "Recalculate the current table line by applying all stored formulas.
2965 With prefix arg ALL, do this for all lines in the table.
2966 With the prefix argument ALL is `(16)' \
2967 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2968 it is the symbol `iterate', recompute the table until it no longer changes.
2969 If NOALIGN is not nil, do not re-align the table after the computations
2970 are done. This is typically used internally to save time, if it is
2971 known that the table will be realigned a little later anyway."
2973 (or (memq this-command org-recalc-commands
)
2974 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2975 (unless (org-at-table-p) (error "Not at a table"))
2976 (if (or (eq all
'iterate
) (equal all
'(16)))
2978 (org-table-get-specials)
2979 (let* ((eqlist (sort (org-table-get-stored-formulas)
2980 (lambda (a b
) (string< (car a
) (car b
)))))
2981 (eqlist1 (copy-sequence eqlist
))
2982 (inhibit-redisplay (not debug-on-error
))
2983 (line-re org-table-dataline-regexp
)
2984 (thisline (org-current-line))
2985 (thiscol (org-table-current-column))
2987 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
2988 ;; Insert constants in all formulas
2991 (when (string-match "\\`$[<>]" (car x
))
2993 (setq x
(cons (substring
2994 (org-table-formula-handle-first/last-rc
2997 (if (assoc (car x
) eqlist1
)
2998 (error "\"%s=\" formula tries to overwrite existing formula for column %s"
3001 (org-table-formula-handle-first/last-rc
(car x
))
3002 (org-table-formula-substitute-names
3003 (org-table-formula-handle-first/last-rc
(cdr x
)))))
3005 ;; Split the equation list
3006 (while (setq eq
(pop eqlist
))
3007 (if (<= (string-to-char (car eq
)) ?
9)
3010 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
3011 ;; Expand ranges in lhs of formulas
3012 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
3014 ;; Get the correct line range to process
3017 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
3018 (goto-char (setq beg
(org-table-begin)))
3019 (if (re-search-forward org-table-calculate-mark-regexp end t
)
3020 ;; This is a table with marked lines, compute selected lines
3021 (setq line-re org-table-recalculate-regexp
)
3022 ;; Move forward to the first non-header line
3023 (if (and (re-search-forward org-table-dataline-regexp end t
)
3024 (re-search-forward org-table-hline-regexp end t
)
3025 (re-search-forward org-table-dataline-regexp end t
))
3026 (setq beg
(match-beginning 0))
3027 nil
))) ;; just leave beg where it is
3028 (setq beg
(point-at-bol)
3029 end
(move-marker (make-marker) (1+ (point-at-eol)))))
3031 (and all
(message "Re-applying formulas to full table..."))
3033 ;; First find the named fields, and mark them untouchable.
3034 ;; Also check if several field/range formulas try to set the same field.
3035 (remove-text-properties beg end
'(org-untouchable t
))
3036 (while (setq eq
(pop eqlname
))
3038 a
(assoc name org-table-named-field-locations
))
3040 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
3042 (when (member name1 seen-fields
)
3043 (error "Several field/range formulas try to set %s" name1
))
3044 (push name1 seen-fields
)
3047 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
3050 (aref org-table-dlines
3051 (string-to-number (match-string 1 name
)))
3052 (error (error "Invalid row number in %s"
3054 (string-to-number (match-string 2 name
)))))
3055 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
3056 (message "Re-applying formula to field: %s" name
)
3057 (org-goto-line (nth 1 a
))
3058 (org-table-goto-column (nth 2 a
))
3059 (push (append a
(list (cdr eq
))) eqlname1
)
3060 (org-table-put-field-property :org-untouchable t
)))
3061 (setq eqlname1
(nreverse eqlname1
))
3063 ;; Now evaluate the column formulas, but skip fields covered by
3066 (while (re-search-forward line-re end t
)
3067 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
3068 ;; Unprotected line, recalculate
3069 (and all
(message "Re-applying formulas to full table...(line %d)"
3070 (setq cnt
(1+ cnt
))))
3071 (setq org-last-recalc-line
(org-current-line))
3073 (while (setq entry
(pop eql
))
3074 (org-goto-line org-last-recalc-line
)
3075 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
3076 (unless (get-text-property (point) :org-untouchable
)
3077 (org-table-eval-formula nil
(cdr entry
)
3078 'noalign
'nocst
'nostore
'noanalysis
)))))
3080 ;; Now evaluate the field formulas
3081 (while (setq eq
(pop eqlname1
))
3082 (message "Re-applying formula to field: %s" (car eq
))
3083 (org-goto-line (nth 1 eq
))
3084 (org-table-goto-column (nth 2 eq
))
3085 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
3086 'nostore
'noanalysis
))
3088 (org-goto-line thisline
)
3089 (org-table-goto-column thiscol
)
3090 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3091 (or noalign
(and org-table-may-need-update
(org-table-align))
3092 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
3094 ;; back to initial position
3095 (message "Re-applying formulas...done")
3096 (org-goto-line thisline
)
3097 (org-table-goto-column thiscol
)
3098 (or noalign
(and org-table-may-need-update
(org-table-align))
3099 (and all
(message "Re-applying formulas...done"))))))
3102 (defun org-table-iterate (&optional arg
)
3103 "Recalculate the table until it does not change anymore.
3104 The maximum number of iterations is 10, but you can choose a different value
3105 with the prefix ARG."
3107 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3109 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3114 (org-table-recalculate 'all
)
3115 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3116 (if (not (string= lasttbl thistbl
))
3117 (setq lasttbl thistbl
)
3119 (message "Convergence after %d iterations" i
)
3120 (message "Table was already stable"))
3122 (error "No convergence after %d iterations" i
))))
3125 (defun org-table-recalculate-buffer-tables ()
3126 "Recalculate all tables in the current buffer."
3131 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
3134 (defun org-table-iterate-buffer-tables ()
3135 "Iterate all tables in the buffer, to converge inter-table dependencies."
3139 (checksum (md5 (buffer-string)))
3147 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
3148 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3150 (message "Convergence after %d iterations" (- imax i
))
3152 (setq checksum c1
)))
3153 (error "No convergence after %d iterations" imax
))))))
3155 (defun org-table-expand-lhs-ranges (equations)
3156 "Expand list of formulas.
3157 If some of the RHS in the formulas are ranges or a row reference, expand
3158 them to individual field equations for each field."
3159 (let (e res lhs rhs range r1 r2 c1 c2
)
3160 (while (setq e
(pop equations
))
3161 (setq lhs
(car e
) rhs
(cdr e
))
3163 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs
)
3164 ;; This just refers to one fixed field
3166 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs
)
3167 ;; This just refers to one fixed named field
3169 ((string-match "^@[0-9]+$" lhs
)
3170 (loop for ic from
1 to org-table-current-ncol do
3171 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
3172 (put-text-property 0 (length (caar res
))
3173 :orig-eqn e
(caar res
))))
3175 (setq range
(org-table-get-range lhs org-table-current-begin-pos
3177 (setq r1
(nth 0 range
) c1
(nth 1 range
)
3178 r2
(nth 2 range
) c2
(nth 3 range
))
3179 (setq r1
(org-table-line-to-dline r1
))
3180 (setq r2
(org-table-line-to-dline r2
'above
))
3181 (loop for ir from r1 to r2 do
3182 (loop for ic from c1 to c2 do
3183 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
3184 (put-text-property 0 (length (caar res
))
3185 :orig-eqn e
(caar res
)))))))
3188 (defun org-table-formula-handle-first/last-rc
(s)
3189 "Replace @<, @>, $<, $> with first/last row/column of the table.
3190 So @< and $< will always be replaced with @1 and $1, respectively.
3191 The advantage of these special markers are that structure editing of
3192 the table will not change them, while @1 and $1 will be modified
3193 when a line/row is swapped out of that privileged position. So for
3194 formulas that use a range of rows or columns, it may often be better
3195 to anchor the formula with \"I\" row markers, or to offset from the
3196 borders of the table using the @< @> $< $> makers."
3197 (let (n nmax len char
(start 0))
3198 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3201 (setq start
(match-end 3))
3202 (setq nmax
(if (equal (match-string 1 s
) "@")
3203 (1- (length org-table-dlines
))
3204 org-table-current-ncol
)
3205 len
(- (match-end 2) (match-beginning 2))
3206 char
(string-to-char (match-string 2 s
))
3210 (if (or (< n
1) (> n nmax
))
3211 (error "Reference \"%s\" in expression \"%s\" points outside table"
3212 (match-string 0 s
) s
))
3213 (setq start
(match-beginning 0))
3214 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3217 (defun org-table-formula-substitute-names (f)
3218 "Replace $const with values in string F."
3219 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
3220 ;; First, check for column names
3221 (while (setq start
(string-match org-table-column-name-regexp f start
))
3222 (setq start
(1+ start
))
3223 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
3224 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
3225 ;; Parameters and constants
3227 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
3229 (setq start
(match-end 2))
3230 (setq start
(1+ start
))
3231 (if (setq a
(save-match-data
3232 (org-table-get-constant (match-string 1 f
))))
3233 (setq f
(replace-match
3234 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
3235 (if org-table-formula-debug
3236 (put-text-property 0 (length f
) :orig-formula f1 f
))
3239 (defun org-table-get-constant (const)
3240 "Find the value for a parameter or constant in a formula.
3241 Parameters get priority."
3242 (or (cdr (assoc const org-table-local-parameters
))
3243 (cdr (assoc const org-table-formula-constants-local
))
3244 (cdr (assoc const org-table-formula-constants
))
3245 (and (fboundp 'constants-get
) (constants-get const
))
3246 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3247 (org-entry-get nil
(substring const
5) 'inherit
))
3250 (defvar org-table-fedit-map
3251 (let ((map (make-sparse-keymap)))
3252 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3253 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3254 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3255 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3256 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3257 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3258 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3259 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3260 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3261 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3262 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3263 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3264 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3265 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3266 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3267 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3268 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3269 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3270 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3271 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3274 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3276 ["Finish and Install" org-table-fedit-finish t
]
3277 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3278 ["Abort" org-table-fedit-abort t
]
3280 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3281 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3283 "Shift Reference at Point"
3284 ["Up" org-table-fedit-ref-up t
]
3285 ["Down" org-table-fedit-ref-down t
]
3286 ["Left" org-table-fedit-ref-left t
]
3287 ["Right" org-table-fedit-ref-right t
]
3289 "Change Test Row for Column Formulas"
3290 ["Up" org-table-fedit-line-up t
]
3291 ["Down" org-table-fedit-line-down t
]
3293 ["Scroll Table Window" org-table-fedit-scroll t
]
3294 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3295 ["Show Table Grid" org-table-fedit-toggle-coordinates
3296 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3297 org-table-overlay-coordinates
)]
3299 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3300 :style toggle
:selected org-table-buffer-is-an
]))
3305 (defun org-table-edit-formulas ()
3306 "Edit the formulas of the current table in a separate buffer."
3308 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+TBLFM")))
3309 (beginning-of-line 0))
3310 (unless (org-at-table-p) (error "Not at a table"))
3311 (org-table-get-specials)
3312 (let ((key (org-table-current-field-formula 'key
'noerror
))
3313 (eql (sort (org-table-get-stored-formulas 'noerror
)
3314 'org-table-formula-less-p
))
3315 (pos (point-marker))
3317 (wc (current-window-configuration))
3318 (sel-win (selected-window))
3319 (titles '((column .
"# Column Formulas\n")
3320 (field .
"# Field and Range Formulas\n")
3321 (named .
"# Named Field Formulas\n")))
3323 (org-switch-to-buffer-other-window "*Edit Formulas*")
3325 ;; Keep global-font-lock-mode from turning on font-lock-mode
3326 (let ((font-lock-global-modes '(not fundamental-mode
)))
3328 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
3329 (org-set-local 'org-pos pos
)
3330 (org-set-local 'org-window-configuration wc
)
3331 (org-set-local 'org-selected-window sel-win
)
3332 (use-local-map org-table-fedit-map
)
3333 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3334 (easy-menu-add org-table-fedit-menu
)
3335 (setq startline
(org-current-line))
3336 (while (setq entry
(pop eql
))
3338 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3339 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3340 ((string-match "^[0-9]" (car entry
)) 'column
)
3342 (when (setq title
(assq type titles
))
3343 (or (bobp) (insert "\n"))
3344 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3345 (setq titles
(remove title titles
)))
3346 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3347 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3348 (car entry
) " = " (cdr entry
) "\n"))
3349 (remove-text-properties 0 (length s
) '(face nil
) s
)
3351 (if (eq org-table-use-standard-references t
)
3352 (org-table-fedit-toggle-ref-type))
3353 (org-goto-line startline
)
3354 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3356 (defun org-table-fedit-post-command ()
3357 (when (not (memq this-command
'(lisp-complete-symbol)))
3358 (let ((win (selected-window)))
3361 (org-table-show-reference)
3363 (select-window win
)))))
3365 (defun org-table-formula-to-user (s)
3366 "Convert a formula from internal to user representation."
3367 (if (eq org-table-use-standard-references t
)
3368 (org-table-convert-refs-to-an s
)
3371 (defun org-table-formula-from-user (s)
3372 "Convert a formula from user to internal representation."
3373 (if org-table-use-standard-references
3374 (org-table-convert-refs-to-rc s
)
3377 (defun org-table-convert-refs-to-rc (s)
3378 "Convert spreadsheet references from A7 to @7$28.
3379 Works for single references, but also for entire formulas and even the
3382 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3385 ;; format match, just advance
3386 (setq start
(match-end 0)))
3387 ((and (> (match-beginning 0) 0)
3388 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3389 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3390 ;; 3.e5 or something like this.
3391 (setq start
(match-end 0)))
3392 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3393 ;; (member (match-string 1 s)
3394 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3396 ;; function name, just advance
3397 (setq start
(match-end 0)))
3399 (setq start
(match-beginning 0)
3401 (if (equal (match-string 2 s
) "&")
3402 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3404 (string-to-number (match-string 2 s
))
3405 (org-letters-to-number (match-string 1 s
))))
3409 (defun org-table-convert-refs-to-an (s)
3410 "Convert spreadsheet references from to @7$28 to AB7.
3411 Works for single references, but also for entire formulas and even the
3413 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3414 (setq s
(replace-match
3416 (org-number-to-letters
3417 (string-to-number (match-string 2 s
)))
3418 (string-to-number (match-string 1 s
)))
3420 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3421 (setq s
(replace-match (concat "\\1"
3422 (org-number-to-letters
3423 (string-to-number (match-string 2 s
))) "&")
3427 (defun org-letters-to-number (s)
3428 "Convert a base 26 number represented by letters into an integer.
3429 For example: AB -> 28."
3432 (while (> (length s
) 0)
3433 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3437 (defun org-number-to-letters (n)
3438 "Convert an integer into a base 26 number represented by letters.
3439 For example: 28 -> AB."
3442 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3446 (defun org-table-time-string-to-seconds (s)
3447 "Convert a time string into numerical duration in seconds.
3448 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3449 If S is a string representing a number, keep this number."
3452 (let (hour minus min sec res
)
3454 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3455 (setq minus
(< 0 (length (match-string 1 s
)))
3456 hour
(string-to-number (match-string 2 s
))
3457 min
(string-to-number (match-string 3 s
))
3458 sec
(string-to-number (match-string 4 s
)))
3460 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3461 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3462 ((and (not (string-match org-ts-regexp-both s
))
3463 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3464 (setq minus
(< 0 (length (match-string 1 s
)))
3465 hour
(string-to-number (match-string 2 s
))
3466 min
(string-to-number (match-string 3 s
)))
3468 (setq res
(- (+ (* hour
3600) (* min
60))))
3469 (setq res
(+ (* hour
3600) (* min
60)))))
3470 (t (setq res
(string-to-number s
))))
3471 (number-to-string res
))))
3473 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3474 "Convert a number of seconds to a time string.
3475 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3476 minutes or seconds."
3477 (let* ((secs0 (abs secs
))
3479 (cond ((eq output-format
'days
)
3480 (format "%.3f" (/ (float secs0
) 86400)))
3481 ((eq output-format
'hours
)
3482 (format "%.2f" (/ (float secs0
) 3600)))
3483 ((eq output-format
'minutes
)
3484 (format "%.1f" (/ (float secs0
) 60)))
3485 ((eq output-format
'seconds
)
3486 (format "%d" secs0
))
3487 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0
)))))
3488 (if (< secs
0) (concat "-" res
) res
)))
3490 (defun org-table-fedit-convert-buffer (function)
3491 "Convert all references in this buffer, using FUNCTION."
3492 (let ((line (org-current-line)))
3493 (goto-char (point-min))
3495 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3496 (delete-region (point) (point-at-eol))
3497 (or (eobp) (forward-char 1)))
3498 (org-goto-line line
)))
3500 (defun org-table-fedit-toggle-ref-type ()
3501 "Convert all references in the buffer from B3 to @3$2 and back."
3503 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3504 (org-table-fedit-convert-buffer
3505 (if org-table-buffer-is-an
3506 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3507 (message "Reference type switched to %s"
3508 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3510 (defun org-table-fedit-ref-up ()
3511 "Shift the reference at point one row/hline up."
3513 (org-table-fedit-shift-reference 'up
))
3514 (defun org-table-fedit-ref-down ()
3515 "Shift the reference at point one row/hline down."
3517 (org-table-fedit-shift-reference 'down
))
3518 (defun org-table-fedit-ref-left ()
3519 "Shift the reference at point one field to the left."
3521 (org-table-fedit-shift-reference 'left
))
3522 (defun org-table-fedit-ref-right ()
3523 "Shift the reference at point one field to the right."
3525 (org-table-fedit-shift-reference 'right
))
3527 (defun org-table-fedit-shift-reference (dir)
3529 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3530 (if (memq dir
'(left right
))
3531 (org-rematch-and-replace 1 (eq dir
'left
))
3532 (error "Cannot shift reference in this direction")))
3533 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3534 ;; A B3-like reference
3535 (if (memq dir
'(up down
))
3536 (org-rematch-and-replace 2 (eq dir
'up
))
3537 (org-rematch-and-replace 1 (eq dir
'left
))))
3539 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3540 ;; An internal reference
3541 (if (memq dir
'(up down
))
3542 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3543 (org-rematch-and-replace 5 (eq dir
'left
))))))
3545 (defun org-rematch-and-replace (n &optional decr hline
)
3546 "Re-match the group N, and replace it with the shifted reference."
3547 (or (match-end n
) (error "Cannot shift reference in this direction"))
3548 (goto-char (match-beginning n
))
3549 (and (looking-at (regexp-quote (match-string n
)))
3550 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3553 (defun org-table-shift-refpart (ref &optional decr hline
)
3554 "Shift a reference part REF.
3555 If DECR is set, decrease the references row/column, else increase.
3556 If HLINE is set, this may be a hline reference, it certainly is not
3557 a translation reference."
3559 (let* ((sign (string-match "^[-+]" ref
)) n
)
3561 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3563 ((and hline
(string-match "^I+" ref
))
3564 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3565 (setq n
(+ n
(if decr -
1 1)))
3566 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3568 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3570 (concat sign
(make-string n ?I
)))
3572 ((string-match "^[0-9]+" ref
)
3573 (setq n
(string-to-number (concat sign ref
)))
3574 (setq n
(+ n
(if decr -
1 1)))
3576 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3577 (number-to-string (max 1 n
))))
3579 ((string-match "^[a-zA-Z]+" ref
)
3580 (org-number-to-letters
3581 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3583 (t (error "Cannot shift reference"))))))
3585 (defun org-table-fedit-toggle-coordinates ()
3586 "Toggle the display of coordinates in the referenced table."
3588 (let ((pos (marker-position org-pos
)))
3589 (with-current-buffer (marker-buffer org-pos
)
3592 (org-table-toggle-coordinate-overlays)))))
3594 (defun org-table-fedit-finish (&optional arg
)
3595 "Parse the buffer for formula definitions and install them.
3596 With prefix ARG, apply the new formulas to the table."
3598 (org-table-remove-rectangle-highlight)
3599 (if org-table-use-standard-references
3601 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3602 (setq org-table-buffer-is-an nil
)))
3603 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3604 (goto-char (point-min))
3605 (while (re-search-forward
3606 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3608 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3609 form
(match-string 3))
3610 (setq form
(org-trim form
))
3611 (when (not (equal form
""))
3612 (while (string-match "[ \t]*\n[ \t]*" form
)
3613 (setq form
(replace-match " " t t form
)))
3614 (when (assoc var eql
)
3615 (error "Double formulas for %s" var
))
3616 (push (cons var form
) eql
)))
3618 (set-window-configuration org-window-configuration
)
3619 (select-window sel-win
)
3621 (unless (org-at-table-p)
3622 (error "Lost table position - cannot install formulas"))
3623 (org-table-store-formulas eql
)
3624 (move-marker pos nil
)
3625 (kill-buffer "*Edit Formulas*")
3627 (org-table-recalculate 'all
)
3628 (message "New formulas installed - press C-u C-c C-c to apply."))))
3630 (defun org-table-fedit-abort ()
3631 "Abort editing formulas, without installing the changes."
3633 (org-table-remove-rectangle-highlight)
3634 (let ((pos org-pos
) (sel-win org-selected-window
))
3635 (set-window-configuration org-window-configuration
)
3636 (select-window sel-win
)
3638 (move-marker pos nil
)
3639 (message "Formula editing aborted without installing changes")))
3641 (defun org-table-fedit-lisp-indent ()
3642 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3644 (let ((pos (point)) beg end ind
)
3645 (beginning-of-line 1)
3647 ((looking-at "[ \t]")
3649 (call-interactively 'lisp-indent-line
))
3650 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3651 ((not (fboundp 'pp-buffer
))
3652 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3653 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3654 (goto-char (- (match-end 0) 2))
3656 (setq ind
(make-string (current-column) ?\
))
3657 (condition-case nil
(forward-sexp 1)
3659 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3662 (narrow-to-region beg end
)
3663 (if (eq last-command this-command
)
3665 (goto-char (point-min))
3666 (setq this-command nil
)
3667 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3668 (replace-match " ")))
3670 (untabify (point-min) (point-max))
3671 (goto-char (1+ (point-min)))
3672 (while (re-search-forward "^." nil t
)
3673 (beginning-of-line 1)
3675 (goto-char (point-max))
3676 (org-delete-backward-char 1)))
3680 (defvar org-show-positions nil
)
3682 (defun org-table-show-reference (&optional local
)
3683 "Show the location/value of the $ expression at point."
3685 (org-table-remove-rectangle-highlight)
3687 (let ((pos (if local
(point) org-pos
))
3689 (org-inhibit-highlight-removal t
)
3690 (win (selected-window))
3691 (org-show-positions nil
)
3692 var name e what match dest
)
3693 (if local
(org-table-get-specials))
3695 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3696 (setq match
(concat (substring (match-string 0) 0 -
1)
3698 (substring (match-string 0) 0 -
1)
3701 ((or (org-at-regexp-p org-table-range-regexp2
)
3702 (org-at-regexp-p org-table-translate-regexp
)
3703 (org-at-regexp-p org-table-range-regexp
))
3706 (org-table-convert-refs-to-rc (match-string 0))))
3708 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3709 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3711 (t (error "No reference at point")))
3712 match
(and what
(or match
(match-string 0))))
3713 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3714 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3715 'secondary-selection
))
3716 (org-add-hook 'before-change-functions
3717 'org-table-remove-rectangle-highlight
)
3718 (if (eq what
'name
) (setq var
(substring match
1)))
3719 (when (eq what
'range
)
3720 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3721 (setq match
(org-table-formula-substitute-names match
)))
3725 (re-search-backward "^\\S-" nil t
)
3726 (beginning-of-line 1)
3727 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3730 (org-table-convert-refs-to-rc (match-string 1))))
3731 (org-table-add-rectangle-overlay
3732 (match-beginning 1) (match-end 1) face2
))))
3733 (if (and (markerp pos
) (marker-buffer pos
))
3734 (if (get-buffer-window (marker-buffer pos
))
3735 (select-window (get-buffer-window (marker-buffer pos
)))
3736 (org-switch-to-buffer-other-window (get-buffer-window
3737 (marker-buffer pos
)))))
3739 (org-table-force-dataline)
3741 (setq name
(substring dest
1))
3743 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3744 (setq e
(assoc name org-table-named-field-locations
))
3745 (org-goto-line (nth 1 e
))
3746 (org-table-goto-column (nth 2 e
)))
3747 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3748 (let ((l (string-to-number (match-string 1 dest
)))
3749 (c (string-to-number (match-string 2 dest
))))
3750 (org-goto-line (aref org-table-dlines l
))
3751 (org-table-goto-column c
)))
3752 (t (org-table-goto-column (string-to-number name
))))
3753 (move-marker pos
(point))
3754 (org-table-highlight-rectangle nil nil face2
))
3756 ((equal dest match
))
3761 (org-table-get-range match nil nil
'highlight
))
3763 ((setq e
(assoc var org-table-named-field-locations
))
3764 (org-goto-line (nth 1 e
))
3765 (org-table-goto-column (nth 2 e
))
3766 (org-table-highlight-rectangle (point) (point))
3767 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3768 ((setq e
(assoc var org-table-column-names
))
3769 (org-table-goto-column (string-to-number (cdr e
)))
3770 (org-table-highlight-rectangle (point) (point))
3771 (goto-char (org-table-begin))
3772 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3775 (goto-char (match-beginning 1))
3776 (org-table-highlight-rectangle)
3777 (message "Named column (column %s)" (cdr e
)))
3778 (error "Column name not found")))
3781 (org-table-goto-column (string-to-number (substring match
1)))
3782 (org-table-highlight-rectangle (point) (point))
3783 (message "Column %s" (substring match
1)))
3784 ((setq e
(assoc var org-table-local-parameters
))
3785 (goto-char (org-table-begin))
3786 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3788 (goto-char (match-beginning 1))
3789 (org-table-highlight-rectangle)
3790 (message "Local parameter."))
3791 (error "Parameter not found")))
3794 ((not var
) (error "No reference at point"))
3795 ((setq e
(assoc var org-table-formula-constants-local
))
3796 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3798 ((setq e
(assoc var org-table-formula-constants
))
3799 (message "Constant: $%s=%s in `org-table-formula-constants'."
3801 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3802 (message "Constant: $%s=%s, from `constants.el'%s."
3803 var e
(format " (%s units)" constants-unit-system
)))
3804 (t (error "Undefined name $%s" var
)))))
3806 (when (and org-show-positions
3807 (not (memq this-command
'(org-table-fedit-scroll
3808 org-table-fedit-scroll-down
))))
3809 (push pos org-show-positions
)
3810 (push org-table-current-begin-pos org-show-positions
)
3811 (let ((min (apply 'min org-show-positions
))
3812 (max (apply 'max org-show-positions
)))
3813 (goto-char min
) (recenter 0)
3815 (or (pos-visible-in-window-p max
) (recenter -
1))))
3816 (select-window win
))))
3818 (defun org-table-force-dataline ()
3819 "Make sure the cursor is in a dataline in a table."
3820 (unless (save-excursion
3821 (beginning-of-line 1)
3822 (looking-at org-table-dataline-regexp
))
3823 (let* ((re org-table-dataline-regexp
)
3824 (p1 (save-excursion (re-search-forward re nil
'move
)))
3825 (p2 (save-excursion (re-search-backward re nil
'move
))))
3827 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3829 ((or p1 p2
) (goto-char (or p1 p2
)))
3830 (t (error "No table dataline around here"))))))
3832 (defun org-table-fedit-line-up ()
3833 "Move cursor one line up in the window showing the table."
3835 (org-table-fedit-move 'previous-line
))
3837 (defun org-table-fedit-line-down ()
3838 "Move cursor one line down in the window showing the table."
3840 (org-table-fedit-move 'next-line
))
3842 (defun org-table-fedit-move (command)
3843 "Move the cursor in the window showing the table.
3844 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3845 (let ((org-table-allow-automatic-line-recalculation nil
)
3846 (pos org-pos
) (win (selected-window)) p
)
3847 (select-window (get-buffer-window (marker-buffer org-pos
)))
3849 (call-interactively command
)
3850 (while (and (org-at-table-p)
3851 (org-at-table-hline-p))
3852 (call-interactively command
))
3853 (or (org-at-table-p) (goto-char p
))
3854 (move-marker pos
(point))
3855 (select-window win
)))
3857 (defun org-table-fedit-scroll (N)
3859 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3860 (scroll-other-window N
)))
3862 (defun org-table-fedit-scroll-down (N)
3864 (org-table-fedit-scroll (- N
)))
3866 (defvar org-table-rectangle-overlays nil
)
3868 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3869 "Add a new overlay."
3870 (let ((ov (make-overlay beg end
)))
3871 (overlay-put ov
'face
(or face
'secondary-selection
))
3872 (push ov org-table-rectangle-overlays
)))
3874 (defun org-table-highlight-rectangle (&optional beg end face
)
3875 "Highlight rectangular region in a table."
3876 (setq beg
(or beg
(point)) end
(or end
(point)))
3877 (let ((b (min beg end
))
3880 (and (boundp 'org-show-positions
)
3881 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3882 (goto-char (min beg end
))
3883 (setq l1
(org-current-line)
3884 c1
(org-table-current-column))
3885 (goto-char (max beg end
))
3886 (setq l2
(org-current-line)
3887 c2
(org-table-current-column))
3888 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3890 (beginning-of-line 1)
3891 (loop for line from l1 to l2 do
3892 (when (looking-at org-table-dataline-regexp
)
3893 (org-table-goto-column c1
)
3894 (skip-chars-backward "^|\n") (setq beg
(point))
3895 (org-table-goto-column c2
)
3896 (skip-chars-forward "^|\n") (setq end
(point))
3897 (org-table-add-rectangle-overlay beg end face
))
3898 (beginning-of-line 2))
3900 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3902 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3903 "Remove the rectangle overlays."
3904 (unless org-inhibit-highlight-removal
3905 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3906 (mapc 'delete-overlay org-table-rectangle-overlays
)
3907 (setq org-table-rectangle-overlays nil
)))
3909 (defvar org-table-coordinate-overlays nil
3910 "Collects the coordinate grid overlays, so that they can be removed.")
3911 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3913 (defun org-table-overlay-coordinates ()
3914 "Add overlays to the table at point, to show row/column coordinates."
3916 (mapc 'delete-overlay org-table-coordinate-overlays
)
3917 (setq org-table-coordinate-overlays nil
)
3919 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3920 (goto-char (org-table-begin))
3921 (while (org-at-table-p)
3922 (setq eol
(point-at-eol))
3923 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
3924 (push ov org-table-coordinate-overlays
)
3925 (setq hline
(looking-at org-table-hline-regexp
))
3926 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3927 (format "%4d" (setq id
(1+ id
)))))
3928 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3931 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3932 (setq beg
(1+ (match-beginning 0))
3934 s1
(concat "$" (int-to-string ic
))
3935 s2
(org-number-to-letters ic
)
3936 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3937 (setq ov
(make-overlay beg
(+ beg
(length str
))))
3938 (push ov org-table-coordinate-overlays
)
3939 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3940 (beginning-of-line 2)))))
3943 (defun org-table-toggle-coordinate-overlays ()
3944 "Toggle the display of Row/Column numbers in tables."
3946 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3947 (message "Tables Row/Column numbers display turned %s"
3948 (if org-table-overlay-coordinates
"on" "off"))
3949 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3951 (unless org-table-overlay-coordinates
3952 (mapc 'delete-overlay org-table-coordinate-overlays
)
3953 (setq org-table-coordinate-overlays nil
)))
3956 (defun org-table-toggle-formula-debugger ()
3957 "Toggle the formula debugger in tables."
3959 (setq org-table-formula-debug
(not org-table-formula-debug
))
3960 (message "Formula debugging has been turned %s"
3961 (if org-table-formula-debug
"on" "off")))
3963 ;;; The orgtbl minor mode
3965 ;; Define a minor mode which can be used in other modes in order to
3966 ;; integrate the org-mode table editor.
3968 ;; This is really a hack, because the org-mode table editor uses several
3969 ;; keys which normally belong to the major mode, for example the TAB and
3970 ;; RET keys. Here is how it works: The minor mode defines all the keys
3971 ;; necessary to operate the table editor, but wraps the commands into a
3972 ;; function which tests if the cursor is currently inside a table. If that
3973 ;; is the case, the table editor command is executed. However, when any of
3974 ;; those keys is used outside a table, the function uses `key-binding' to
3975 ;; look up if the key has an associated command in another currently active
3976 ;; keymap (minor modes, major mode, global), and executes that command.
3977 ;; There might be problems if any of the keys used by the table editor is
3978 ;; otherwise used as a prefix key.
3980 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3981 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3982 ;; addresses this by checking explicitly for both bindings.
3984 ;; The optimized version (see variable `orgtbl-optimized') takes over
3985 ;; all keys which are bound to `self-insert-command' in the *global map*.
3986 ;; Some modes bind other commands to simple characters, for example
3987 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3988 ;; active, this binding is ignored inside tables and replaced with a
3989 ;; modified self-insert.
3992 (defvar orgtbl-mode-map
(make-keymap)
3993 "Keymap for `orgtbl-mode'.")
3995 (defvar org-old-auto-fill-inhibit-regexp nil
3996 "Local variable used by `orgtbl-mode'.")
3998 (defconst orgtbl-line-start-regexp
3999 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4000 "Matches a line belonging to an orgtbl.")
4002 (defconst orgtbl-extra-font-lock-keywords
4003 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4004 0 (quote 'org-table
) 'prepend
))
4005 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4007 ;; Install it as a minor mode.
4008 (put 'orgtbl-mode
:included t
)
4009 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4012 (define-minor-mode orgtbl-mode
4013 "The `org-mode' table editor as a minor mode for use in other modes."
4014 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4015 (org-load-modules-maybe)
4017 ((derived-mode-p 'org-mode
)
4018 ;; Exit without error, in case some hook functions calls this
4019 ;; by accident in org-mode.
4020 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4022 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4023 ;; Make sure we are first in minor-mode-map-alist
4024 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4025 ;; FIXME: maybe it should use emulation-mode-map-alists?
4026 (and c
(setq minor-mode-map-alist
4027 (cons c
(delq c minor-mode-map-alist
)))))
4028 (org-set-local (quote org-table-may-need-update
) t
)
4029 (org-add-hook 'before-change-functions
'org-before-change-function
4031 (org-set-local 'org-old-auto-fill-inhibit-regexp
4032 auto-fill-inhibit-regexp
)
4033 (org-set-local 'auto-fill-inhibit-regexp
4034 (if auto-fill-inhibit-regexp
4035 (concat orgtbl-line-start-regexp
"\\|"
4036 auto-fill-inhibit-regexp
)
4037 orgtbl-line-start-regexp
))
4038 (add-to-invisibility-spec '(org-cwidth))
4039 (when (fboundp 'font-lock-add-keywords
)
4040 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4041 (org-restart-font-lock))
4042 (easy-menu-add orgtbl-mode-menu
))
4044 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4045 (org-table-cleanup-narrow-column-properties)
4046 (org-remove-from-invisibility-spec '(org-cwidth))
4047 (remove-hook 'before-change-functions
'org-before-change-function t
)
4048 (when (fboundp 'font-lock-remove-keywords
)
4049 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4050 (org-restart-font-lock))
4051 (easy-menu-remove orgtbl-mode-menu
)
4052 (force-mode-line-update 'all
))))
4054 (defun org-table-cleanup-narrow-column-properties ()
4055 "Remove all properties related to narrow-column invisibility."
4056 (let ((s (point-min)))
4057 (while (setq s
(text-property-any s
(point-max)
4058 'display org-narrow-column-arrow
))
4059 (remove-text-properties s
(1+ s
) '(display t
)))
4060 (setq s
(point-min))
4061 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
4062 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
4063 (setq s
(point-min))
4064 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
4065 (remove-text-properties s
(1+ s
) '(invisible t
)))))
4067 (defun orgtbl-make-binding (fun n
&rest keys
)
4068 "Create a function for binding in the table minor mode.
4069 FUN is the command to call inside a table. N is used to create a unique
4070 command name. KEYS are keys that should be checked in for a command
4071 to execute outside of tables."
4074 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4076 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4077 "Outside of tables, run the binding of `"
4078 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
4083 (list 'call-interactively
(list 'quote fun
))
4084 (list 'let
'(orgtbl-mode)
4085 (list 'call-interactively
4088 (list 'key-binding k
))
4090 '('orgtbl-error
))))))))
4092 (defun orgtbl-error ()
4093 "Error when there is no default binding for a table key."
4095 (error "This key has no function outside tables"))
4097 (defun orgtbl-setup ()
4098 "Setup orgtbl keymaps."
4101 '(([(meta shift left
)] org-table-delete-column
)
4102 ([(meta left
)] org-table-move-column-left
)
4103 ([(meta right
)] org-table-move-column-right
)
4104 ([(meta shift right
)] org-table-insert-column
)
4105 ([(meta shift up
)] org-table-kill-row
)
4106 ([(meta shift down
)] org-table-insert-row
)
4107 ([(meta up
)] org-table-move-row-up
)
4108 ([(meta down
)] org-table-move-row-down
)
4109 ("\C-c\C-w" org-table-cut-region
)
4110 ("\C-c\M-w" org-table-copy-region
)
4111 ("\C-c\C-y" org-table-paste-rectangle
)
4112 ("\C-c\C-w" org-table-wrap-region
)
4113 ("\C-c-" org-table-insert-hline
)
4114 ("\C-c}" org-table-toggle-coordinate-overlays
)
4115 ("\C-c{" org-table-toggle-formula-debugger
)
4116 ("\C-m" org-table-next-row
)
4117 ([(shift return
)] org-table-copy-down
)
4118 ("\C-c?" org-table-field-info
)
4119 ("\C-c " org-table-blank-field
)
4120 ("\C-c+" org-table-sum
)
4121 ("\C-c=" org-table-eval-formula
)
4122 ("\C-c'" org-table-edit-formulas
)
4123 ("\C-c`" org-table-edit-field
)
4124 ("\C-c*" org-table-recalculate
)
4125 ("\C-c^" org-table-sort-lines
)
4126 ("\M-a" org-table-beginning-of-field
)
4127 ("\M-e" org-table-end-of-field
)
4128 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4130 (while (setq elt
(pop bindings
))
4131 (setq nfunc
(1+ nfunc
))
4132 (setq key
(org-key (car elt
))
4134 cmd
(orgtbl-make-binding fun nfunc key
))
4135 (org-defkey orgtbl-mode-map key cmd
))
4137 ;; Special treatment needed for TAB and RET
4138 (org-defkey orgtbl-mode-map
[(return)]
4139 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4140 (org-defkey orgtbl-mode-map
"\C-m"
4141 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4143 (org-defkey orgtbl-mode-map
[(tab)]
4144 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4145 (org-defkey orgtbl-mode-map
"\C-i"
4146 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4148 (org-defkey orgtbl-mode-map
[(shift tab
)]
4149 (orgtbl-make-binding 'org-table-previous-field
104
4150 [(shift tab
)] [(tab)] "\C-i"))
4153 (unless (featurep 'xemacs
)
4154 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4155 (orgtbl-make-binding 'org-table-previous-field
107
4156 [S-iso-lefttab
] [backtab] [(shift tab)]
4159 (org-defkey orgtbl-mode-map [backtab]
4160 (orgtbl-make-binding 'org-table-previous-field
108
4161 [backtab] [S-iso-lefttab] [(shift tab)]
4164 (org-defkey orgtbl-mode-map "\M-\C-m"
4165 (orgtbl-make-binding 'org-table-wrap-region 105
4166 "\M-\C-m" [(meta return)]))
4167 (org-defkey orgtbl-mode-map [(meta return)]
4168 (orgtbl-make-binding 'org-table-wrap-region 106
4169 [(meta return)] "\M-\C-m"))
4171 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4172 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4174 (when orgtbl-optimized
4175 ;; If the user wants maximum table support, we need to hijack
4176 ;; some standard editing functions
4177 (org-remap orgtbl-mode-map
4178 'self-insert-command 'orgtbl-self-insert-command
4179 'delete-char 'org-delete-char
4180 'delete-backward-char 'org-delete-backward-char)
4181 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4182 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4184 ["Create or convert" org-table-create-or-convert-from-region
4185 :active (not (org-at-table-p)) :keys "C-c |" ]
4187 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4188 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4189 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4190 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4192 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4193 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4194 ["Copy Field from Above"
4195 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4198 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4199 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4200 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4201 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4203 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4204 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4205 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4206 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4207 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4209 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4211 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4212 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4213 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4214 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4217 ["Insert table template" orgtbl-insert-radio-table
4218 (assq major-mode orgtbl-radio-table-templates)]
4219 ["Comment/uncomment table" orgtbl-toggle-comment t])
4221 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4222 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4223 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4224 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4225 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4226 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4227 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4228 ["Sum Column/Rectangle" org-table-sum
4229 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4230 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4232 org-table-toggle-formula-debugger :active (org-at-table-p)
4234 :style toggle :selected org-table-formula-debug]
4235 ["Show Col/Row Numbers"
4236 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4238 :style toggle :selected org-table-overlay-coordinates]
4242 (defun orgtbl-ctrl-c-ctrl-c (arg)
4243 "If the cursor is inside a table, realign the table.
4244 If it is a table to be sent away to a receiver, do it.
4245 With prefix arg, also recompute table."
4247 (let ((case-fold-search t) (pos (point)) action consts-str consts cst const-str)
4249 (beginning-of-line 1)
4251 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4252 ((looking-at "[ \t]*|") pos)
4253 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4257 (org-table-maybe-eval-formula)
4259 (call-interactively 'org-table-recalculate)
4260 (org-table-maybe-recalculate-line))
4261 (call-interactively 'org-table-align)
4262 (when (orgtbl-send-table 'maybe)
4263 (run-hooks 'orgtbl-after-send-table-hook)))
4264 ((eq action 'recalc)
4266 (goto-char (point-min))
4267 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t)
4268 (setq const-str (substring-no-properties (match-string 1)))
4269 (setq consts (append consts (org-split-string const-str "[ \t]+")))
4272 (while (setq e (pop consts))
4273 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4274 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4275 (setq org-table-formula-constants-local cst)))))
4277 (beginning-of-line 1)
4278 (skip-chars-backward " \r\n\t")
4279 (if (org-at-table-p)
4280 (org-call-with-arg 'org-table-recalculate t))))
4281 (t (let (orgtbl-mode)
4282 (call-interactively (key-binding "\C-c\C-c")))))))
4284 (defun orgtbl-create-or-convert-from-region (arg)
4285 "Create table or convert region to table, if no conflicting binding.
4286 This installs the table binding `C-c |', but only if there is no
4287 conflicting binding to this key outside orgtbl-mode."
4289 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4291 (call-interactively cmd)
4292 (call-interactively 'org-table-create-or-convert-from-region))))
4294 (defun orgtbl-tab (arg)
4295 "Justification and field motion for `orgtbl-mode'."
4297 (if arg (org-table-edit-field t)
4298 (org-table-justify-field-maybe)
4299 (org-table-next-field)))
4301 (defun orgtbl-ret ()
4302 "Justification and field motion for `orgtbl-mode'."
4306 (org-table-justify-field-maybe)
4307 (org-table-next-row)))
4309 (defun orgtbl-self-insert-command (N)
4310 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4311 If the cursor is in a table looking at whitespace, the whitespace is
4312 overwritten, and the table is not marked as requiring realignment."
4314 (if (and (org-at-table-p)
4316 (and org-table-auto-blank-field
4317 (member last-command
4318 '(orgtbl-hijacker-command-100
4319 orgtbl-hijacker-command-101
4320 orgtbl-hijacker-command-102
4321 orgtbl-hijacker-command-103
4322 orgtbl-hijacker-command-104
4323 orgtbl-hijacker-command-105
4325 (org-table-blank-field))
4328 (looking-at "[^|\n]* +|"))
4329 (let (org-table-may-need-update)
4330 (goto-char (1- (match-end 0)))
4331 (org-delete-backward-char 1)
4332 (goto-char (match-beginning 0))
4333 (self-insert-command N))
4334 (setq org-table-may-need-update t)
4337 (cmd (or (key-binding
4338 (or (and (listp function-key-map)
4339 (setq a (assoc last-input-event function-key-map))
4341 (vector last-input-event)))
4342 'self-insert-command)))
4343 (call-interactively cmd)
4344 (if (and org-self-insert-cluster-for-undo
4345 (eq cmd 'self-insert-command))
4346 (if (not (eq last-command 'orgtbl-self-insert-command))
4347 (setq org-self-insert-command-undo-counter 1)
4348 (if (>= org-self-insert-command-undo-counter 20)
4349 (setq org-self-insert-command-undo-counter 1)
4350 (and (> org-self-insert-command-undo-counter 0)
4352 (not (cadr buffer-undo-list)) ; remove nil entry
4353 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4354 (setq org-self-insert-command-undo-counter
4355 (1+ org-self-insert-command-undo-counter))))))))
4357 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4358 "Regular expression matching exponentials as produced by calc.")
4360 (defun orgtbl-export (table target)
4361 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
4362 (lines (org-split-string table "[ \t]*\n[ \t]*"))
4363 org-table-last-alignment org-table-last-column-widths
4365 (if (not (fboundp func))
4366 (error "Cannot export orgtbl table to %s" target))
4367 (setq lines (org-table-clean-before-export lines))
4371 (if (string-match org-table-hline-regexp x)
4373 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4375 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
4377 (loop for i from (1- maxcol) downto 0 do
4378 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
4379 (setq column (delq nil column))
4380 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
4381 (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))
4382 (funcall func table nil)))
4384 (defun orgtbl-gather-send-defs ()
4385 "Gather a plist of :name, :transform, :params for each destination before
4388 (goto-char (org-table-begin))
4390 (beginning-of-line 0)
4391 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4392 (let ((name (org-no-properties (match-string 1)))
4393 (transform (intern (match-string 2)))
4394 (params (if (match-end 3)
4395 (read (concat "(" (match-string 3) ")")))))
4396 (push (list :name name :transform transform :params params)
4398 (beginning-of-line 0)))
4401 (defun orgtbl-send-replace-tbl (name txt)
4402 "Find and replace table NAME with TXT."
4404 (goto-char (point-min))
4405 (unless (re-search-forward
4406 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4407 (error "Don't know where to insert translated table"))
4408 (goto-char (match-beginning 0))
4409 (beginning-of-line 2)
4411 (let ((beg (point)))
4412 (unless (re-search-forward
4413 (concat "END RECEIVE ORGTBL +" name) nil t)
4414 (error "Cannot find end of insertion region"))
4415 (beginning-of-line 1)
4416 (delete-region beg (point))))
4420 (defun org-table-to-lisp (&optional txt)
4421 "Convert the table at point to a Lisp structure.
4422 The structure will be a list. Each item is either the symbol `hline'
4423 for a horizontal separator line, or a list of field values as strings.
4424 The table is taken from the parameter TXT, or from the buffer at point."
4426 (unless (org-at-table-p)
4427 (error "No table at point")))
4429 (buffer-substring-no-properties (org-table-begin)
4431 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4435 (if (string-match org-table-hline-regexp x)
4437 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4440 (defun orgtbl-send-table (&optional maybe)
4441 "Send a transformed version of this table to the receiver position.
4442 With argument MAYBE, fail quietly if no transformation is defined for
4446 (unless (org-at-table-p) (error "Not at a table"))
4447 ;; when non-interactive, we assume align has just happened.
4448 (when (org-called-interactively-p 'any) (org-table-align))
4449 (let ((dests (orgtbl-gather-send-defs))
4450 (txt (buffer-substring-no-properties (org-table-begin)
4453 (unless dests (if maybe (throw 'exit nil)
4454 (error "Don't know how to transform this table")))
4455 (dolist (dest dests)
4456 (let* ((name (plist-get dest :name))
4457 (transform (plist-get dest :transform))
4458 (params (plist-get dest :params))
4459 (skip (plist-get params :skip))
4460 (skipcols (plist-get params :skipcols))
4461 (no-escape (plist-get params :no-escape))
4463 (lines (org-table-clean-before-export
4465 (org-split-string txt "[ \t]*\n[ \t]*"))))
4466 (i0 (if org-table-clean-did-remove-column 2 1))
4467 (lines (if no-escape lines
4468 (mapcar (lambda(l) (replace-regexp-in-string
4469 "\\([&%#_^]\\)" "\\\\\\1{}" l)) lines)))
4472 (if (string-match org-table-hline-regexp x)
4474 (org-remove-by-index
4475 (org-split-string (org-trim x) "\\s-*|\\s-*")
4478 (fun (if (= i0 2) 'cdr 'identity))
4479 (org-table-last-alignment
4480 (org-remove-by-index (funcall fun org-table-last-alignment)
4482 (org-table-last-column-widths
4483 (org-remove-by-index (funcall fun org-table-last-column-widths)
4485 (txt (if (fboundp transform)
4486 (funcall transform table params)
4487 (error "No such transformation function %s" transform))))
4488 (orgtbl-send-replace-tbl name txt))
4489 (setq ntbl (1+ ntbl)))
4490 (message "Table converted and installed at %d receiver location%s"
4491 ntbl (if (> ntbl 1) "s" ""))
4496 (defun org-remove-by-index (list indices &optional i0)
4497 "Remove the elements in LIST with indices in INDICES.
4498 First element has index 0, or I0 if given."
4501 (if (integerp indices) (setq indices (list indices)))
4502 (setq i0 (1- (or i0 0)))
4503 (delq :rm (mapcar (lambda (x)
4505 (if (memq i0 indices) :rm x))
4508 (defun orgtbl-toggle-comment ()
4509 "Comment or uncomment the orgtbl at point."
4511 (let* ((case-fold-search t)
4512 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4513 (re2 (concat "^" orgtbl-line-start-regexp))
4514 (commented (save-excursion (beginning-of-line 1)
4515 (cond ((looking-at re1) t)
4516 ((looking-at re2) nil)
4517 (t (error "Not at an org table")))))
4518 (re (if commented re1 re2))
4521 (beginning-of-line 1)
4522 (while (looking-at re) (beginning-of-line 0))
4523 (beginning-of-line 2)
4525 (while (looking-at re) (beginning-of-line 2))
4527 (comment-region beg end (if commented '(4) nil))))
4529 (defun orgtbl-insert-radio-table ()
4530 "Insert a radio table template appropriate for this major mode."
4532 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4535 (unless e (error "No radio table setup defined for %s" major-mode))
4536 (setq name (read-string "Table name: "))
4537 (while (string-match "%n" txt)
4538 (setq txt (replace-match name t t txt)))
4539 (or (bolp) (insert "\n"))
4544 ;; Dynamically bound input and output for table formatting.
4545 (defvar *orgtbl-table* nil
4546 "Carries the current table through formatting routines.")
4547 (defvar *orgtbl-rtn* nil
4548 "Formatting routines push the output lines here.")
4549 ;; Formatting parameters for the current table section.
4550 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4551 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4552 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4553 (defvar *orgtbl-fmt* nil "Format for each entry.")
4554 (defvar *orgtbl-efmt* nil "Format for numbers.")
4555 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4556 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4557 (defvar *orgtbl-lstart* nil "Text starting a row.")
4558 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4559 (defvar *orgtbl-lend* nil "Text ending a row.")
4560 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4562 (defsubst orgtbl-get-fmt (fmt i)
4563 "Retrieve the format from FMT corresponding to the Ith column."
4564 (if (and (not (functionp fmt)) (consp fmt))
4568 (defsubst orgtbl-apply-fmt (fmt &rest args)
4569 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4570 (cond ((functionp fmt) (apply fmt args))
4571 (fmt (apply 'format fmt args))
4575 (defsubst orgtbl-eval-str (str)
4576 "If STR is a function, evaluate it with no arguments."
4581 (defun orgtbl-format-line (line)
4582 "Format LINE as a table row."
4583 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4589 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4590 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4591 (orgtbl-apply-fmt efmt (match-string 1 f)
4594 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4595 *orgtbl-default-fmt*)
4598 (push (if *orgtbl-lfmt*
4599 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4600 (concat (orgtbl-eval-str *orgtbl-lstart*)
4601 (mapconcat 'identity line *orgtbl-sep*)
4602 (orgtbl-eval-str *orgtbl-lend*)))
4605 (defun orgtbl-format-section (section-stopper)
4606 "Format lines until the first occurrence of SECTION-STOPPER."
4609 (while (not (eq (car *orgtbl-table*) section-stopper))
4610 (if prevline (orgtbl-format-line prevline))
4611 (setq prevline (pop *orgtbl-table*)))
4612 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4613 (*orgtbl-lend* *orgtbl-llend*)
4614 (*orgtbl-lfmt* *orgtbl-llfmt*))
4615 (orgtbl-format-line prevline))))))
4618 (defun orgtbl-to-generic (table params)
4619 "Convert the orgtbl-mode TABLE to some other format.
4620 This generic routine can be used for many standard cases.
4621 TABLE is a list, each entry either the symbol `hline' for a horizontal
4622 separator line, or a list of fields for that line.
4623 PARAMS is a property list of parameters that can influence the conversion.
4624 For the generic converter, some parameters are obligatory: you need to
4625 specify either :lfmt, or all of (:lstart :lend :sep).
4627 Valid parameters are:
4629 :splice When set to t, return only table body lines, don't wrap
4630 them into :tstart and :tend. Default is nil. When :splice
4631 is non-nil, this also means that the exporter should not look
4632 for and interpret header and footer sections.
4634 :hline String to be inserted on horizontal separation lines.
4635 May be nil to ignore hlines.
4637 :sep Separator between two fields
4638 :remove-nil-lines Do not include lines that evaluate to nil.
4640 Each in the following group may be either a string or a function
4641 of no arguments returning a string:
4643 :tstart String to start the table. Ignored when :splice is t.
4644 :tend String to end the table. Ignored when :splice is t.
4645 :lstart String to start a new table line.
4646 :llstart String to start the last table line, defaults to :lstart.
4647 :lend String to end a table line
4648 :llend String to end the last table line, defaults to :lend.
4650 Each in the following group may be a string, a function of one
4651 argument (the field or line) returning a string, or a plist
4652 mapping columns to either of the above:
4654 :lfmt Format for entire line, with enough %s to capture all fields.
4655 If this is present, :lstart, :lend, and :sep are ignored.
4656 :llfmt Format for the entire last line, defaults to :lfmt.
4657 :fmt A format to be used to wrap the field, should contain
4658 %s for the original field value. For example, to wrap
4659 everything in dollars, you could use :fmt \"$%s$\".
4660 This may also be a property list with column numbers and
4661 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4662 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4663 Same as above, specific for the header lines in the table.
4664 All lines before the first hline are treated as header.
4665 If any of these is not present, the data line value is used.
4667 This may be either a string or a function of two arguments:
4669 :efmt Use this format to print numbers with exponentials.
4670 The format should have %s twice for inserting mantissa
4671 and exponent, for example \"%s\\\\times10^{%s}\". This
4672 may also be a property list with column numbers and
4673 formats. :fmt will still be applied after :efmt.
4675 In addition to this, the parameters :skip and :skipcols are always handled
4676 directly by `orgtbl-send-table'. See manual."
4677 (let* ((splicep (plist-get params :splice))
4678 (hline (plist-get params :hline))
4679 (skipheadrule (plist-get params :skipheadrule))
4680 (remove-nil-linesp (plist-get params :remove-nil-lines))
4681 (remove-newlines (plist-get params :remove-newlines))
4682 (*orgtbl-hline* hline)
4683 (*orgtbl-table* table)
4684 (*orgtbl-sep* (plist-get params :sep))
4685 (*orgtbl-efmt* (plist-get params :efmt))
4686 (*orgtbl-lstart* (plist-get params :lstart))
4687 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4688 (*orgtbl-lend* (plist-get params :lend))
4689 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4690 (*orgtbl-lfmt* (plist-get params :lfmt))
4691 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4692 (*orgtbl-fmt* (plist-get params :fmt))
4697 (when (plist-member params :tstart)
4698 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4699 (if tstart (push tstart *orgtbl-rtn*)))))
4701 ;; Do we have a heading section? If so, format it and handle the
4703 (if (and (not splicep)
4704 (or (consp (car *orgtbl-table*))
4705 (consp (nth 1 *orgtbl-table*)))
4706 (memq 'hline (cdr *orgtbl-table*)))
4708 (when (eq 'hline (car *orgtbl-table*))
4709 ;; there is a hline before the first data line
4710 (and hline (push hline *orgtbl-rtn*))
4711 (pop *orgtbl-table*))
4712 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4714 (*orgtbl-llstart* (or (plist-get params :hllstart)
4716 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4717 (*orgtbl-llend* (or (plist-get params :hllend)
4718 (plist-get params :hlend) *orgtbl-llend*))
4719 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4720 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4721 (plist-get params :hlfmt) *orgtbl-llfmt*))
4722 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4723 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4724 (orgtbl-format-section 'hline))
4725 (if (and hline (not skipheadrule)) (push hline *orgtbl-rtn*))
4726 (pop *orgtbl-table*)))
4728 ;; Now format the main section.
4729 (orgtbl-format-section nil)
4732 (when (plist-member params :tend)
4733 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4734 (if tend (push tend *orgtbl-rtn*)))))
4736 (mapconcat (if remove-newlines
4738 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4740 (nreverse (if remove-nil-linesp
4741 (remq nil *orgtbl-rtn*)
4742 *orgtbl-rtn*)) "\n")))
4745 (defun orgtbl-to-tsv (table params)
4746 "Convert the orgtbl-mode table to TAB separated material."
4747 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4749 (defun orgtbl-to-csv (table params)
4750 "Convert the orgtbl-mode table to CSV material.
4751 This does take care of the proper quoting of fields with comma or quotes."
4752 (orgtbl-to-generic table (org-combine-plists
4753 '(:sep "," :fmt org-quote-csv-field)
4757 (defun orgtbl-to-latex (table params)
4758 "Convert the orgtbl-mode TABLE to LaTeX.
4759 TABLE is a list, each entry either the symbol `hline' for a horizontal
4760 separator line, or a list of fields for that line.
4761 PARAMS is a property list of parameters that can influence the conversion.
4762 Supports all parameters from `orgtbl-to-generic'. Most important for
4765 :splice When set to t, return only table body lines, don't wrap
4766 them into a tabular environment. Default is nil.
4768 :fmt A format to be used to wrap the field, should contain %s for the
4769 original field value. For example, to wrap everything in dollars,
4770 use :fmt \"$%s$\". This may also be a property list with column
4771 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4772 The format may also be a function that formats its one argument.
4774 :efmt Format for transforming numbers with exponentials. The format
4775 should have %s twice for inserting mantissa and exponent, for
4776 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4777 This may also be a property list with column numbers and formats.
4778 The format may also be a function that formats its two arguments.
4780 :llend If you find too much space below the last line of a table,
4781 pass a value of \"\" for :llend to suppress the final \\\\.
4783 The general parameters :skip and :skipcols have already been applied when
4784 this function is called."
4785 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4786 org-table-last-alignment ""))
4789 :tstart (concat "\\begin{tabular}{" alignment "}")
4790 :tend "\\end{tabular}"
4791 :lstart "" :lend " \\\\" :sep " & "
4792 :efmt "%s\\,(%s)" :hline "\\hline")))
4793 (orgtbl-to-generic table (org-combine-plists params2 params))))
4796 (defun orgtbl-to-html (table params)
4797 "Convert the orgtbl-mode TABLE to HTML.
4798 TABLE is a list, each entry either the symbol `hline' for a horizontal
4799 separator line, or a list of fields for that line.
4800 PARAMS is a property list of parameters that can influence the conversion.
4801 Currently this function recognizes the following parameters:
4803 :splice When set to t, return only table body lines, don't wrap
4804 them into a <table> environment. Default is nil.
4806 The general parameters :skip and :skipcols have already been applied when
4807 this function is called. The function does *not* use `orgtbl-to-generic',
4808 so you cannot specify parameters for it."
4810 (let ((output (org-export-string-as
4811 (orgtbl-to-orgtbl table nil) 'html t '(:with-tables t))))
4812 (if (not (plist-get params :splice)) output
4814 (replace-regexp-in-string
4815 "\\`<table .*>\n" ""
4816 (replace-regexp-in-string "</table>\n*\\'" "" output))))))
4819 (defun orgtbl-to-texinfo (table params)
4820 "Convert the orgtbl-mode TABLE to TeXInfo.
4821 TABLE is a list, each entry either the symbol `hline' for a horizontal
4822 separator line, or a list of fields for that line.
4823 PARAMS is a property list of parameters that can influence the conversion.
4824 Supports all parameters from `orgtbl-to-generic'. Most important for
4827 :splice nil/t When set to t, return only table body lines, don't wrap
4828 them into a multitable environment. Default is nil.
4830 :fmt fmt A format to be used to wrap the field, should contain
4831 %s for the original field value. For example, to wrap
4832 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4833 This may also be a property list with column numbers and
4834 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4835 Each format also may be a function that formats its one
4838 :cf \"f1 f2..\" The column fractions for the table. By default these
4839 are computed automatically from the width of the columns
4842 The general parameters :skip and :skipcols have already been applied when
4843 this function is called."
4844 (let* ((total (float (apply '+ org-table-last-column-widths)))
4845 (colfrac (or (plist-get params :cf)
4847 (lambda (x) (format "%.3f" (/ (float x) total)))
4848 org-table-last-column-widths " ")))
4851 :tstart (concat "@multitable @columnfractions " colfrac)
4852 :tend "@end multitable"
4853 :lstart "@item " :lend "" :sep " @tab "
4854 :hlstart "@headitem ")))
4855 (orgtbl-to-generic table (org-combine-plists params2 params))))
4858 (defun orgtbl-to-orgtbl (table params)
4859 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4860 Useful when slicing one table into many. The :hline, :sep,
4861 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4862 and :tend suppress strings without splicing; they can be set to
4863 provide ORGTBL directives for the generated table."
4867 :tstart nil :tend nil
4872 (params (org-combine-plists params2 params)))
4874 (insert (orgtbl-to-generic table params))
4875 (goto-char (point-min))
4876 (while (re-search-forward org-table-hline-regexp nil t)
4878 (buffer-substring 1 (buffer-size)))))
4880 (defun orgtbl-to-table.el (table params)
4881 "Convert the orgtbl-mode TABLE into a table.el table."
4883 (insert (orgtbl-to-orgtbl table params))
4885 (replace-regexp-in-string
4887 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
4889 (defun orgtbl-to-unicode (table params)
4890 "Convert the orgtbl-mode TABLE into a table with unicode characters.
4891 You need the ascii-art-to-unicode.el package for this. You can download
4892 it here: http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el."
4894 (insert (orgtbl-to-table.el table params))
4895 (goto-char (point-min))
4896 (if (or (featurep 'ascii-art-to-unicode)
4897 (require 'ascii-art-to-unicode nil t))
4899 (unless (delq nil (mapcar (lambda (l) (string-match "aa2u" (car l))) org-stored-links))
4900 (push '("http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el"
4901 "Link to ascii-art-to-unicode.el") org-stored-links))
4902 (error "Please download ascii-art-to-unicode.el (use C-c C-l to insert the link to it)"))
4905 (defun org-table-get-remote-range (name-or-id form)
4906 "Get a field value or a list of values in a range from table at ID.
4908 NAME-OR-ID may be the name of a table in the current file as set by
4909 a \"#+TBLNAME:\" directive. The first table following this line
4910 will then be used. Alternatively, it may be an ID referring to
4911 any entry, also in a different file. In this case, the first table
4912 in that entry will be referenced.
4913 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
4914 \"@I$2..@II$2\". All the references must be absolute, not relative.
4916 The return value is either a single string for a single field, or a
4917 list of the fields in the rectangle ."
4919 (let ((case-fold-search t) (id-loc nil)
4920 ;; Protect a bunch of variables from being overwritten
4921 ;; by the context of the remote table
4922 org-table-column-names org-table-column-name-regexp
4923 org-table-local-parameters org-table-named-field-locations
4924 org-table-current-line-types org-table-current-begin-line
4925 org-table-current-begin-pos org-table-dlines
4926 org-table-current-ncol
4927 org-table-hlines org-table-last-alignment
4928 org-table-last-column-widths org-table-last-alignment
4929 org-table-last-column-widths tbeg
4931 (setq form (org-table-convert-refs-to-rc form))
4936 (goto-char (point-min))
4937 (if (re-search-forward
4938 (concat "^[ \t]*#\\+tblname:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4940 (setq buffer (current-buffer) loc (match-beginning 0))
4941 (setq id-loc (org-id-find name-or-id 'marker))
4942 (unless (and id-loc (markerp id-loc))
4943 (error "Can't find remote table \"%s\"" name-or-id))
4944 (setq buffer (marker-buffer id-loc)
4945 loc (marker-position id-loc))
4946 (move-marker id-loc nil)))
4947 (with-current-buffer buffer
4953 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4954 (not (match-beginning 1)))
4955 (error "Cannot find a table at NAME or ID %s" name-or-id))
4956 (setq tbeg (point-at-bol))
4957 (org-table-get-specials)
4958 (setq form (org-table-formula-substitute-names
4959 (org-table-formula-handle-first/last-rc form)))
4960 (if (and (string-match org-table-range-regexp form)
4961 (> (length (match-string 0 form)) 1))
4963 (org-table-get-range (match-string 0 form) tbeg 1))
4966 (defmacro org-define-lookup-function (mode)
4967 (let ((mode-str (symbol-name mode))
4968 (first-p (equal mode 'first))
4969 (all-p (equal mode 'all)))
4970 (let ((plural-str (if all-p "s" "")))
4971 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
4972 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
4973 If R-LIST is nil, return matching element%s of S-LIST.
4974 If PREDICATE is not nil, use it instead of `equal' to match VAL.
4975 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
4976 This function is generated by a call to the macro `org-define-lookup-function'."
4977 mode-str plural-str plural-str plural-str)
4978 (let ,(let ((lvars '((p (or predicate 'equal))
4980 (rl (or r-list s-list))
4982 (if first-p (add-to-list 'lvars '(match-p nil)))
4984 (while ,(if first-p '(and (not match-p) sl) 'sl)
4986 (if (funcall p val (car sl))
4988 ,(if first-p '(setq match-p t))
4989 (let ((rval (car rl)))
4990 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
4991 (setq sl (cdr sl) rl (cdr rl))))
4994 (org-define-lookup-function first)
4995 (org-define-lookup-function last)
4996 (org-define-lookup-function all)
4998 (provide 'org-table)
5001 ;; generated-autoload-file: "org-loaddefs.el"
5004 ;;; org-table.el ends here