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-table-clean-before-export
"org-exp"
42 (lines &optional maybe-quoted
))
43 (declare-function org-format-org-table-html
"org-html" (lines &optional splice
))
44 (declare-function aa2u
"ext:ascii-art-to-unicode" ())
45 (defvar orgtbl-mode
) ; defined below
46 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
47 (defvar org-export-html-table-tag
) ; defined in org-exp.el
48 (defvar constants-unit-system
)
49 (defvar org-table-follow-field-mode
)
51 (defvar orgtbl-after-send-table-hook nil
52 "Hook for functions attaching to `C-c C-c', if the table is sent.
53 This can be used to add additional functionality after the table is sent
54 to the receiver position, otherwise, if table is not sent, the functions
57 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
58 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
59 In the optimized version, the table editor takes over all simple keys that
60 normally just insert a character. In tables, the characters are inserted
61 in a way to minimize disturbing the table structure (i.e. in overwrite mode
62 for empty fields). Outside tables, the correct binding of the keys is
65 The default for this option is t if the optimized version is also used in
66 Org-mode. See the variable `org-enable-table-editor' for details. Changing
67 this variable requires a restart of Emacs to become effective."
71 (defcustom orgtbl-radio-table-templates
72 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
73 % END RECEIVE ORGTBL %n
75 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
78 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
79 @c END RECEIVE ORGTBL %n
81 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
84 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
85 <!-- END RECEIVE ORGTBL %n -->
87 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
90 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
91 #+ END RECEIVE ORGTBL %n
93 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
96 "Templates for radio tables in different major modes.
97 All occurrences of %n in a template will be replaced with the name of the
98 table, obtained by prompting the user."
101 (list (symbol :tag
"Major mode")
102 (string :tag
"Format"))))
104 (defgroup org-table-settings nil
105 "Settings for tables in Org-mode."
106 :tag
"Org Table Settings"
109 (defcustom org-table-default-size
"5x2"
110 "The default size for newly created tables, Columns x Rows."
111 :group
'org-table-settings
114 (defcustom org-table-number-regexp
115 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
116 "Regular expression for recognizing numbers in table columns.
117 If a table column contains mostly numbers, it will be aligned to the
118 right. If not, it will be aligned to the left.
120 The default value of this option is a regular expression which allows
121 anything which looks remotely like a number as used in scientific
122 context. For example, all of the following will be considered a
124 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
126 Other options offered by the customize interface are more restrictive."
127 :group
'org-table-settings
129 (const :tag
"Positive Integers"
131 (const :tag
"Integers"
133 (const :tag
"Floating Point Numbers"
134 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
135 (const :tag
"Floating Point Number or Integer"
136 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
137 (const :tag
"Exponential, Floating point, Integer"
138 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
139 (const :tag
"Very General Number-Like, including hex"
140 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
141 (const :tag
"Very General Number-Like, including hex, allows comma as decimal mark"
142 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
143 (string :tag
"Regexp:")))
145 (defcustom org-table-number-fraction
0.5
146 "Fraction of numbers in a column required to make the column align right.
147 In a column all non-white fields are considered. If at least
148 this fraction of fields is matched by `org-table-number-regexp',
149 alignment to the right border applies."
150 :group
'org-table-settings
153 (defgroup org-table-editing nil
154 "Behavior of tables during editing in Org-mode."
155 :tag
"Org Table Editing"
158 (defcustom org-table-automatic-realign t
159 "Non-nil means automatically re-align table when pressing TAB or RETURN.
160 When nil, aligning is only done with \\[org-table-align], or after column
162 :group
'org-table-editing
165 (defcustom org-table-auto-blank-field t
166 "Non-nil means automatically blank table field when starting to type into it.
167 This only happens when typing immediately after a field motion
168 command (TAB, S-TAB or RET).
169 Only relevant when `org-enable-table-editor' is equal to `optimized'."
170 :group
'org-table-editing
173 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
174 "Non-nil means automatically exit the follow mode.
175 When nil, the follow mode will stay on and be active in any table
176 the cursor enters. Since the table follow filed mode messes with the
177 window configuration, it is not recommended to set this variable to nil,
178 except maybe locally in a special file that has mostly tables with long
184 (defcustom org-table-fix-formulas-confirm nil
185 "Whether the user should confirm when Org fixes formulas."
186 :group
'org-table-editing
189 (const :tag
"with yes-or-no" yes-or-no-p
)
190 (const :tag
"with y-or-n" y-or-n-p
)
191 (const :tag
"no confirmation" nil
)))
192 (put 'org-table-fix-formulas-confirm
194 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
196 (defcustom org-table-tab-jumps-over-hlines t
197 "Non-nil means tab in the last column of a table with jump over a hline.
198 If a horizontal separator line is following the current line,
199 `org-table-next-field' can either create a new row before that line, or jump
200 over the line. When this option is nil, a new line will be created before
202 :group
'org-table-editing
205 (defgroup org-table-calculation nil
206 "Options concerning tables in Org-mode."
207 :tag
"Org Table Calculation"
210 (defcustom org-table-use-standard-references
'from
211 "Should org-mode work with table references like B3 instead of @3$2?
214 from accept as input, do not present for editing
215 t accept as input and present for editing"
216 :group
'org-table-calculation
218 (const :tag
"Never, don't even check user input for them" nil
)
219 (const :tag
"Always, both as user input, and when editing" t
)
220 (const :tag
"Convert user input, don't offer during editing" from
)))
222 (defcustom org-table-copy-increment t
223 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
224 :group
'org-table-calculation
227 (defcustom org-calc-default-modes
228 '(calc-internal-prec 12
229 calc-float-format
(float 8)
232 calc-symbolic-mode nil
233 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
234 calc-display-working-message t
236 "List with Calc mode settings for use in `calc-eval' for table formulas.
237 The list must contain alternating symbols (Calc modes variables and values).
238 Don't remove any of the default settings, just change the values. Org-mode
239 relies on the variables to be present in the list."
240 :group
'org-table-calculation
243 (defcustom org-table-duration-custom-format
'hours
244 "Format for the output of calc computations like $1+$2;t.
245 The default value is 'hours, and will output the results as a
246 number of hours. Other allowed values are 'seconds, 'minutes and
247 'days, and the output will be a fraction of seconds, minutes or
249 :group
'org-table-calculation
251 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
252 (symbol :tag
"Minutes" 'minutes
)
253 (symbol :tag
"Hours " 'hours
)
254 (symbol :tag
"Days " 'days
)))
256 (defcustom org-table-formula-field-format
"%s"
257 "Format for fields which contain the result of a formula.
258 For example, using \"~%s~\" will display the result within tilde
259 characters. Beware that modifying the display can prevent the
260 field from being used in another formula."
261 :group
'org-table-settings
265 (defcustom org-table-formula-evaluate-inline t
266 "Non-nil means TAB and RET evaluate a formula in current table field.
267 If the current field starts with an equal sign, it is assumed to be a formula
268 which should be evaluated as described in the manual and in the documentation
269 string of the command `org-table-eval-formula'. This feature requires the
271 When this variable is nil, formula calculation is only available through
272 the command \\[org-table-eval-formula]."
273 :group
'org-table-calculation
276 (defcustom org-table-formula-use-constants t
277 "Non-nil means interpret constants in formulas in tables.
278 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
279 by the value given in `org-table-formula-constants', or by a value obtained
280 from the `constants.el' package."
281 :group
'org-table-calculation
284 (defcustom org-table-formula-constants nil
285 "Alist with constant names and values, for use in table formulas.
286 The car of each element is a name of a constant, without the `$' before it.
287 The cdr is the value as a string. For example, if you'd like to use the
288 speed of light in a formula, you would configure
290 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
292 and then use it in an equation like `$1*$c'.
294 Constants can also be defined on a per-file basis using a line like
296 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
297 :group
'org-table-calculation
299 (cons (string :tag
"name")
300 (string :tag
"value"))))
302 (defcustom org-table-allow-automatic-line-recalculation t
303 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
304 Automatically means when TAB or RET or C-c C-c are pressed in the line."
305 :group
'org-table-calculation
308 (defcustom org-table-error-on-row-ref-crossing-hline t
309 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
313 (defcustom org-table-relative-ref-may-cross-hline t
314 "Non-nil means relative formula references may cross hlines.
315 Here are the allowed values:
317 nil Relative references may not cross hlines. They will reference the
318 field next to the hline instead. Coming from below, the reference
319 will be to the field below the hline. Coming from above, it will be
321 t Relative references may cross hlines.
322 error An attempt to cross a hline will throw an error.
324 It is probably good to never set this variable to nil, for the sake of
325 portability of tables."
326 :group
'org-table-calculation
328 (const :tag
"Allow to cross" t
)
329 (const :tag
"Stick to hline" nil
)
330 (const :tag
"Error on attempt to cross" error
)))
332 (defgroup org-table-import-export nil
333 "Options concerning table import and export in Org-mode."
334 :tag
"Org Table Import Export"
337 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
338 "Default export parameters for `org-table-export'.
339 These can be overridden for a specific table by setting the
340 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
341 radio tables for the different export transformations and
342 available parameters."
343 :group
'org-table-import-export
346 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
347 "Detects a table line marked for automatic recalculation.")
348 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
349 "Detects a table line marked for automatic recalculation.")
350 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
351 "Detects a table line marked for automatic recalculation.")
352 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
353 "Searching from within a table (any type) this finds the first line outside the table.")
354 (defvar org-table-last-highlighted-reference nil
)
355 (defvar org-table-formula-history nil
)
357 (defvar org-table-column-names nil
358 "Alist with column names, derived from the `!' line.")
359 (defvar org-table-column-name-regexp nil
360 "Regular expression matching the current column names.")
361 (defvar org-table-local-parameters nil
362 "Alist with parameter names, derived from the `$' line.")
363 (defvar org-table-named-field-locations nil
364 "Alist with locations of named fields.")
366 (defvar org-table-current-line-types nil
367 "Table row types, non-nil only for the duration of a command.")
368 (defvar org-table-current-begin-line nil
369 "Table begin line, non-nil only for the duration of a command.")
370 (defvar org-table-current-begin-pos nil
371 "Table begin position, non-nil only for the duration of a command.")
372 (defvar org-table-current-ncol nil
373 "Number of columns in table, non-nil only for the duration of a command.")
374 (defvar org-table-dlines nil
375 "Vector of data line line numbers in the current table.")
376 (defvar org-table-hlines nil
377 "Vector of hline line numbers in the current table.")
379 (defconst org-table-range-regexp
380 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
382 "Regular expression for matching ranges in formulas.")
384 (defconst org-table-range-regexp2
386 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
388 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
389 "Match a range for reference display.")
391 (defun org-table-colgroup-line-p (line)
392 "Is this a table line colgroup information?"
394 (and (string-match "[<>]\\|&[lg]t;" line
)
395 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
401 (not (member s
'("" "<" ">" "<>" "<" ">" "<>"))))
402 (org-split-string (match-string 1 line
) "[ \t]*|[ \t]*")))))))
404 (defun org-table-cookie-line-p (line)
405 "Is this a table line with only alignment/width cookies?"
407 (and (string-match "[<>]\\|&[lg]t;" line
)
409 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line
)
410 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line
))
411 (not (delq nil
(mapcar
413 (not (or (equal s
"")
415 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s
)
417 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'"
419 (org-split-string (match-string 1 line
)
420 "[ \t]*|[ \t]*")))))))
422 (defconst org-table-translate-regexp
423 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
424 "Match a reference that needs translation, for reference display.")
427 (defun org-table-create-with-table.el
()
428 "Use the table.el package to insert a new table.
429 If there is already a table at point, convert between Org-mode tables
430 and table.el tables."
435 (if (y-or-n-p "Convert table to Org-mode table? ")
436 (org-table-convert)))
438 (when (y-or-n-p "Convert table to table.el table? ")
440 (org-table-convert)))
441 (t (call-interactively 'table-insert
))))
444 (defun org-table-create-or-convert-from-region (arg)
445 "Convert region to table, or create an empty table.
446 If there is an active region, convert it to a table, using the function
447 `org-table-convert-region'. See the documentation of that function
448 to learn how the prefix argument is interpreted to determine the field
450 If there is no such region, create an empty table with `org-table-create'."
452 (if (org-region-active-p)
453 (org-table-convert-region (region-beginning) (region-end) arg
)
454 (org-table-create arg
)))
457 (defun org-table-create (&optional size
)
458 "Query for a size and insert a table skeleton.
459 SIZE is a string Columns x Rows like for example \"3x2\"."
462 (setq size
(read-string
463 (concat "Table size Columns x Rows [e.g. "
464 org-table-default-size
"]: ")
465 "" nil org-table-default-size
)))
468 (indent (make-string (current-column) ?\
))
469 (split (org-split-string size
" *x *"))
470 (rows (string-to-number (nth 1 split
)))
471 (columns (string-to-number (car split
)))
472 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
474 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
475 (point-at-bol) (point)))
476 (beginning-of-line 1)
478 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
479 (dotimes (i rows
) (insert line
))
482 ;; Insert a hline after the first row.
490 (defun org-table-convert-region (beg0 end0
&optional separator
)
491 "Convert region to a table.
492 The region goes from BEG0 to END0, but these borders will be moved
493 slightly, to make sure a beginning of line in the first line is included.
495 SEPARATOR specifies the field separator in the lines. It can have the
498 '(4) Use the comma as a field separator
499 '(16) Use a TAB as field separator
500 integer When a number, use that many spaces as field separator
501 nil When nil, the command tries to be smart and figure out the
502 separator in the following way:
503 - when each line contains a TAB, assume TAB-separated material
504 - when each line contains a comma, assume CSV material
505 - else, assume one or more SPACE characters as separator."
507 (let* ((beg (min beg0 end0
))
508 (end (max beg0 end0
))
511 (beginning-of-line 1)
512 (setq beg
(point-marker))
514 (if (bolp) (backward-char 1) (end-of-line 1))
515 (setq end
(point-marker))
516 ;; Get the right field separator
521 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
522 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
525 (if (equal separator
'(4))
526 (while (< (point) end
)
527 ;; parse the csv stuff
529 ((looking-at "^") (insert "| "))
530 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
531 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
532 (replace-match "\\1")
533 (if (looking-at "\"") (insert "\"")))
534 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
535 ((looking-at "[ \t]*,") (replace-match " | "))
536 (t (beginning-of-line 2))))
538 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
539 ((equal separator
'(16)) "^\\|\t")
540 ((integerp separator
)
542 (error "Number of spaces in separator must be >= 1")
543 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
544 (t (error "This should not happen"))))
545 (while (re-search-forward re end t
)
546 (replace-match "| " t t
)))
551 (defun org-table-import (file arg
)
552 "Import FILE as a table.
553 The file is assumed to be tab-separated. Such files can be produced by most
554 spreadsheet and database applications. If no tabs (at least one per line)
555 are found, lines will be split on whitespace into fields."
557 (or (bolp) (newline))
560 (insert-file-contents file
)
561 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
564 (defvar org-table-last-alignment
)
565 (defvar org-table-last-column-widths
)
567 (defun org-table-export (&optional file format
)
568 "Export table to a file, with configurable format.
569 Such a file can be imported into usual spreadsheet programs.
571 FILE can be the output file name. If not given, it will be taken
572 from a TABLE_EXPORT_FILE property in the current entry or higher
573 up in the hierarchy, or the user will be prompted for a file
574 name. FORMAT can be an export format, of the same kind as it
575 used when `orgtbl-mode' sends a table in a different format.
577 The command suggests a format depending on TABLE_EXPORT_FORMAT,
578 whether it is set locally or up in the hierarchy, then on the
579 extension of the given file name, and finally on the variable
580 `org-table-export-default-format'."
582 (unless (org-at-table-p)
583 (error "No table at point"))
585 (org-table-align) ;; make sure we have everything we need
586 (let* ((beg (org-table-begin))
587 (end (org-table-end))
588 (txt (buffer-substring-no-properties beg end
))
589 (file (or file
(org-entry-get beg
"TABLE_EXPORT_FILE" t
)))
590 (formats '("orgtbl-to-tsv" "orgtbl-to-csv"
591 "orgtbl-to-latex" "orgtbl-to-html"
592 "orgtbl-to-generic" "orgtbl-to-texinfo"
595 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)))
596 buf deffmt-readable fileext
)
598 (setq file
(read-file-name "Export table to: "))
599 (unless (or (not (file-exists-p file
))
600 (y-or-n-p (format "Overwrite file %s? " file
)))
602 (if (file-directory-p file
)
603 (error "This is a directory path, not a file"))
604 (if (and (buffer-file-name)
605 (equal (file-truename file
)
606 (file-truename (buffer-file-name))))
607 (error "Please specify a file name that is different from current"))
608 (setq fileext
(concat (file-name-extension file
) "$"))
610 (setq deffmt-readable
611 (or (car (delq nil
(mapcar (lambda(f) (if (string-match fileext f
) f
)) formats
)))
612 org-table-export-default-format
))
613 (while (string-match "\t" deffmt-readable
)
614 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
615 (while (string-match "\n" deffmt-readable
)
616 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
617 (setq format
(org-completing-read "Format: " formats nil nil deffmt-readable
)))
618 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
619 (let* ((transform (intern (match-string 1 format
)))
620 (params (if (match-end 2)
621 (read (concat "(" (match-string 2 format
) ")"))))
622 (skip (plist-get params
:skip
))
623 (skipcols (plist-get params
:skipcols
))
624 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
625 (lines (org-table-clean-before-export lines
))
626 (i0 (if org-table-clean-did-remove-column
2 1))
629 (if (string-match org-table-hline-regexp x
)
632 (org-split-string (org-trim x
) "\\s-*|\\s-*")
635 (fun (if (= i0
2) 'cdr
'identity
))
636 (org-table-last-alignment
637 (org-remove-by-index (funcall fun org-table-last-alignment
)
639 (org-table-last-column-widths
640 (org-remove-by-index (funcall fun org-table-last-column-widths
)
643 (unless (fboundp transform
)
644 (error "No such transformation function %s" transform
))
645 (setq txt
(funcall transform table params
))
647 (with-current-buffer (find-file-noselect file
)
648 (setq buf
(current-buffer))
654 (message "Export done."))
655 (error "TABLE_EXPORT_FORMAT invalid"))))
657 (defvar org-table-aligned-begin-marker
(make-marker)
658 "Marker at the beginning of the table last aligned.
659 Used to check if cursor still is in that table, to minimize realignment.")
660 (defvar org-table-aligned-end-marker
(make-marker)
661 "Marker at the end of the table last aligned.
662 Used to check if cursor still is in that table, to minimize realignment.")
663 (defvar org-table-last-alignment nil
664 "List of flags for flushright alignment, from the last re-alignment.
665 This is being used to correctly align a single field after TAB or RET.")
666 (defvar org-table-last-column-widths nil
667 "List of max width of fields in each column.
668 This is being used to correctly align a single field after TAB or RET.")
669 (defvar org-table-formula-debug nil
670 "Non-nil means debug table formulas.
671 When nil, simply write \"#ERROR\" in corrupted fields.")
672 (make-variable-buffer-local 'org-table-formula-debug
)
673 (defvar org-table-overlay-coordinates nil
674 "Overlay coordinates after each align of a table.")
675 (make-variable-buffer-local 'org-table-overlay-coordinates
)
677 (defvar org-last-recalc-line nil
)
678 (defvar org-table-do-narrow t
) ; for dynamic scoping
679 (defconst org-narrow-column-arrow
"=>"
680 "Used as display property in narrowed table columns.")
683 (defun org-table-align ()
684 "Align the table at point by aligning all vertical bars."
688 (beg (org-table-begin))
689 (end (org-table-end))
690 ;; Current cursor position
691 (linepos (org-current-line))
692 (colpos (org-table-current-column))
693 (winstart (window-start))
694 (winstartline (org-current-line (min winstart
(1- (point-max)))))
695 lines
(new "") lengths l typenums ty fields maxfields i
703 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
705 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
706 emptystrings links dates emph raise narrow
707 falign falign1 fmax f1 len c e space
)
709 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
710 ;; Check if we have links or dates
712 (setq links
(re-search-forward org-bracket-link-regexp end t
))
714 (setq emph
(and org-hide-emphasis-markers
715 (re-search-forward org-emph-re end t
)))
717 (setq raise
(and org-use-sub-superscripts
718 (re-search-forward org-match-substring-regexp end t
)))
720 (setq dates
(and org-display-custom-times
721 (re-search-forward org-ts-regexp-both end t
)))
722 ;; Make sure the link properties are right
723 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
724 ;; Make sure the date properties are right
725 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
726 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
727 (when raise
(goto-char beg
) (while (org-raise-scripts end
)))
729 ;; Check if we are narrowing any columns
731 (setq narrow
(and org-table-do-narrow
732 org-format-transports-properties-p
733 (re-search-forward "<[lrc]?[0-9]+>" end t
)))
735 (setq falign
(re-search-forward "<[lrc][0-9]*>" end t
))
738 (setq lines
(org-split-string
739 (buffer-substring beg end
) "\n"))
740 ;; Store the indentation of the first line
741 (if (string-match "^ *" (car lines
))
742 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
743 ;; Mark the hlines by setting the corresponding element to nil
744 ;; At the same time, we remove trailing space.
745 (setq lines
(mapcar (lambda (l)
746 (if (string-match "^ *|-" l
)
748 (if (string-match "[ \t]+$" l
)
749 (substring l
0 (match-beginning 0))
752 ;; Get the data fields by splitting the lines.
755 (org-split-string l
" *| *"))
756 (delq nil
(copy-sequence lines
))))
757 ;; How many fields in the longest line?
759 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
761 (kill-region beg end
)
762 (org-table-create org-table-default-size
)
763 (error "Empty table - created default table")))
764 ;; A list of empty strings to fill any short rows on output
765 (setq emptystrings
(make-list maxfields
""))
766 ;; Check for special formatting.
768 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
769 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
770 ;; Check if there is an explicit width specified
772 (when (or narrow falign
)
773 (setq c column fmax nil falign1 nil
)
776 (when (and (stringp e
) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e
))
777 (if (match-end 1) (setq falign1
(match-string 1 e
)))
778 (if (and org-table-do-narrow
(match-end 2))
779 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
780 ;; Find fields that are wider than fmax, and shorten them
782 (loop for xx in column do
783 (when (and (stringp xx
)
784 (> (org-string-width xx
) fmax
))
785 (org-add-props xx nil
787 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
788 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
790 (error "Cannot narrow field starting with wide link \"%s\""
791 (match-string 0 xx
)))
792 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
793 (add-text-properties (- f1
2) f1
794 (list 'display org-narrow-column-arrow
)
796 ;; Get the maximum width for each column
797 (push (apply 'max
(or fmax
1) 1 (mapcar 'org-string-width column
))
799 ;; Get the fraction of numbers, to decide about alignment of the column
801 (push (equal (downcase falign1
) "r") typenums
)
802 (setq cnt
0 frac
0.0)
803 (loop for x in column do
806 (setq frac
( / (+ (* frac cnt
)
807 (if (string-match org-table-number-regexp x
) 1 0))
808 (setq cnt
(1+ cnt
))))))
809 (push (>= frac org-table-number-fraction
) typenums
)))
810 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
812 ;; Store the alignment of this table, for later editing of single fields
813 (setq org-table-last-alignment typenums
814 org-table-last-column-widths lengths
)
816 ;; With invisible characters, `format' does not get the field width right
817 ;; So we need to make these fields wide by hand.
818 (when (or links emph raise
)
819 (loop for i from
0 upto
(1- maxfields
) do
820 (setq len
(nth i lengths
))
821 (loop for j from
0 upto
(1- (length fields
)) do
822 (setq c
(nthcdr i
(car (nthcdr j fields
))))
823 (if (and (stringp (car c
))
824 (or (text-property-any 0 (length (car c
))
825 'invisible
'org-link
(car c
))
826 (text-property-any 0 (length (car c
))
827 'org-dwidth t
(car c
)))
828 (< (org-string-width (car c
)) len
))
830 (setq space
(make-string (- len
(org-string-width (car c
))) ?\
))
831 (setcar c
(if (nth i typenums
)
832 (concat space
(car c
))
833 (concat (car c
) space
))))))))
835 ;; Compute the formats needed for output of the table
836 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
837 (while (setq l
(pop lengths
))
838 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
839 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
840 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
841 (setq rfmt
(concat rfmt
"\n")
842 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
846 (if l
(apply 'format rfmt
847 (append (pop fields
) emptystrings
))
850 (move-marker org-table-aligned-begin-marker
(point))
852 ;; Replace the old one
853 (delete-region (point) end
)
854 (move-marker end nil
)
855 (move-marker org-table-aligned-end-marker
(point))
856 (when (and orgtbl-mode
(not (derived-mode-p 'org-mode
)))
857 (goto-char org-table-aligned-begin-marker
)
858 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
859 ;; Try to move to the old location
860 (org-goto-line winstartline
)
861 (setq winstart
(point-at-bol))
862 (org-goto-line linepos
)
863 (set-window-start (selected-window) winstart
'noforce
)
864 (org-table-goto-column colpos
)
865 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
866 (setq org-table-may-need-update nil
)
869 (defun org-table-begin (&optional table-type
)
870 "Find the beginning of the table and return its position.
871 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
873 (if (not (re-search-backward
874 (if table-type org-table-any-border-regexp
875 org-table-border-regexp
)
877 (progn (goto-char (point-min)) (point))
878 (goto-char (match-beginning 0))
879 (beginning-of-line 2)
882 (defun org-table-end (&optional table-type
)
883 "Find the end of the table and return its position.
884 With argument TABLE-TYPE, go to the end of a table.el-type table."
886 (if (not (re-search-forward
887 (if table-type org-table-any-border-regexp
888 org-table-border-regexp
)
890 (goto-char (point-max))
891 (goto-char (match-beginning 0)))
895 (defun org-table-justify-field-maybe (&optional new
)
896 "Justify the current field, text to left, number to right.
897 Optional argument NEW may specify text to replace the current field content."
899 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
900 ((org-at-table-hline-p))
902 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
904 (< (point) org-table-aligned-begin-marker
)
905 (>= (point) org-table-aligned-end-marker
)))
906 ;; This is not the same table, force a full re-align
907 (setq org-table-may-need-update t
))
908 (t ;; realign the current field, based on previous full realign
909 (let* ((pos (point)) s
910 (col (org-table-current-column))
911 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
914 (skip-chars-backward "^|\n")
915 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
917 (setq s
(match-string 1)
919 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
920 e
(not (= (match-beginning 2) (match-end 2))))
921 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
922 l
(if e
"|" (setq org-table-may-need-update t
) ""))
925 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
926 (setq n
(format f new
))
927 (setq n
(concat new
"|") org-table-may-need-update t
)))
928 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
930 (let (org-table-may-need-update)
931 (replace-match n t t
))))
932 (setq org-table-may-need-update t
))
936 (defun org-table-next-field ()
937 "Go to the next field in the current table, creating new lines as needed.
938 Before doing so, re-align the table if necessary."
940 (org-table-maybe-eval-formula)
941 (org-table-maybe-recalculate-line)
942 (if (and org-table-automatic-realign
943 org-table-may-need-update
)
945 (let ((end (org-table-end)))
946 (if (org-at-table-hline-p)
950 (re-search-forward "|" end
)
951 (if (looking-at "[ \t]*$")
952 (re-search-forward "|" end
))
953 (if (and (looking-at "-")
954 org-table-tab-jumps-over-hlines
955 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
956 (goto-char (match-beginning 1)))
959 (beginning-of-line 0)
960 (org-table-insert-row 'below
))
961 (if (looking-at " ") (forward-char 1))))
963 (org-table-insert-row 'below
)))))
966 (defun org-table-previous-field ()
967 "Go to the previous field in the table.
968 Before doing so, re-align the table if necessary."
970 (org-table-justify-field-maybe)
971 (org-table-maybe-recalculate-line)
972 (if (and org-table-automatic-realign
973 org-table-may-need-update
)
975 (if (org-at-table-hline-p)
979 (re-search-backward "|" (org-table-begin))
980 (re-search-backward "|" (org-table-begin)))
981 (error (error "Cannot move to previous table field")))
982 (while (looking-at "|\\(-\\|[ \t]*$\\)")
983 (re-search-backward "|" (org-table-begin)))
984 (if (looking-at "| ?")
985 (goto-char (match-end 0))))
987 (defun org-table-beginning-of-field (&optional n
)
988 "Move to the end of the current table field.
989 If already at or after the end, move to the end of the next table field.
990 With numeric argument N, move N-1 fields forward first."
995 (org-table-previous-field))
996 (if (not (re-search-backward "|" (point-at-bol 0) t
))
997 (error "No more table fields before the current")
998 (goto-char (match-end 0))
999 (and (looking-at " ") (forward-char 1)))
1000 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1002 (defun org-table-end-of-field (&optional n
)
1003 "Move to the beginning of the current table field.
1004 If already at or before the beginning, move to the beginning of the
1006 With numeric argument N, move N-1 fields backward first."
1008 (let ((pos (point)))
1011 (org-table-next-field))
1012 (when (re-search-forward "|" (point-at-eol 1) t
)
1014 (skip-chars-backward " ")
1015 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1017 (if (<= (point) pos
) (org-table-end-of-field 2))))
1020 (defun org-table-next-row ()
1021 "Go to the next row (same column) in the current table.
1022 Before doing so, re-align the table if necessary."
1024 (org-table-maybe-eval-formula)
1025 (org-table-maybe-recalculate-line)
1026 (if (or (looking-at "[ \t]*$")
1027 (save-excursion (skip-chars-backward " \t") (bolp)))
1029 (if (and org-table-automatic-realign
1030 org-table-may-need-update
)
1032 (let ((col (org-table-current-column)))
1033 (beginning-of-line 2)
1034 (if (or (not (org-at-table-p))
1035 (org-at-table-hline-p))
1037 (beginning-of-line 0)
1038 (org-table-insert-row 'below
)))
1039 (org-table-goto-column col
)
1040 (skip-chars-backward "^|\n\r")
1041 (if (looking-at " ") (forward-char 1)))))
1044 (defun org-table-copy-down (n)
1045 "Copy a field down in the current column.
1046 If the field at the cursor is empty, copy into it the content of
1047 the nearest non-empty field above. With argument N, use the Nth
1048 non-empty field. If the current field is not empty, it is copied
1049 down to the next row, and the cursor is moved with it.
1050 Therefore, repeating this command causes the column to be filled
1052 If the variable `org-table-copy-increment' is non-nil and the
1053 field is an integer or a timestamp, it will be incremented while
1054 copying. In the case of a timestamp, increment by one day."
1056 (let* ((colpos (org-table-current-column))
1057 (col (current-column))
1058 (field (org-table-get-field))
1059 (non-empty (string-match "[^ \t]" field
))
1060 (beg (org-table-begin))
1063 (org-table-check-inside-data-field)
1066 (setq txt
(org-trim field
))
1067 (org-table-next-row)
1068 (org-table-blank-field))
1072 (while (progn (beginning-of-line 1)
1073 (re-search-backward org-table-dataline-regexp
1075 (org-table-goto-column colpos t
)
1076 (if (and (looking-at
1077 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1078 (<= (setq n
(1- n
)) 0))
1079 (throw 'exit
(match-string 1))))))))
1082 (if (and org-table-copy-increment
1083 (not (equal orig-n
0))
1084 (string-match "^[0-9]+$" txt
)
1085 (< (string-to-number txt
) 100000000))
1086 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
1088 (org-move-to-column col
)
1089 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1090 (org-timestamp-up-day)
1091 (org-table-maybe-recalculate-line))
1093 (org-move-to-column col
))
1094 (error "No non-empty field found"))))
1096 (defun org-table-check-inside-data-field (&optional noerror
)
1097 "Is point inside a table data field?
1098 I.e. not on a hline or before the first or after the last column?
1099 This actually throws an error, so it aborts the current command."
1100 (if (or (not (org-at-table-p))
1101 (= (org-table-current-column) 0)
1102 (org-at-table-hline-p)
1103 (looking-at "[ \t]*$"))
1106 (error "Not in table data field"))
1109 (defvar org-table-clip nil
1110 "Clipboard for table regions.")
1112 (defun org-table-get (line column
)
1113 "Get the field in table line LINE, column COLUMN.
1114 If LINE is larger than the number of data lines in the table, the function
1115 returns nil. However, if COLUMN is too large, we will simply return an
1117 If LINE is nil, use the current line.
1118 If column is nil, use the current column."
1119 (setq column
(or column
(org-table-current-column)))
1121 (and (or (not line
) (org-table-goto-line line
))
1122 (org-trim (org-table-get-field column
)))))
1124 (defun org-table-put (line column value
&optional align
)
1125 "Put VALUE into line LINE, column COLUMN.
1126 When ALIGN is set, also realign the table."
1127 (setq column
(or column
(org-table-current-column)))
1128 (prog1 (save-excursion
1129 (and (or (not line
) (org-table-goto-line line
))
1130 (progn (org-table-goto-column column nil
'force
) t
)
1131 (org-table-get-field column value
)))
1132 (and align
(org-table-align))))
1134 (defun org-table-current-line ()
1135 "Return the index of the current data line."
1136 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1138 (goto-char (org-table-begin))
1139 (while (and (re-search-forward org-table-dataline-regexp end t
)
1141 (< (point-at-eol) pos
))))
1144 (defun org-table-goto-line (N)
1145 "Go to the Nth data line in the current table.
1146 Return t when the line exists, nil if it does not exist."
1147 (goto-char (org-table-begin))
1148 (let ((end (org-table-end)) (cnt 0))
1149 (while (and (re-search-forward org-table-dataline-regexp end t
)
1150 (< (setq cnt
(1+ cnt
)) N
)))
1153 (defun org-table-blank-field ()
1154 "Blank the current table field or active region."
1156 (org-table-check-inside-data-field)
1157 (if (and (org-called-interactively-p 'any
) (org-region-active-p))
1158 (let (org-table-clip)
1159 (org-table-cut-region (region-beginning) (region-end)))
1160 (skip-chars-backward "^|")
1162 (if (looking-at "|[^|\n]+")
1163 (let* ((pos (match-beginning 0))
1164 (match (match-string 0))
1165 (len (org-string-width match
)))
1166 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1167 (goto-char (+ 2 pos
))
1168 (substring match
1)))))
1170 (defun org-table-get-field (&optional n replace
)
1171 "Return the value of the field in column N of current row.
1172 N defaults to current field.
1173 If REPLACE is a string, replace field with this value. The return value
1174 is always the old value."
1175 (and n
(org-table-goto-column n
))
1176 (skip-chars-backward "^|\n")
1178 (if (looking-at "|[^|\r\n]*")
1179 (let* ((pos (match-beginning 0))
1180 (val (buffer-substring (1+ pos
) (match-end 0))))
1182 (replace-match (concat "|" (if (equal replace
"") " " replace
))
1184 (goto-char (min (point-at-eol) (+ 2 pos
)))
1186 (forward-char 1) ""))
1189 (defun org-table-field-info (arg)
1190 "Show info about the current field, and highlight any reference at point."
1192 (org-table-get-specials)
1194 (let* ((pos (point))
1195 (col (org-table-current-column))
1196 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1197 (name (car (rassoc (list (org-current-line) col
)
1198 org-table-named-field-locations
)))
1199 (eql (org-table-expand-lhs-ranges
1202 (cons (org-table-formula-handle-first/last-rc
1204 (org-table-get-stored-formulas))))
1205 (dline (org-table-current-dline))
1206 (ref (format "@%d$%d" dline col
))
1207 (ref1 (org-table-convert-refs-to-an ref
))
1208 (fequation (or (assoc name eql
) (assoc ref eql
)))
1209 (cequation (assoc (int-to-string col
) eql
))
1210 (eqn (or fequation cequation
)))
1211 (if (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))
1212 (setq eqn
(get-text-property 0 :orig-eqn
(car eqn
))))
1215 (org-table-show-reference 'local
)
1217 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1219 (if cname
(concat " or $" cname
) "")
1221 (if name
(concat " or $" name
) "")
1222 ;; FIXME: formula info not correct if special table line
1224 (concat ", formula: "
1225 (org-table-formula-to-user
1227 (if (string-match "^[$@]"(car eqn
)) "" "$")
1228 (car eqn
) "=" (cdr eqn
))))
1231 (defun org-table-current-column ()
1232 "Find out which column we are in."
1234 (if (org-called-interactively-p 'any
) (org-table-check-inside-data-field))
1236 (let ((cnt 0) (pos (point)))
1237 (beginning-of-line 1)
1238 (while (search-forward "|" pos t
)
1239 (setq cnt
(1+ cnt
)))
1240 (when (org-called-interactively-p 'interactive
)
1241 (message "In table column %d" cnt
))
1245 (defun org-table-current-dline ()
1246 "Find out what table data line we are in.
1247 Only data lines count for this."
1249 (when (org-called-interactively-p 'any
)
1250 (org-table-check-inside-data-field))
1252 (let ((cnt 0) (pos (point)))
1253 (goto-char (org-table-begin))
1254 (while (<= (point) pos
)
1255 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1256 (beginning-of-line 2))
1257 (when (org-called-interactively-p 'any
)
1258 (message "This is table line %d" cnt
))
1262 (defun org-table-goto-column (n &optional on-delim force
)
1263 "Move the cursor to the Nth column in the current table line.
1264 With optional argument ON-DELIM, stop with point before the left delimiter
1266 If there are less than N fields, just go to after the last delimiter.
1267 However, when FORCE is non-nil, create new columns if necessary."
1269 (beginning-of-line 1)
1271 (while (and (> (setq n
(1- n
)) -
1)
1272 (or (search-forward "|" (point-at-eol) t
)
1274 (progn (end-of-line 1)
1275 (skip-chars-backward "^|")
1278 (when (and force
(not (looking-at ".*|")))
1279 (save-excursion (end-of-line 1) (insert " | ")))
1282 (if (looking-at " ") (forward-char 1)))))
1285 (defun org-table-insert-column ()
1286 "Insert a new column into the table."
1288 (if (not (org-at-table-p))
1289 (error "Not at a table"))
1290 (org-table-find-dataline)
1291 (let* ((col (max 1 (org-table-current-column)))
1292 (beg (org-table-begin))
1293 (end (org-table-end))
1294 ;; Current cursor position
1295 (linepos (org-current-line))
1298 (while (< (point) end
)
1299 (if (org-at-table-hline-p)
1301 (org-table-goto-column col t
)
1303 (beginning-of-line 2))
1304 (move-marker end nil
)
1305 (org-goto-line linepos
)
1306 (org-table-goto-column colpos
)
1308 (when (or (not org-table-fix-formulas-confirm
)
1309 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1310 (org-table-fix-formulas "$" nil
(1- col
) 1)
1311 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1313 (defun org-table-find-dataline ()
1314 "Find a data line in the current table, which is needed for column commands."
1315 (if (and (org-at-table-p)
1316 (not (org-at-table-hline-p)))
1318 (let ((col (current-column))
1319 (end (org-table-end)))
1320 (org-move-to-column col
)
1321 (while (and (< (point) end
)
1322 (or (not (= (current-column) col
))
1323 (org-at-table-hline-p)))
1324 (beginning-of-line 2)
1325 (org-move-to-column col
))
1326 (if (and (org-at-table-p)
1327 (not (org-at-table-hline-p)))
1330 "Please position cursor in a data line for column operations")))))
1332 (defun org-table-line-to-dline (line &optional above
)
1333 "Turn a buffer line number into a data line number.
1334 If there is no data line in this line, return nil.
1335 If there is no matching dline (most likely te reference was a hline), the
1336 first dline below it is used. When ABOVE is non-nil, the one above is used."
1338 (let ((ll (length org-table-dlines
))
1344 (if (<= (aref org-table-dlines i
) line
)
1349 (if (>= (aref org-table-dlines i
) line
)
1355 (defun org-table-delete-column ()
1356 "Delete a column from the table."
1358 (if (not (org-at-table-p))
1359 (error "Not at a table"))
1360 (org-table-find-dataline)
1361 (org-table-check-inside-data-field)
1362 (let* ((col (org-table-current-column))
1363 (beg (org-table-begin))
1364 (end (org-table-end))
1365 ;; Current cursor position
1366 (linepos (org-current-line))
1369 (while (< (point) end
)
1370 (if (org-at-table-hline-p)
1372 (org-table-goto-column col t
)
1373 (and (looking-at "|[^|\n]+|")
1374 (replace-match "|")))
1375 (beginning-of-line 2))
1376 (move-marker end nil
)
1377 (org-goto-line linepos
)
1378 (org-table-goto-column colpos
)
1380 (when (or (not org-table-fix-formulas-confirm
)
1381 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1382 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1384 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1388 (defun org-table-move-column-right ()
1389 "Move column to the right."
1391 (org-table-move-column nil
))
1393 (defun org-table-move-column-left ()
1394 "Move column to the left."
1396 (org-table-move-column 'left
))
1399 (defun org-table-move-column (&optional left
)
1400 "Move the current column to the right. With arg LEFT, move to the left."
1402 (if (not (org-at-table-p))
1403 (error "Not at a table"))
1404 (org-table-find-dataline)
1405 (org-table-check-inside-data-field)
1406 (let* ((col (org-table-current-column))
1407 (col1 (if left
(1- col
) col
))
1408 (beg (org-table-begin))
1409 (end (org-table-end))
1410 ;; Current cursor position
1411 (linepos (org-current-line))
1412 (colpos (if left
(1- col
) (1+ col
))))
1413 (if (and left
(= col
1))
1414 (error "Cannot move column further left"))
1415 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1416 (error "Cannot move column further right"))
1418 (while (< (point) end
)
1419 (if (org-at-table-hline-p)
1421 (org-table-goto-column col1 t
)
1422 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1423 (replace-match "|\\2|\\1|")))
1424 (beginning-of-line 2))
1425 (move-marker end nil
)
1426 (org-goto-line linepos
)
1427 (org-table-goto-column colpos
)
1429 (when (or (not org-table-fix-formulas-confirm
)
1430 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1431 (org-table-fix-formulas
1432 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1433 (cons (number-to-string colpos
) (number-to-string col
))))
1434 (org-table-fix-formulas
1435 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1436 (cons (number-to-string colpos
) (number-to-string col
)))))))
1439 (defun org-table-move-row-down ()
1440 "Move table row down."
1442 (org-table-move-row nil
))
1444 (defun org-table-move-row-up ()
1445 "Move table row up."
1447 (org-table-move-row 'up
))
1450 (defun org-table-move-row (&optional up
)
1451 "Move the current table line down. With arg UP, move it up."
1453 (let* ((col (current-column))
1455 (hline1p (save-excursion (beginning-of-line 1)
1456 (looking-at org-table-hline-regexp
)))
1457 (dline1 (org-table-current-dline))
1458 (dline2 (+ dline1
(if up -
1 1)))
1461 (beginning-of-line tonew
)
1462 (unless (org-at-table-p)
1464 (error "Cannot move row further"))
1465 (setq hline2p
(looking-at org-table-hline-regexp
))
1467 (beginning-of-line 1)
1469 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1470 (delete-region (point) (1+ (point-at-eol)))
1471 (beginning-of-line tonew
)
1473 (beginning-of-line 0)
1474 (org-move-to-column col
)
1475 (unless (or hline1p hline2p
1476 (not (or (not org-table-fix-formulas-confirm
)
1477 (funcall org-table-fix-formulas-confirm
1478 "Fix formulas? "))))
1479 (org-table-fix-formulas
1480 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1481 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1484 (defun org-table-insert-row (&optional arg
)
1485 "Insert a new row above the current line into the table.
1486 With prefix ARG, insert below the current line."
1488 (if (not (org-at-table-p))
1489 (error "Not at a table"))
1490 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1491 (new (org-table-clean-line line
)))
1492 ;; Fix the first field if necessary
1493 (if (string-match "^[ \t]*| *[#$] *|" line
)
1494 (setq new
(replace-match (match-string 0 line
) t t new
)))
1495 (beginning-of-line (if arg
2 1))
1496 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1497 (beginning-of-line 0)
1498 (re-search-forward "| ?" (point-at-eol) t
)
1499 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1501 (when (or (not org-table-fix-formulas-confirm
)
1502 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1503 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1506 (defun org-table-insert-hline (&optional above
)
1507 "Insert a horizontal-line below the current line into the table.
1508 With prefix ABOVE, insert above the current line."
1510 (if (not (org-at-table-p))
1511 (error "Not at a table"))
1512 (when (eobp) (insert "\n") (backward-char 1))
1513 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1515 (let ((line (org-table-clean-line
1516 (buffer-substring (point-at-bol) (point-at-eol))))
1517 (col (current-column)))
1518 (while (string-match "|\\( +\\)|" line
)
1519 (setq line
(replace-match
1520 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1521 ?-
) "|") t t line
)))
1522 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1523 (beginning-of-line (if above
1 2))
1525 (beginning-of-line (if above
1 -
1))
1526 (org-move-to-column col
)
1527 (and org-table-overlay-coordinates
(org-table-align))))
1530 (defun org-table-hline-and-move (&optional same-column
)
1531 "Insert a hline and move to the row below that line."
1533 (let ((col (org-table-current-column)))
1534 (org-table-maybe-eval-formula)
1535 (org-table-maybe-recalculate-line)
1536 (org-table-insert-hline)
1538 (if (looking-at "\n[ \t]*|-")
1539 (progn (insert "\n|") (org-table-align))
1540 (org-table-next-field))
1541 (if same-column
(org-table-goto-column col
))))
1543 (defun org-table-clean-line (s)
1544 "Convert a table line S into a string with only \"|\" and space.
1545 In particular, this does handle wide and invisible characters."
1546 (if (string-match "^[ \t]*|-" s
)
1547 ;; It's a hline, just map the characters
1548 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1549 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1550 (setq s
(replace-match
1551 (concat "|" (make-string (org-string-width (match-string 1 s
))
1557 (defun org-table-kill-row ()
1558 "Delete the current row or horizontal line from the table."
1560 (if (not (org-at-table-p))
1561 (error "Not at a table"))
1562 (let ((col (current-column))
1563 (dline (org-table-current-dline)))
1564 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1565 (if (not (org-at-table-p)) (beginning-of-line 0))
1566 (org-move-to-column col
)
1567 (when (or (not org-table-fix-formulas-confirm
)
1568 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1569 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1573 (defun org-table-sort-lines (with-case &optional sorting-type
)
1574 "Sort table lines according to the column at point.
1576 The position of point indicates the column to be used for
1577 sorting, and the range of lines is the range between the nearest
1578 horizontal separator lines, or the entire table of no such lines
1579 exist. If point is before the first column, you will be prompted
1580 for the sorting column. If there is an active region, the mark
1581 specifies the first line and the sorting column, while point
1582 should be in the last line to be included into the sorting.
1584 The command then prompts for the sorting type which can be
1585 alphabetically, numerically, or by time (as given in a time stamp
1586 in the field). Sorting in reverse order is also possible.
1588 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1590 If SORTING-TYPE is specified when this function is called from a Lisp
1591 program, no prompting will take place. SORTING-TYPE must be a character,
1592 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1593 should be done in reverse order."
1595 (let* ((thisline (org-current-line))
1596 (thiscol (org-table-current-column))
1597 (otc org-table-overlay-coordinates
)
1598 beg end bcol ecol tend tbeg column lns pos
)
1599 (when (equal thiscol
0)
1600 (if (org-called-interactively-p 'any
)
1603 (read-string "Use column N for sorting: ")))
1605 (org-table-goto-column thiscol
))
1606 (org-table-check-inside-data-field)
1607 (if (org-region-active-p)
1609 (setq beg
(region-beginning) end
(region-end))
1611 (setq column
(org-table-current-column)
1614 (setq end
(point-at-bol 2)))
1615 (setq column
(org-table-current-column)
1617 tbeg
(org-table-begin)
1618 tend
(org-table-end))
1619 (if (re-search-backward org-table-hline-regexp tbeg t
)
1620 (setq beg
(point-at-bol 2))
1622 (setq beg
(point-at-bol 1)))
1624 (if (re-search-forward org-table-hline-regexp tend t
)
1625 (setq end
(point-at-bol 1))
1627 (setq end
(point-at-bol))))
1628 (setq beg
(move-marker (make-marker) beg
)
1629 end
(move-marker (make-marker) end
))
1632 (org-table-goto-column column
)
1633 (skip-chars-backward "^|")
1634 (setq bcol
(current-column))
1635 (org-table-goto-column (1+ column
))
1636 (skip-chars-backward "^|")
1637 (setq ecol
(1- (current-column)))
1638 (org-table-goto-column column
)
1639 (setq lns
(mapcar (lambda(x) (cons
1640 (org-sort-remove-invisible
1642 (org-split-string x
"[ \t]*|[ \t]*")))
1644 (org-split-string (buffer-substring beg end
) "\n")))
1645 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1646 (when org-table-overlay-coordinates
1647 (org-table-toggle-coordinate-overlays))
1648 (delete-region beg end
)
1649 (move-marker beg nil
)
1650 (move-marker end nil
)
1651 (insert (mapconcat 'cdr lns
"\n") "\n")
1652 (org-goto-line thisline
)
1653 (org-table-goto-column thiscol
)
1654 (when otc
(org-table-toggle-coordinate-overlays))
1655 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1658 (defun org-table-cut-region (beg end
)
1659 "Copy region in table to the clipboard and blank all relevant fields.
1660 If there is no active region, use just the field at point."
1662 (if (org-region-active-p) (region-beginning) (point))
1663 (if (org-region-active-p) (region-end) (point))))
1664 (org-table-copy-region beg end
'cut
))
1667 (defun org-table-copy-region (beg end
&optional cut
)
1668 "Copy rectangular region in table to clipboard.
1669 A special clipboard is used which can only be accessed
1670 with `org-table-paste-rectangle'."
1672 (if (org-region-active-p) (region-beginning) (point))
1673 (if (org-region-active-p) (region-end) (point))
1674 current-prefix-arg
))
1675 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1677 (rpl (if cut
" " nil
)))
1679 (org-table-check-inside-data-field)
1680 (setq l01
(org-current-line)
1681 c01
(org-table-current-column))
1683 (org-table-check-inside-data-field)
1684 (setq l02
(org-current-line)
1685 c02
(org-table-current-column))
1686 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1687 c1
(min c01 c02
) c2
(max c01 c02
))
1691 (if (> l1 l2
) (throw 'exit t
))
1693 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1694 (setq cols nil ic1 c1 ic2 c2
)
1695 (while (< ic1
(1+ ic2
))
1696 (push (org-table-get-field ic1 rpl
) cols
)
1697 (setq ic1
(1+ ic1
)))
1698 (push (nreverse cols
) region
)
1699 (setq l1
(1+ l1
)))))
1700 (setq org-table-clip
(nreverse region
))
1701 (if cut
(org-table-align))
1705 (defun org-table-paste-rectangle ()
1706 "Paste a rectangular region into a table.
1707 The upper right corner ends up in the current field. All involved fields
1708 will be overwritten. If the rectangle does not fit into the present table,
1709 the table is enlarged as needed. The process ignores horizontal separator
1712 (unless (and org-table-clip
(listp org-table-clip
))
1713 (error "First cut/copy a region to paste!"))
1714 (org-table-check-inside-data-field)
1715 (let* ((clip org-table-clip
)
1716 (line (org-current-line))
1717 (col (org-table-current-column))
1718 (org-enable-table-editor t
)
1719 (org-table-automatic-realign nil
)
1721 (while (setq cols
(pop clip
))
1722 (while (org-at-table-hline-p) (beginning-of-line 2))
1723 (if (not (org-at-table-p))
1724 (progn (end-of-line 0) (org-table-next-field)))
1726 (while (setq field
(pop cols
))
1727 (org-table-goto-column c nil
'force
)
1728 (org-table-get-field nil field
)
1730 (beginning-of-line 2))
1731 (org-goto-line line
)
1732 (org-table-goto-column col
)
1736 (defun org-table-convert ()
1737 "Convert from `org-mode' table to table.el and back.
1738 Obviously, this only works within limits. When an Org-mode table is
1739 converted to table.el, all horizontal separator lines get lost, because
1740 table.el uses these as cell boundaries and has no notion of horizontal lines.
1741 A table.el table can be converted to an Org-mode table only if it does not
1742 do row or column spanning. Multiline cells will become multiple cells.
1743 Beware, Org-mode does not test if the table can be successfully converted - it
1744 blindly applies a recipe that works for simple tables."
1747 (if (org-at-table.el-p
)
1748 ;; convert to Org-mode table
1749 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1750 (end (move-marker (make-marker) (org-table-end t
))))
1751 (table-unrecognize-region beg end
)
1753 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1756 (if (org-at-table-p)
1757 ;; convert to table.el table
1758 (let ((beg (move-marker (make-marker) (org-table-begin)))
1759 (end (move-marker (make-marker) (org-table-end))))
1760 ;; first, get rid of all horizontal lines
1762 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1764 ;; insert a hline before first
1766 (org-table-insert-hline 'above
)
1767 (beginning-of-line -
1)
1768 ;; insert a hline after each line
1769 (while (progn (beginning-of-line 3) (< (point) end
))
1770 (org-table-insert-hline))
1772 (setq end
(move-marker end
(org-table-end)))
1773 ;; replace "+" at beginning and ending of hlines
1774 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1775 (replace-match "\\1+-"))
1777 (while (re-search-forward "-|[ \t]*$" end t
)
1778 (replace-match "-+"))
1781 (defun org-table-transpose-table-at-point ()
1782 "Transpose orgmode table at point and eliminate hlines.
1790 will be transposed as
1797 Note that horizontal lines disappeared."
1800 (apply #'mapcar
* #'list
1801 ;; remove 'hline from list
1802 (delq nil
(mapcar (lambda (x) (when (listp x
) x
))
1803 (org-table-to-lisp))))))
1804 (delete-region (org-table-begin) (org-table-end))
1805 (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1810 (defun org-table-wrap-region (arg)
1811 "Wrap several fields in a column like a paragraph.
1812 This is useful if you'd like to spread the contents of a field over several
1813 lines, in order to keep the table compact.
1815 If there is an active region, and both point and mark are in the same column,
1816 the text in the column is wrapped to minimum width for the given number of
1817 lines. Generally, this makes the table more compact. A prefix ARG may be
1818 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1819 formats the selected text to two lines. If the region was longer than two
1820 lines, the remaining lines remain empty. A negative prefix argument reduces
1821 the current number of lines by that amount. The wrapped text is pasted back
1822 into the table. If you formatted it to more lines than it was before, fields
1823 further down in the table get overwritten - so you might need to make space in
1826 If there is no region, the current field is split at the cursor position and
1827 the text fragment to the right of the cursor is prepended to the field one
1830 If there is no region, but you specify a prefix ARG, the current field gets
1831 blank, and the content is appended to the field above."
1833 (org-table-check-inside-data-field)
1834 (if (org-region-active-p)
1835 ;; There is a region: fill as a paragraph
1836 (let* ((beg (region-beginning))
1837 (cline (save-excursion (goto-char beg
) (org-current-line)))
1838 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1840 (org-table-cut-region (region-beginning) (region-end))
1841 (if (> (length (car org-table-clip
)) 1)
1842 (error "Region must be limited to single column"))
1843 (setq nlines
(if arg
1845 (+ (length org-table-clip
) arg
)
1847 (length org-table-clip
)))
1848 (setq org-table-clip
1849 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1851 (org-goto-line cline
)
1852 (org-table-goto-column ccol
)
1853 (org-table-paste-rectangle))
1854 ;; No region, split the current field at point
1855 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1856 (skip-chars-forward "^\r\n|"))
1858 ;; combine with field above
1859 (let ((s (org-table-blank-field))
1860 (col (org-table-current-column)))
1861 (beginning-of-line 0)
1862 (while (org-at-table-hline-p) (beginning-of-line 0))
1863 (org-table-goto-column col
)
1864 (skip-chars-forward "^|")
1865 (skip-chars-backward " ")
1866 (insert " " (org-trim s
))
1869 (if (looking-at "\\([^|]+\\)+|")
1870 (let ((s (match-string 1)))
1871 (replace-match " |")
1872 (goto-char (match-beginning 0))
1873 (org-table-next-row)
1874 (insert (org-trim s
) " ")
1876 (org-table-next-row)))))
1878 (defvar org-field-marker nil
)
1881 (defun org-table-edit-field (arg)
1882 "Edit table field in a different window.
1883 This is mainly useful for fields that contain hidden parts.
1884 When called with a \\[universal-argument] prefix, just make the full field visible so that
1885 it can be edited in place."
1889 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
1891 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1892 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1893 (remove-text-properties b e
'(org-cwidth t invisible t
1894 display t intangible t
))
1895 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1896 (font-lock-fontify-block))))
1898 (let ((pos (point-marker))
1900 (if (eq org-table-use-standard-references t
)
1901 (concat (org-number-to-letters (org-table-current-column))
1902 (int-to-string (org-table-current-dline)))
1903 (concat "@" (int-to-string (org-table-current-dline))
1904 "$" (int-to-string (org-table-current-column)))))
1905 (field (org-table-get-field))
1906 (cw (current-window-configuration))
1909 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
1910 (when (and (local-variable-p 'org-field-marker
)
1911 (markerp org-field-marker
))
1912 (move-marker org-field-marker nil
))
1914 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
1915 (let ((org-inhibit-startup t
)) (org-mode))
1917 (setq truncate-lines nil
)
1919 (goto-char (setq p
(point-max)))
1920 (insert (org-trim field
))
1921 (remove-text-properties p
(point-max)
1922 '(invisible t org-cwidth t display t
1925 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1926 (org-set-local 'org-window-configuration cw
)
1927 (org-set-local 'org-field-marker pos
)
1928 (message "Edit and finish with C-c C-c")))))
1930 (defun org-table-finish-edit-field ()
1931 "Finish editing a table data field.
1932 Remove all newline characters, insert the result into the table, realign
1933 the table and kill the editing buffer."
1934 (let ((pos org-field-marker
)
1935 (cw org-window-configuration
)
1936 (cb (current-buffer))
1938 (goto-char (point-min))
1939 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1940 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1941 (replace-match " "))
1942 (setq text
(org-trim (buffer-string)))
1943 (set-window-configuration cw
)
1945 (select-window (get-buffer-window (marker-buffer pos
)))
1947 (move-marker pos nil
)
1948 (org-table-check-inside-data-field)
1949 (org-table-get-field nil text
)
1951 (message "New field value inserted")))
1953 (define-minor-mode org-table-follow-field-mode
1954 "Minor mode to make the table field editor window follow the cursor.
1955 When this mode is active, the field editor window will always show the
1956 current field. The mode exits automatically when the cursor leaves the
1957 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
1958 nil
" TblFollow" nil
1959 (if org-table-follow-field-mode
1960 (org-add-hook 'post-command-hook
'org-table-follow-fields-with-editor
1962 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
1963 (let* ((buf (get-buffer "*Org Table Edit Field*"))
1964 (win (and buf
(get-buffer-window buf
))))
1965 (when win
(delete-window win
))
1967 (with-current-buffer buf
1968 (move-marker org-field-marker nil
))
1969 (kill-buffer buf
)))))
1971 (defun org-table-follow-fields-with-editor ()
1972 (if (and org-table-exit-follow-field-mode-when-leaving-table
1973 (not (org-at-table-p)))
1974 ;; We have left the table, exit the follow mode
1975 (org-table-follow-field-mode -
1)
1976 (when (org-table-check-inside-data-field 'noerror
)
1977 (let ((win (selected-window)))
1978 (org-table-edit-field nil
)
1979 (org-fit-window-to-buffer)
1980 (select-window win
)))))
1982 (defvar org-timecnt
) ; dynamically scoped parameter
1985 (defun org-table-sum (&optional beg end nlast
)
1986 "Sum numbers in region of current table column.
1987 The result will be displayed in the echo area, and will be available
1988 as kill to be inserted with \\[yank].
1990 If there is an active region, it is interpreted as a rectangle and all
1991 numbers in that rectangle will be summed. If there is no active
1992 region and point is located in a table column, sum all numbers in that
1995 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1996 numbers are assumed to be times as well (in decimal hours) and the
1997 numbers are added as such.
1999 If NLAST is a number, only the NLAST fields will actually be summed."
2002 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2004 ((and beg end
)) ; beg and end given explicitly
2005 ((org-region-active-p)
2006 (setq beg
(region-beginning) end
(region-end)))
2008 (setq col
(org-table-current-column))
2009 (goto-char (org-table-begin))
2010 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2011 (error "No table data"))
2012 (org-table-goto-column col
)
2014 (goto-char (org-table-end))
2015 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2016 (error "No table data"))
2017 (org-table-goto-column col
)
2018 (setq end
(point))))
2019 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2020 (items1 (cond ((not nlast
) items
)
2021 ((>= nlast
(length items
)) items
)
2022 (t (setq items
(reverse items
))
2023 (setcdr (nthcdr (1- nlast
) items
) nil
)
2025 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2027 (res (apply '+ numbers
))
2028 (sres (if (= org-timecnt
0)
2029 (number-to-string res
)
2030 (setq diff
(* 3600 res
)
2031 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2032 m
(floor (/ diff
60)) diff
(mod diff
60)
2034 (format "%d:%02d:%02d" h m s
))))
2036 (if (org-called-interactively-p 'interactive
)
2038 (substitute-command-keys
2039 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2040 (length numbers
) sres
))))
2043 (defun org-table-get-number-for-summing (s)
2045 (if (string-match "^ *|? *" s
)
2046 (setq s
(replace-match "" nil nil s
)))
2047 (if (string-match " *|? *$" s
)
2048 (setq s
(replace-match "" nil nil s
)))
2049 (setq n
(string-to-number s
))
2051 ((and (string-match "0" s
)
2052 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2053 ((string-match "\\`[ \t]+\\'" s
) nil
)
2054 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2055 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2056 (m (string-to-number (or (match-string 2 s
) "0")))
2057 (s (string-to-number (or (match-string 4 s
) "0"))))
2058 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2059 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2063 (defun org-table-current-field-formula (&optional key noerror
)
2064 "Return the formula active for the current field.
2065 Assumes that specials are in place.
2066 If KEY is given, return the key to this formula.
2067 Otherwise return the formula preceded with \"=\" or \":=\"."
2068 (let* ((name (car (rassoc (list (org-current-line)
2069 (org-table-current-column))
2070 org-table-named-field-locations
)))
2071 (col (org-table-current-column))
2072 (scol (int-to-string col
))
2073 (ref (format "@%d$%d" (org-table-current-dline) col
))
2074 (stored-list (org-table-get-stored-formulas noerror
))
2075 (ass (or (assoc name stored-list
)
2076 (assoc ref stored-list
)
2077 (assoc scol stored-list
))))
2080 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
2083 (defun org-table-get-formula (&optional equation named
)
2084 "Read a formula from the minibuffer, offer stored formula as default.
2085 When NAMED is non-nil, look for a named equation."
2086 (let* ((stored-list (org-table-get-stored-formulas))
2087 (name (car (rassoc (list (org-current-line)
2088 (org-table-current-column))
2089 org-table-named-field-locations
)))
2090 (ref (format "@%d$%d" (org-table-current-dline)
2091 (org-table-current-column)))
2092 (refass (assoc ref stored-list
))
2093 (nameass (assoc name stored-list
))
2095 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
2098 (int-to-string (org-table-current-column))))
2099 (dummy (and (or nameass refass
) (not named
)
2100 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2102 (name (or name ref
))
2103 (org-table-may-need-update nil
)
2104 (stored (cdr (assoc scol stored-list
)))
2106 ((and stored equation
(string-match "^ *=? *$" equation
))
2110 (t (org-table-formula-from-user
2112 (org-table-formula-to-user
2113 (format "%s formula %s%s="
2114 (if named
"Field" "Column")
2115 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
2117 (if stored
(org-table-formula-to-user stored
) "")
2118 'org-table-formula-history
2121 (when (not (string-match "\\S-" eq
))
2123 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2124 (org-table-store-formulas stored-list
)
2125 (error "Formula removed"))
2126 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2127 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2128 (if (and name
(not named
))
2129 ;; We set the column equation, delete the named one.
2130 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2133 (setcdr (assoc scol stored-list
) eq
)
2134 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2135 (if (or mustsave
(not (equal stored eq
)))
2136 (org-table-store-formulas stored-list
))
2139 (defun org-table-store-formulas (alist)
2140 "Store the list of formulas below the current table."
2141 (setq alist
(sort alist
'org-table-formula-less-p
))
2142 (let ((case-fold-search t
))
2144 (goto-char (org-table-end))
2145 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2147 ;; don't overwrite TBLFM, we might use text properties to store stuff
2148 (goto-char (match-beginning 3))
2149 (delete-region (match-beginning 3) (match-end 0)))
2151 (insert (or (match-string 2) "#+TBLFM:")))
2153 (mapconcat (lambda (x)
2155 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2156 (car x
) "=" (cdr x
)))
2160 (defsubst org-table-formula-make-cmp-string
(a)
2161 (when (string-match "\\`$[<>]" a
)
2162 (let ((arrow (string-to-char (substring a
1))))
2163 ;; Fake a high number to make sure this is sorted at the end.
2164 (setq a
(org-table-formula-handle-first/last-rc a
))
2165 (setq a
(format "$%d" (+ 10000
2166 (if (= arrow ?
<) -
1000 0)
2167 (string-to-number (substring a
1)))))))
2169 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2173 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2175 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2177 (concat "@@" (match-string 5 a
))))))
2179 (defun org-table-formula-less-p (a b
)
2180 "Compare two formulas for sorting."
2181 (let ((as (org-table-formula-make-cmp-string (car a
)))
2182 (bs (org-table-formula-make-cmp-string (car b
))))
2183 (and as bs
(string< as bs
))))
2186 (defun org-table-get-stored-formulas (&optional noerror
)
2187 "Return an alist with the stored formulas directly after current table."
2188 (interactive) ;; FIXME interactive?
2189 (let ((case-fold-search t
) scol eq eq-alist strings string seen
)
2191 (goto-char (org-table-end))
2192 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2193 (setq strings
(org-split-string (org-match-string-no-properties 2)
2195 (while (setq string
(pop strings
))
2196 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2197 (setq scol
(if (match-end 2)
2198 (match-string 2 string
)
2199 (match-string 1 string
))
2200 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2201 (concat "$" scol
) scol
)
2202 eq
(match-string 3 string
)
2203 eq-alist
(cons (cons scol eq
) eq-alist
))
2204 (if (member scol seen
)
2207 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2210 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2211 (push scol seen
))))))
2212 (nreverse eq-alist
)))
2214 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2215 "Modify the equations after the table structure has been edited.
2216 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2217 For all numbers larger than LIMIT, shift them by DELTA."
2219 (goto-char (org-table-end))
2220 (when (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2221 (let ((msg "The formulas in #+TBLFM have been updated")
2222 (re (concat key
"\\([0-9]+\\)"))
2225 (if (or (equal key
"$") (equal key
"$LR"))
2226 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2227 (regexp-quote key
) remove
)
2228 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2231 (while (re-search-forward re2
(point-at-eol) t
)
2232 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2233 (if (equal (char-before (match-beginning 0)) ?.
)
2234 (error "Change makes TBLFM term %s invalid, use undo to recover"
2236 (replace-match "")))))
2237 (while (re-search-forward re
(point-at-eol) t
)
2238 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2239 (setq s
(match-string 1) n
(string-to-number s
))
2241 ((setq a
(assoc s replace
))
2242 (replace-match (concat key
(cdr a
)) t t
)
2244 ((and limit
(> n limit
))
2245 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2246 (message msg
)))))))))
2248 (defun org-table-get-specials ()
2249 "Get the column names and local parameters for this table."
2251 (let ((beg (org-table-begin)) (end (org-table-end))
2252 names name fields fields1 field cnt
2253 c v l line col types dlines hlines last-dline
)
2254 (setq org-table-column-names nil
2255 org-table-local-parameters nil
2256 org-table-named-field-locations nil
2257 org-table-current-begin-line nil
2258 org-table-current-begin-pos nil
2259 org-table-current-line-types nil
2260 org-table-current-ncol
0)
2262 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2263 (setq names
(org-split-string (match-string 1) " *| *")
2265 (while (setq name
(pop names
))
2267 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name
)
2268 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2269 (setq org-table-column-names
(nreverse org-table-column-names
))
2270 (setq org-table-column-name-regexp
2271 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2273 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2274 (setq fields
(org-split-string (match-string 1) " *| *"))
2275 (while (setq field
(pop fields
))
2276 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2277 (push (cons (match-string 1 field
) (match-string 2 field
))
2278 org-table-local-parameters
))))
2280 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2281 (setq c
(match-string 1)
2282 fields
(org-split-string (match-string 2) " *| *"))
2284 (beginning-of-line (if (equal c
"_") 2 0))
2285 (setq line
(org-current-line) col
1)
2286 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2287 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2288 (while (and fields1
(setq field
(pop fields
)))
2289 (setq v
(pop fields1
) col
(1+ col
))
2290 (when (and (stringp field
) (stringp v
)
2291 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field
))
2292 (push (cons field v
) org-table-local-parameters
)
2293 (push (list field line col
) org-table-named-field-locations
))))
2294 ;; Analyse the line types
2296 (setq org-table-current-begin-line
(org-current-line)
2297 org-table-current-begin-pos
(point)
2298 l org-table-current-begin-line
)
2299 (while (looking-at "[ \t]*|\\(-\\)?")
2300 (push (if (match-end 1) 'hline
'dline
) types
)
2301 (if (match-end 1) (push l hlines
) (push l dlines
))
2302 (beginning-of-line 2)
2304 (push 'hline types
) ;; add an imaginary extra hline to the end
2305 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2306 last-dline
(car dlines
)
2307 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2308 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2309 (org-goto-line last-dline
)
2310 (let* ((l last-dline
)
2311 (fields (org-split-string
2312 (buffer-substring (point-at-bol) (point-at-eol))
2314 (nfields (length fields
))
2316 (setq org-table-current-ncol nfields
)
2317 (loop for i from
1 to nfields do
2318 (push (list (format "LR%d" i
) l i
) al
)
2319 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2320 (setq org-table-named-field-locations
2321 (append org-table-named-field-locations al
))
2322 (setq org-table-local-parameters
2323 (append org-table-local-parameters al2
))))))
2326 (defun org-table-maybe-eval-formula ()
2327 "Check if the current field starts with \"=\" or \":=\".
2328 If yes, store the formula and apply it."
2329 ;; We already know we are in a table. Get field will only return a formula
2330 ;; when appropriate. It might return a separator line, but no problem.
2331 (when org-table-formula-evaluate-inline
2332 (let* ((field (org-trim (or (org-table-get-field) "")))
2334 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2335 (setq named
(equal (string-to-char field
) ?
:)
2336 eq
(match-string 1 field
))
2337 (if (or (fboundp 'calc-eval
)
2338 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2339 (org-table-eval-formula (if named
'(4) nil
)
2340 (org-table-formula-from-user eq
))
2341 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2343 (defvar org-recalc-commands nil
2344 "List of commands triggering the recalculation of a line.
2345 Will be filled automatically during use.")
2347 (defvar org-recalc-marks
2348 '((" " .
"Unmarked: no special line, no automatic recalculation")
2349 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2350 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2351 ("!" .
"Column name definition line. Reference in formula as $name.")
2352 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2353 ("_" .
"Names for values in row below this one.")
2354 ("^" .
"Names for values in row above this one.")))
2357 (defun org-table-rotate-recalc-marks (&optional newchar
)
2358 "Rotate the recalculation mark in the first column.
2359 If in any row, the first field is not consistent with a mark,
2360 insert a new column for the markers.
2361 When there is an active region, change all the lines in the region,
2362 after prompting for the marking character.
2363 After each change, a message will be displayed indicating the meaning
2366 (unless (org-at-table-p) (error "Not at a table"))
2367 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2368 (beg (org-table-begin))
2369 (end (org-table-end))
2370 (l (org-current-line))
2371 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2372 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2376 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2377 (col (org-table-current-column))
2378 (forcenew (car (assoc newchar org-recalc-marks
)))
2381 (message "Change region to what mark? Type # * ! $ or SPC: ")
2382 (setq newchar
(char-to-string (read-char-exclusive))
2383 forcenew
(car (assoc newchar org-recalc-marks
))))
2384 (if (and newchar
(not forcenew
))
2385 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2387 (if l1
(org-goto-line l1
))
2389 (beginning-of-line 1)
2390 (unless (looking-at org-table-dataline-regexp
)
2391 (error "Not at a table data line")))
2393 (org-table-goto-column 1)
2394 (org-table-insert-column)
2395 (org-table-goto-column (1+ col
)))
2396 (setq epos
(point-at-eol))
2398 (beginning-of-line 1)
2399 (org-table-get-field
2400 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2402 (setq new
(or forcenew
2403 (cadr (member (match-string 1) marks
))))
2409 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2410 (and (looking-at org-table-dataline-regexp
)
2411 (org-table-get-field 1 (concat " " new
" "))))
2412 (org-goto-line l1
)))
2413 (if (not (= epos
(point-at-eol))) (org-table-align))
2415 (and (org-called-interactively-p 'interactive
)
2416 (message "%s" (cdr (assoc new org-recalc-marks
))))))
2419 (defun org-table-maybe-recalculate-line ()
2420 "Recompute the current line if marked for it, and if we haven't just done it."
2422 (and org-table-allow-automatic-line-recalculation
2423 (not (and (memq last-command org-recalc-commands
)
2424 (equal org-last-recalc-line
(org-current-line))))
2425 (save-excursion (beginning-of-line 1)
2426 (looking-at org-table-auto-recalculate-regexp
))
2427 (org-table-recalculate) t
))
2429 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2430 (defsubst org-set-calc-mode
(var &optional value
)
2432 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2433 ("R" calc-angle-mode rad
)
2434 ("F" calc-prefer-frac t
)
2435 ("S" calc-symbolic-mode t
)))
2436 value
(nth 2 var
) var
(nth 1 var
)))
2437 (if (memq var org-tbl-calc-modes
)
2438 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2439 (cons var
(cons value org-tbl-calc-modes
)))
2443 (defun org-table-eval-formula (&optional arg equation
2444 suppress-align suppress-const
2445 suppress-store suppress-analysis
)
2446 "Replace the table field value at the cursor by the result of a calculation.
2448 This function makes use of Dave Gillespie's Calc package, in my view the
2449 most exciting program ever written for GNU Emacs. So you need to have Calc
2450 installed in order to use this function.
2452 In a table, this command replaces the value in the current field with the
2453 result of a formula. It also installs the formula as the \"current\" column
2454 formula, by storing it in a special line below the table. When called
2455 with a `C-u' prefix, the current field must be a named field, and the
2456 formula is installed as valid in only this specific field.
2458 When called with two `C-u' prefixes, insert the active equation
2459 for the field back into the current field, so that it can be
2460 edited there. This is useful in order to use \\[org-table-show-reference]
2461 to check the referenced fields.
2463 When called, the command first prompts for a formula, which is read in
2464 the minibuffer. Previously entered formulas are available through the
2465 history list, and the last used formula is offered as a default.
2466 These stored formulas are adapted correctly when moving, inserting, or
2467 deleting columns with the corresponding commands.
2469 The formula can be any algebraic expression understood by the Calc package.
2470 For details, see the Org-mode manual.
2472 This function can also be called from Lisp programs and offers
2473 additional arguments: EQUATION can be the formula to apply. If this
2474 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2475 used to speed-up recursive calls by by-passing unnecessary aligns.
2476 SUPPRESS-CONST suppresses the interpretation of constants in the
2477 formula, assuming that this has been done already outside the function.
2478 SUPPRESS-STORE means the formula should not be stored, either because
2479 it is already stored, or because it is a modified equation that should
2480 not overwrite the stored one."
2482 (org-table-check-inside-data-field)
2483 (or suppress-analysis
(org-table-get-specials))
2484 (if (equal arg
'(16))
2485 (let ((eq (org-table-current-field-formula)))
2486 (or eq
(error "No equation active for current field"))
2487 (org-table-get-field nil eq
)
2489 (setq org-table-may-need-update t
))
2491 (ndown (if (integerp arg
) arg
1))
2492 (org-table-automatic-realign nil
)
2493 (case-fold-search nil
)
2495 (formula (if (and equation suppress-store
)
2497 (org-table-get-formula equation
(equal arg
'(4)))))
2498 (n0 (org-table-current-column))
2499 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2500 (numbers nil
) ; was a variable, now fixed default
2502 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2503 duration duration-output-format
)
2504 ;; Parse the format string. Since we have a lot of modes, this is
2505 ;; a lot of work. However, I think calc still uses most of the time.
2506 (if (string-match ";" formula
)
2507 (let ((tmp (org-split-string formula
";")))
2508 (setq formula
(car tmp
)
2509 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2511 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2512 (setq c
(string-to-char (match-string 1 fmt
))
2513 n
(string-to-number (match-string 2 fmt
)))
2515 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2516 (setq org-tbl-calc-modes
2519 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2520 (?s . sci
) (?e . eng
))))
2522 (setq fmt
(replace-match "" t t fmt
)))
2523 (if (string-match "T" fmt
)
2524 (setq duration t numbers t
2525 duration-output-format nil
2526 fmt
(replace-match "" t t fmt
)))
2527 (if (string-match "t" fmt
)
2529 duration-output-format org-table-duration-custom-format
2531 fmt
(replace-match "" t t fmt
)))
2532 (if (string-match "N" fmt
)
2534 fmt
(replace-match "" t t fmt
)))
2535 (if (string-match "L" fmt
)
2537 fmt
(replace-match "" t t fmt
)))
2538 (if (string-match "E" fmt
)
2540 fmt
(replace-match "" t t fmt
)))
2541 (while (string-match "[DRFS]" fmt
)
2542 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2543 (setq fmt
(replace-match "" t t fmt
)))
2544 (unless (string-match "\\S-" fmt
)
2546 (if (and (not suppress-const
) org-table-formula-use-constants
)
2547 (setq formula
(org-table-formula-substitute-names formula
)))
2548 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2550 (setq fields
(org-split-string
2551 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2553 ;; replace fields with duration values if relevant
2556 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2559 (setq fields
(mapcar
2560 (lambda (x) (number-to-string (string-to-number x
)))
2562 (setq ndown
(1- ndown
))
2563 (setq form
(copy-sequence formula
)
2564 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2565 (if (and lispp literal
) (setq lispp
'literal
))
2567 ;; Insert row and column number of formula result field
2568 (while (string-match "[@$]#" form
)
2573 (if (equal (substring form
(match-beginning 0)
2574 (1+ (match-beginning 0)))
2576 (org-table-current-dline)
2577 (org-table-current-column))))
2580 ;; Check for old vertical references
2581 (setq form
(org-table-rewrite-old-row-references form
))
2582 ;; Insert remote references
2583 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2587 (org-table-make-reference
2588 (let ((rmtrng (org-table-get-remote-range
2589 (match-string 1 form
) (match-string 2 form
))))
2592 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2593 (org-table-time-string-to-seconds rmtrng
))
2595 keep-empty numbers lispp
))
2597 ;; Insert complex ranges
2598 (while (and (string-match org-table-range-regexp form
)
2599 (> (length (match-string 0 form
)) 1))
2600 (setq formrg
(save-match-data
2601 (org-table-get-range (match-string 0 form
) nil n0
)))
2604 (org-table-make-reference
2605 ;; possibly handle durations
2608 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2609 (org-table-time-string-to-seconds formrg
))
2611 keep-empty numbers lispp
)))
2612 (if (not (save-match-data
2613 (string-match (regexp-quote form
) formrpl
)))
2614 (setq form
(replace-match formrpl t t form
))
2615 (error "Spreadsheet error: invalid reference \"%s\"" form
)))
2616 ;; Insert simple ranges
2617 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2621 (org-table-make-reference
2623 fields
(string-to-number (match-string 1 form
))
2624 (string-to-number (match-string 2 form
)))
2625 keep-empty numbers lispp
))
2628 ;; Insert the references to fields in same row
2629 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2630 (setq n
(+ (string-to-number (match-string 1 form
))
2631 (if (match-end 2) n0
0))
2632 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
))
2633 (unless x
(error "Invalid field specifier \"%s\""
2634 (match-string 0 form
)))
2635 (setq form
(replace-match
2637 (org-table-make-reference x nil numbers lispp
))
2641 (setq ev
(condition-case nil
2642 (eval (eval (read form
)))
2644 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2645 ev
(if duration
(org-table-time-seconds-to-string
2646 (string-to-number ev
)
2647 duration-output-format
) ev
))
2648 (or (fboundp 'calc-eval
)
2649 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2650 ;; "Inactivate" time-stamps so that Calc can handle them
2651 (setq form
(replace-regexp-in-string org-ts-regexp3
"<\\1>" form
))
2652 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2654 (calc-eval (cons form org-tbl-calc-modes
) (if numbers
'num
)))
2655 ev
(if duration
(org-table-time-seconds-to-string
2656 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2657 (string-to-number (org-table-time-string-to-seconds ev
))
2658 (string-to-number ev
))
2659 duration-output-format
)
2662 (when org-table-formula-debug
2663 (with-output-to-temp-buffer "*Substitution History*"
2664 (princ (format "Substitution history of formula
2668 $1-> %s\n" orig formula form0 form
))
2670 (princ (format " %s^\nError: %s"
2671 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2672 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2674 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2675 (setq bw
(get-buffer-window "*Substitution History*"))
2676 (org-fit-window-to-buffer bw
)
2677 (unless (and (org-called-interactively-p 'any
) (not ndown
))
2678 (unless (let (inhibit-redisplay)
2679 (y-or-n-p "Debugging Formula. Continue to next? "))
2684 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2685 (org-table-justify-field-maybe
2686 (format org-table-formula-field-format
2687 (if fmt
(format fmt
(string-to-number ev
)) ev
)))
2688 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2689 (call-interactively 'org-return
)
2691 (and down
(org-table-maybe-recalculate-line))
2692 (or suppress-align
(and org-table-may-need-update
2693 (org-table-align))))))
2695 (defun org-table-put-field-property (prop value
)
2697 (put-text-property (progn (skip-chars-backward "^|") (point))
2698 (progn (skip-chars-forward "^|") (point))
2701 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2702 "Get a calc vector from a column, according to descriptor DESC.
2703 Optional arguments TBEG and COL can give the beginning of the table and
2704 the current column, to avoid unnecessary parsing.
2706 HIGHLIGHT means just highlight the range.
2708 When CORNERS-ONLY is set, only return the corners of the range as
2709 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2710 in the buffer and column1 and column2 are table column numbers."
2711 (if (not (equal (string-to-char desc
) ?
@))
2712 (setq desc
(concat "@" desc
)))
2714 (or tbeg
(setq tbeg
(org-table-begin)))
2715 (or col
(setq col
(org-table-current-column)))
2716 (let ((thisline (org-current-line))
2717 beg end c1 c2 r1 r2 rangep tmp
)
2718 (unless (string-match org-table-range-regexp desc
)
2719 (error "Invalid table range specifier `%s'" desc
))
2720 (setq rangep
(match-end 3)
2721 r1
(and (match-end 1) (match-string 1 desc
))
2722 r2
(and (match-end 4) (match-string 4 desc
))
2723 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2724 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2726 (and c1
(setq c1
(+ (string-to-number c1
)
2727 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2728 (and c2
(setq c2
(+ (string-to-number c2
)
2729 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2730 (if (equal r1
"") (setq r1 nil
))
2731 (if (equal r2
"") (setq r2 nil
))
2732 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2733 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2734 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2735 (if (not r1
) (setq r1 thisline
))
2736 (if (not r2
) (setq r2 thisline
))
2737 (if (or (not c1
) (= 0 c1
)) (setq c1 col
))
2738 (if (or (not c2
) (= 0 c2
)) (setq c2 col
))
2739 (if (and (not corners-only
)
2740 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2744 (while (not (looking-at org-table-dataline-regexp
))
2745 (beginning-of-line 2))
2746 (prog1 (org-trim (org-table-get-field c1
))
2747 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2748 ;; A range, return a vector
2749 ;; First sort the numbers to get a regular rectangle
2750 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2751 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2753 ;; Only return the corners of the range
2755 ;; Copy the range values into a list
2757 (while (not (looking-at org-table-dataline-regexp
))
2758 (beginning-of-line 2))
2759 (org-table-goto-column c1
)
2762 (while (not (looking-at org-table-dataline-regexp
))
2763 (beginning-of-line 0))
2764 (org-table-goto-column c2
)
2767 (org-table-highlight-rectangle
2768 beg
(progn (skip-chars-forward "^|\n") (point))))
2769 ;; return string representation of calc vector
2771 (apply 'append
(org-table-copy-region beg end
))))))))
2773 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2774 "Analyze descriptor DESC and retrieve the corresponding line number.
2775 The cursor is currently in line CLINE, the table begins in line BLINE,
2776 and TABLE is a vector with line types."
2777 (if (string-match "^[0-9]+$" desc
)
2778 (aref org-table-dlines
(string-to-number desc
))
2779 (setq cline
(or cline
(org-current-line))
2780 bline
(or bline org-table-current-begin-line
)
2781 table
(or table org-table-current-line-types
))
2783 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2785 (and (not (match-end 3)) (not (match-end 6)))
2786 (and (match-end 3) (match-end 6) (not (match-end 5))))
2787 (error "Invalid row descriptor `%s'" desc
))
2788 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2789 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2790 (odir (and (match-end 5) (match-string 5 desc
)))
2791 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2793 (rel (and (match-end 6)
2794 (or (and (match-end 1) (not (match-end 3)))
2796 (if (and hn
(not hdir
))
2799 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2800 (if (and (not hn
) on
(not odir
))
2801 (error "Should never happen");;(aref org-table-dlines on)
2802 (if (and hn
(> hn
0))
2803 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2804 nil hn cline desc
)))
2806 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2807 rel on cline desc
)))
2810 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2811 "FIXME: Needs more documentation."
2812 (let ((l (length table
)))
2814 (while (and (setq i
(+ i
(if backwards -
1 1)))
2816 (not (eq (aref table i
) type
))
2817 (if (and relative
(eq (aref table i
) 'hline
))
2819 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2820 ((eq org-table-relative-ref-may-cross-hline
'error
)
2821 (error "Row descriptor %s used in line %d crosses hline" desc cline
))
2822 (t (setq i
(- i
(if backwards -
1 1))
2827 (if (or (< i
0) (>= i l
))
2828 (error "Row descriptor %s used in line %d leads outside table"
2832 (defun org-table-rewrite-old-row-references (s)
2833 (if (string-match "&[-+0-9I]" s
)
2834 (error "Formula contains old &row reference, please rewrite using @-syntax")
2837 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2838 "Convert list ELEMENTS to something appropriate to insert into formula.
2839 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2840 NUMBERS indicates that everything should be converted to numbers.
2841 LISPP means to return something appropriate for a Lisp list."
2842 (if (stringp elements
) ; just a single val
2844 (if (eq lispp
'literal
)
2846 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2847 (if (equal elements
"") (setq elements
"0"))
2848 (if numbers
(setq elements
(number-to-string (string-to-number elements
))))
2849 (concat "(" elements
")"))
2853 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2855 (setq elements
(or elements
'("0")))
2859 (if (eq lispp
'literal
)
2861 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2863 (concat "[" (mapconcat
2865 (if numbers
(number-to-string (string-to-number x
)) x
))
2870 (defun org-table-recalculate (&optional all noalign
)
2871 "Recalculate the current table line by applying all stored formulas.
2872 With prefix arg ALL, do this for all lines in the table.
2873 With the prefix argument ALL is `(16)' \
2874 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2875 it is the symbol `iterate', recompute the table until it no longer changes.
2876 If NOALIGN is not nil, do not re-align the table after the computations
2877 are done. This is typically used internally to save time, if it is
2878 known that the table will be realigned a little later anyway."
2880 (or (memq this-command org-recalc-commands
)
2881 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2882 (unless (org-at-table-p) (error "Not at a table"))
2883 (if (or (eq all
'iterate
) (equal all
'(16)))
2885 (org-table-get-specials)
2886 (let* ((eqlist (sort (org-table-get-stored-formulas)
2887 (lambda (a b
) (string< (car a
) (car b
)))))
2888 (eqlist1 (copy-sequence eqlist
))
2889 (inhibit-redisplay (not debug-on-error
))
2890 (line-re org-table-dataline-regexp
)
2891 (thisline (org-current-line))
2892 (thiscol (org-table-current-column))
2894 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
2895 ;; Insert constants in all formulas
2898 (when (string-match "\\`$[<>]" (car x
))
2900 (setq x
(cons (substring
2901 (org-table-formula-handle-first/last-rc
2904 (if (assoc (car x
) eqlist1
)
2905 (error "\"%s=\" formula tries to overwrite existing formula for column %s"
2908 (org-table-formula-handle-first/last-rc
(car x
))
2909 (org-table-formula-substitute-names
2910 (org-table-formula-handle-first/last-rc
(cdr x
)))))
2912 ;; Split the equation list
2913 (while (setq eq
(pop eqlist
))
2914 (if (<= (string-to-char (car eq
)) ?
9)
2917 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
2918 ;; Expand ranges in lhs of formulas
2919 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
2921 ;; Get the correct line range to process
2924 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
2925 (goto-char (setq beg
(org-table-begin)))
2926 (if (re-search-forward org-table-calculate-mark-regexp end t
)
2927 ;; This is a table with marked lines, compute selected lines
2928 (setq line-re org-table-recalculate-regexp
)
2929 ;; Move forward to the first non-header line
2930 (if (and (re-search-forward org-table-dataline-regexp end t
)
2931 (re-search-forward org-table-hline-regexp end t
)
2932 (re-search-forward org-table-dataline-regexp end t
))
2933 (setq beg
(match-beginning 0))
2934 nil
))) ;; just leave beg where it is
2935 (setq beg
(point-at-bol)
2936 end
(move-marker (make-marker) (1+ (point-at-eol)))))
2938 (and all
(message "Re-applying formulas to full table..."))
2940 ;; First find the named fields, and mark them untouchable.
2941 ;; Also check if several field/range formulas try to set the same field.
2942 (remove-text-properties beg end
'(org-untouchable t
))
2943 (while (setq eq
(pop eqlname
))
2945 a
(assoc name org-table-named-field-locations
))
2947 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
2949 (when (member name1 seen-fields
)
2950 (error "Several field/range formulas try to set %s" name1
))
2951 (push name1 seen-fields
)
2954 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
2957 (aref org-table-dlines
2958 (string-to-number (match-string 1 name
)))
2959 (error (error "Invalid row number in %s"
2961 (string-to-number (match-string 2 name
)))))
2962 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
2963 (message "Re-applying formula to field: %s" name
)
2964 (org-goto-line (nth 1 a
))
2965 (org-table-goto-column (nth 2 a
))
2966 (push (append a
(list (cdr eq
))) eqlname1
)
2967 (org-table-put-field-property :org-untouchable t
)))
2968 (setq eqlname1
(nreverse eqlname1
))
2970 ;; Now evaluate the column formulas, but skip fields covered by
2973 (while (re-search-forward line-re end t
)
2974 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2975 ;; Unprotected line, recalculate
2976 (and all
(message "Re-applying formulas to full table...(line %d)"
2977 (setq cnt
(1+ cnt
))))
2978 (setq org-last-recalc-line
(org-current-line))
2980 (while (setq entry
(pop eql
))
2981 (org-goto-line org-last-recalc-line
)
2982 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
2983 (unless (get-text-property (point) :org-untouchable
)
2984 (org-table-eval-formula nil
(cdr entry
)
2985 'noalign
'nocst
'nostore
'noanalysis
)))))
2987 ;; Now evaluate the field formulas
2988 (while (setq eq
(pop eqlname1
))
2989 (message "Re-applying formula to field: %s" (car eq
))
2990 (org-goto-line (nth 1 eq
))
2991 (org-table-goto-column (nth 2 eq
))
2992 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
2993 'nostore
'noanalysis
))
2995 (org-goto-line thisline
)
2996 (org-table-goto-column thiscol
)
2997 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
2998 (or noalign
(and org-table-may-need-update
(org-table-align))
2999 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
3001 ;; back to initial position
3002 (message "Re-applying formulas...done")
3003 (org-goto-line thisline
)
3004 (org-table-goto-column thiscol
)
3005 (or noalign
(and org-table-may-need-update
(org-table-align))
3006 (and all
(message "Re-applying formulas...done"))))))
3009 (defun org-table-iterate (&optional arg
)
3010 "Recalculate the table until it does not change anymore.
3011 The maximum number of iterations is 10, but you can choose a different value
3012 with the prefix ARG."
3014 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3016 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3021 (org-table-recalculate 'all
)
3022 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3023 (if (not (string= lasttbl thistbl
))
3024 (setq lasttbl thistbl
)
3026 (message "Convergence after %d iterations" i
)
3027 (message "Table was already stable"))
3029 (error "No convergence after %d iterations" i
))))
3032 (defun org-table-recalculate-buffer-tables ()
3033 "Recalculate all tables in the current buffer."
3038 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
3041 (defun org-table-iterate-buffer-tables ()
3042 "Iterate all tables in the buffer, to converge inter-table dependencies."
3046 (checksum (md5 (buffer-string)))
3054 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
3055 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3057 (message "Convergence after %d iterations" (- imax i
))
3059 (setq checksum c1
)))
3060 (error "No convergence after %d iterations" imax
))))))
3062 (defun org-table-expand-lhs-ranges (equations)
3063 "Expand list of formulas.
3064 If some of the RHS in the formulas are ranges or a row reference, expand
3065 them to individual field equations for each field."
3066 (let (e res lhs rhs range r1 r2 c1 c2
)
3067 (while (setq e
(pop equations
))
3068 (setq lhs
(car e
) rhs
(cdr e
))
3070 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs
)
3071 ;; This just refers to one fixed field
3073 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs
)
3074 ;; This just refers to one fixed named field
3076 ((string-match "^@[0-9]+$" lhs
)
3077 (loop for ic from
1 to org-table-current-ncol do
3078 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
3079 (put-text-property 0 (length (caar res
))
3080 :orig-eqn e
(caar res
))))
3082 (setq range
(org-table-get-range lhs org-table-current-begin-pos
3084 (setq r1
(nth 0 range
) c1
(nth 1 range
)
3085 r2
(nth 2 range
) c2
(nth 3 range
))
3086 (setq r1
(org-table-line-to-dline r1
))
3087 (setq r2
(org-table-line-to-dline r2
'above
))
3088 (loop for ir from r1 to r2 do
3089 (loop for ic from c1 to c2 do
3090 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
3091 (put-text-property 0 (length (caar res
))
3092 :orig-eqn e
(caar res
)))))))
3095 (defun org-table-formula-handle-first/last-rc
(s)
3096 "Replace @<, @>, $<, $> with first/last row/column of the table.
3097 So @< and $< will always be replaced with @1 and $1, respectively.
3098 The advantage of these special markers are that structure editing of
3099 the table will not change them, while @1 and $1 will be modified
3100 when a line/row is swapped out of that privileged position. So for
3101 formulas that use a range of rows or columns, it may often be better
3102 to anchor the formula with \"I\" row markers, or to offset from the
3103 borders of the table using the @< @> $< $> makers."
3104 (let (n nmax len char
(start 0))
3105 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3108 (setq start
(match-end 3))
3109 (setq nmax
(if (equal (match-string 1 s
) "@")
3110 (1- (length org-table-dlines
))
3111 org-table-current-ncol
)
3112 len
(- (match-end 2) (match-beginning 2))
3113 char
(string-to-char (match-string 2 s
))
3117 (if (or (< n
1) (> n nmax
))
3118 (error "Reference \"%s\" in expression \"%s\" points outside table"
3119 (match-string 0 s
) s
))
3120 (setq start
(match-beginning 0))
3121 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3124 (defun org-table-formula-substitute-names (f)
3125 "Replace $const with values in string F."
3126 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
3127 ;; First, check for column names
3128 (while (setq start
(string-match org-table-column-name-regexp f start
))
3129 (setq start
(1+ start
))
3130 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
3131 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
3132 ;; Parameters and constants
3134 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
3136 (setq start
(match-end 2))
3137 (setq start
(1+ start
))
3138 (if (setq a
(save-match-data
3139 (org-table-get-constant (match-string 1 f
))))
3140 (setq f
(replace-match
3141 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
3142 (if org-table-formula-debug
3143 (put-text-property 0 (length f
) :orig-formula f1 f
))
3146 (defun org-table-get-constant (const)
3147 "Find the value for a parameter or constant in a formula.
3148 Parameters get priority."
3149 (or (cdr (assoc const org-table-local-parameters
))
3150 (cdr (assoc const org-table-formula-constants-local
))
3151 (cdr (assoc const org-table-formula-constants
))
3152 (and (fboundp 'constants-get
) (constants-get const
))
3153 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3154 (org-entry-get nil
(substring const
5) 'inherit
))
3157 (defvar org-table-fedit-map
3158 (let ((map (make-sparse-keymap)))
3159 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3160 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3161 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3162 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3163 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3164 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3165 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3166 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3167 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3168 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3169 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3170 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3171 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3172 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3173 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3174 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3175 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3176 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3177 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3178 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3181 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3183 ["Finish and Install" org-table-fedit-finish t
]
3184 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3185 ["Abort" org-table-fedit-abort t
]
3187 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3188 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3190 "Shift Reference at Point"
3191 ["Up" org-table-fedit-ref-up t
]
3192 ["Down" org-table-fedit-ref-down t
]
3193 ["Left" org-table-fedit-ref-left t
]
3194 ["Right" org-table-fedit-ref-right t
]
3196 "Change Test Row for Column Formulas"
3197 ["Up" org-table-fedit-line-up t
]
3198 ["Down" org-table-fedit-line-down t
]
3200 ["Scroll Table Window" org-table-fedit-scroll t
]
3201 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3202 ["Show Table Grid" org-table-fedit-toggle-coordinates
3203 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3204 org-table-overlay-coordinates
)]
3206 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3207 :style toggle
:selected org-table-buffer-is-an
]))
3212 (defun org-table-edit-formulas ()
3213 "Edit the formulas of the current table in a separate buffer."
3215 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+TBLFM")))
3216 (beginning-of-line 0))
3217 (unless (org-at-table-p) (error "Not at a table"))
3218 (org-table-get-specials)
3219 (let ((key (org-table-current-field-formula 'key
'noerror
))
3220 (eql (sort (org-table-get-stored-formulas 'noerror
)
3221 'org-table-formula-less-p
))
3222 (pos (point-marker))
3224 (wc (current-window-configuration))
3225 (sel-win (selected-window))
3226 (titles '((column .
"# Column Formulas\n")
3227 (field .
"# Field and Range Formulas\n")
3228 (named .
"# Named Field Formulas\n")))
3230 (org-switch-to-buffer-other-window "*Edit Formulas*")
3232 ;; Keep global-font-lock-mode from turning on font-lock-mode
3233 (let ((font-lock-global-modes '(not fundamental-mode
)))
3235 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
3236 (org-set-local 'org-pos pos
)
3237 (org-set-local 'org-window-configuration wc
)
3238 (org-set-local 'org-selected-window sel-win
)
3239 (use-local-map org-table-fedit-map
)
3240 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3241 (easy-menu-add org-table-fedit-menu
)
3242 (setq startline
(org-current-line))
3243 (while (setq entry
(pop eql
))
3245 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3246 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3247 ((string-match "^[0-9]" (car entry
)) 'column
)
3249 (when (setq title
(assq type titles
))
3250 (or (bobp) (insert "\n"))
3251 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3252 (setq titles
(remove title titles
)))
3253 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3254 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3255 (car entry
) " = " (cdr entry
) "\n"))
3256 (remove-text-properties 0 (length s
) '(face nil
) s
)
3258 (if (eq org-table-use-standard-references t
)
3259 (org-table-fedit-toggle-ref-type))
3260 (org-goto-line startline
)
3261 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3263 (defun org-table-fedit-post-command ()
3264 (when (not (memq this-command
'(lisp-complete-symbol)))
3265 (let ((win (selected-window)))
3268 (org-table-show-reference)
3270 (select-window win
)))))
3272 (defun org-table-formula-to-user (s)
3273 "Convert a formula from internal to user representation."
3274 (if (eq org-table-use-standard-references t
)
3275 (org-table-convert-refs-to-an s
)
3278 (defun org-table-formula-from-user (s)
3279 "Convert a formula from user to internal representation."
3280 (if org-table-use-standard-references
3281 (org-table-convert-refs-to-rc s
)
3284 (defun org-table-convert-refs-to-rc (s)
3285 "Convert spreadsheet references from A7 to @7$28.
3286 Works for single references, but also for entire formulas and even the
3289 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3292 ;; format match, just advance
3293 (setq start
(match-end 0)))
3294 ((and (> (match-beginning 0) 0)
3295 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3296 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3297 ;; 3.e5 or something like this.
3298 (setq start
(match-end 0)))
3299 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3300 ;; (member (match-string 1 s)
3301 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3303 ;; function name, just advance
3304 (setq start
(match-end 0)))
3306 (setq start
(match-beginning 0)
3308 (if (equal (match-string 2 s
) "&")
3309 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3311 (string-to-number (match-string 2 s
))
3312 (org-letters-to-number (match-string 1 s
))))
3316 (defun org-table-convert-refs-to-an (s)
3317 "Convert spreadsheet references from to @7$28 to AB7.
3318 Works for single references, but also for entire formulas and even the
3320 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3321 (setq s
(replace-match
3323 (org-number-to-letters
3324 (string-to-number (match-string 2 s
)))
3325 (string-to-number (match-string 1 s
)))
3327 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3328 (setq s
(replace-match (concat "\\1"
3329 (org-number-to-letters
3330 (string-to-number (match-string 2 s
))) "&")
3334 (defun org-letters-to-number (s)
3335 "Convert a base 26 number represented by letters into an integer.
3336 For example: AB -> 28."
3339 (while (> (length s
) 0)
3340 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3344 (defun org-number-to-letters (n)
3345 "Convert an integer into a base 26 number represented by letters.
3346 For example: 28 -> AB."
3349 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3353 (defun org-table-time-string-to-seconds (s)
3354 "Convert a time string into numerical duration in seconds.
3355 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3356 If S is a string representing a number, keep this number."
3359 (let (hour minus min sec res
)
3361 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3362 (setq minus
(< 0 (length (match-string 1 s
)))
3363 hour
(string-to-number (match-string 2 s
))
3364 min
(string-to-number (match-string 3 s
))
3365 sec
(string-to-number (match-string 4 s
)))
3367 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3368 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3369 ((and (not (string-match org-ts-regexp-both s
))
3370 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3371 (setq minus
(< 0 (length (match-string 1 s
)))
3372 hour
(string-to-number (match-string 2 s
))
3373 min
(string-to-number (match-string 3 s
)))
3375 (setq res
(- (+ (* hour
3600) (* min
60))))
3376 (setq res
(+ (* hour
3600) (* min
60)))))
3377 (t (setq res
(string-to-number s
))))
3378 (number-to-string res
))))
3380 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3381 "Convert a number of seconds to a time string.
3382 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3383 minutes or seconds."
3384 (let* ((secs0 (abs secs
))
3386 (cond ((eq output-format
'days
)
3387 (format "%.3f" (/ (float secs0
) 86400)))
3388 ((eq output-format
'hours
)
3389 (format "%.2f" (/ (float secs0
) 3600)))
3390 ((eq output-format
'minutes
)
3391 (format "%.1f" (/ (float secs0
) 60)))
3392 ((eq output-format
'seconds
)
3393 (format "%d" secs0
))
3394 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0
)))))
3395 (if (< secs
0) (concat "-" res
) res
)))
3397 (defun org-table-fedit-convert-buffer (function)
3398 "Convert all references in this buffer, using FUNCTION."
3399 (let ((line (org-current-line)))
3400 (goto-char (point-min))
3402 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3403 (delete-region (point) (point-at-eol))
3404 (or (eobp) (forward-char 1)))
3405 (org-goto-line line
)))
3407 (defun org-table-fedit-toggle-ref-type ()
3408 "Convert all references in the buffer from B3 to @3$2 and back."
3410 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3411 (org-table-fedit-convert-buffer
3412 (if org-table-buffer-is-an
3413 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3414 (message "Reference type switched to %s"
3415 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3417 (defun org-table-fedit-ref-up ()
3418 "Shift the reference at point one row/hline up."
3420 (org-table-fedit-shift-reference 'up
))
3421 (defun org-table-fedit-ref-down ()
3422 "Shift the reference at point one row/hline down."
3424 (org-table-fedit-shift-reference 'down
))
3425 (defun org-table-fedit-ref-left ()
3426 "Shift the reference at point one field to the left."
3428 (org-table-fedit-shift-reference 'left
))
3429 (defun org-table-fedit-ref-right ()
3430 "Shift the reference at point one field to the right."
3432 (org-table-fedit-shift-reference 'right
))
3434 (defun org-table-fedit-shift-reference (dir)
3436 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3437 (if (memq dir
'(left right
))
3438 (org-rematch-and-replace 1 (eq dir
'left
))
3439 (error "Cannot shift reference in this direction")))
3440 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3441 ;; A B3-like reference
3442 (if (memq dir
'(up down
))
3443 (org-rematch-and-replace 2 (eq dir
'up
))
3444 (org-rematch-and-replace 1 (eq dir
'left
))))
3446 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3447 ;; An internal reference
3448 (if (memq dir
'(up down
))
3449 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3450 (org-rematch-and-replace 5 (eq dir
'left
))))))
3452 (defun org-rematch-and-replace (n &optional decr hline
)
3453 "Re-match the group N, and replace it with the shifted reference."
3454 (or (match-end n
) (error "Cannot shift reference in this direction"))
3455 (goto-char (match-beginning n
))
3456 (and (looking-at (regexp-quote (match-string n
)))
3457 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3460 (defun org-table-shift-refpart (ref &optional decr hline
)
3461 "Shift a reference part REF.
3462 If DECR is set, decrease the references row/column, else increase.
3463 If HLINE is set, this may be a hline reference, it certainly is not
3464 a translation reference."
3466 (let* ((sign (string-match "^[-+]" ref
)) n
)
3468 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3470 ((and hline
(string-match "^I+" ref
))
3471 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3472 (setq n
(+ n
(if decr -
1 1)))
3473 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3475 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3477 (concat sign
(make-string n ?I
)))
3479 ((string-match "^[0-9]+" ref
)
3480 (setq n
(string-to-number (concat sign ref
)))
3481 (setq n
(+ n
(if decr -
1 1)))
3483 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3484 (number-to-string (max 1 n
))))
3486 ((string-match "^[a-zA-Z]+" ref
)
3487 (org-number-to-letters
3488 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3490 (t (error "Cannot shift reference"))))))
3492 (defun org-table-fedit-toggle-coordinates ()
3493 "Toggle the display of coordinates in the referenced table."
3495 (let ((pos (marker-position org-pos
)))
3496 (with-current-buffer (marker-buffer org-pos
)
3499 (org-table-toggle-coordinate-overlays)))))
3501 (defun org-table-fedit-finish (&optional arg
)
3502 "Parse the buffer for formula definitions and install them.
3503 With prefix ARG, apply the new formulas to the table."
3505 (org-table-remove-rectangle-highlight)
3506 (if org-table-use-standard-references
3508 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3509 (setq org-table-buffer-is-an nil
)))
3510 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3511 (goto-char (point-min))
3512 (while (re-search-forward
3513 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3515 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3516 form
(match-string 3))
3517 (setq form
(org-trim form
))
3518 (when (not (equal form
""))
3519 (while (string-match "[ \t]*\n[ \t]*" form
)
3520 (setq form
(replace-match " " t t form
)))
3521 (when (assoc var eql
)
3522 (error "Double formulas for %s" var
))
3523 (push (cons var form
) eql
)))
3525 (set-window-configuration org-window-configuration
)
3526 (select-window sel-win
)
3528 (unless (org-at-table-p)
3529 (error "Lost table position - cannot install formulas"))
3530 (org-table-store-formulas eql
)
3531 (move-marker pos nil
)
3532 (kill-buffer "*Edit Formulas*")
3534 (org-table-recalculate 'all
)
3535 (message "New formulas installed - press C-u C-c C-c to apply."))))
3537 (defun org-table-fedit-abort ()
3538 "Abort editing formulas, without installing the changes."
3540 (org-table-remove-rectangle-highlight)
3541 (let ((pos org-pos
) (sel-win org-selected-window
))
3542 (set-window-configuration org-window-configuration
)
3543 (select-window sel-win
)
3545 (move-marker pos nil
)
3546 (message "Formula editing aborted without installing changes")))
3548 (defun org-table-fedit-lisp-indent ()
3549 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3551 (let ((pos (point)) beg end ind
)
3552 (beginning-of-line 1)
3554 ((looking-at "[ \t]")
3556 (call-interactively 'lisp-indent-line
))
3557 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3558 ((not (fboundp 'pp-buffer
))
3559 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3560 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3561 (goto-char (- (match-end 0) 2))
3563 (setq ind
(make-string (current-column) ?\
))
3564 (condition-case nil
(forward-sexp 1)
3566 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3569 (narrow-to-region beg end
)
3570 (if (eq last-command this-command
)
3572 (goto-char (point-min))
3573 (setq this-command nil
)
3574 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3575 (replace-match " ")))
3577 (untabify (point-min) (point-max))
3578 (goto-char (1+ (point-min)))
3579 (while (re-search-forward "^." nil t
)
3580 (beginning-of-line 1)
3582 (goto-char (point-max))
3583 (org-delete-backward-char 1)))
3587 (defvar org-show-positions nil
)
3589 (defun org-table-show-reference (&optional local
)
3590 "Show the location/value of the $ expression at point."
3592 (org-table-remove-rectangle-highlight)
3594 (let ((pos (if local
(point) org-pos
))
3596 (org-inhibit-highlight-removal t
)
3597 (win (selected-window))
3598 (org-show-positions nil
)
3599 var name e what match dest
)
3600 (if local
(org-table-get-specials))
3602 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3603 (setq match
(concat (substring (match-string 0) 0 -
1)
3605 (substring (match-string 0) 0 -
1)
3608 ((or (org-at-regexp-p org-table-range-regexp2
)
3609 (org-at-regexp-p org-table-translate-regexp
)
3610 (org-at-regexp-p org-table-range-regexp
))
3613 (org-table-convert-refs-to-rc (match-string 0))))
3615 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3616 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3618 (t (error "No reference at point")))
3619 match
(and what
(or match
(match-string 0))))
3620 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3621 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3622 'secondary-selection
))
3623 (org-add-hook 'before-change-functions
3624 'org-table-remove-rectangle-highlight
)
3625 (if (eq what
'name
) (setq var
(substring match
1)))
3626 (when (eq what
'range
)
3627 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3628 (setq match
(org-table-formula-substitute-names match
)))
3632 (re-search-backward "^\\S-" nil t
)
3633 (beginning-of-line 1)
3634 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3637 (org-table-convert-refs-to-rc (match-string 1))))
3638 (org-table-add-rectangle-overlay
3639 (match-beginning 1) (match-end 1) face2
))))
3640 (if (and (markerp pos
) (marker-buffer pos
))
3641 (if (get-buffer-window (marker-buffer pos
))
3642 (select-window (get-buffer-window (marker-buffer pos
)))
3643 (org-switch-to-buffer-other-window (get-buffer-window
3644 (marker-buffer pos
)))))
3646 (org-table-force-dataline)
3648 (setq name
(substring dest
1))
3650 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3651 (setq e
(assoc name org-table-named-field-locations
))
3652 (org-goto-line (nth 1 e
))
3653 (org-table-goto-column (nth 2 e
)))
3654 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3655 (let ((l (string-to-number (match-string 1 dest
)))
3656 (c (string-to-number (match-string 2 dest
))))
3657 (org-goto-line (aref org-table-dlines l
))
3658 (org-table-goto-column c
)))
3659 (t (org-table-goto-column (string-to-number name
))))
3660 (move-marker pos
(point))
3661 (org-table-highlight-rectangle nil nil face2
))
3663 ((equal dest match
))
3668 (org-table-get-range match nil nil
'highlight
))
3670 ((setq e
(assoc var org-table-named-field-locations
))
3671 (org-goto-line (nth 1 e
))
3672 (org-table-goto-column (nth 2 e
))
3673 (org-table-highlight-rectangle (point) (point))
3674 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3675 ((setq e
(assoc var org-table-column-names
))
3676 (org-table-goto-column (string-to-number (cdr e
)))
3677 (org-table-highlight-rectangle (point) (point))
3678 (goto-char (org-table-begin))
3679 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3682 (goto-char (match-beginning 1))
3683 (org-table-highlight-rectangle)
3684 (message "Named column (column %s)" (cdr e
)))
3685 (error "Column name not found")))
3688 (org-table-goto-column (string-to-number (substring match
1)))
3689 (org-table-highlight-rectangle (point) (point))
3690 (message "Column %s" (substring match
1)))
3691 ((setq e
(assoc var org-table-local-parameters
))
3692 (goto-char (org-table-begin))
3693 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3695 (goto-char (match-beginning 1))
3696 (org-table-highlight-rectangle)
3697 (message "Local parameter."))
3698 (error "Parameter not found")))
3701 ((not var
) (error "No reference at point"))
3702 ((setq e
(assoc var org-table-formula-constants-local
))
3703 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3705 ((setq e
(assoc var org-table-formula-constants
))
3706 (message "Constant: $%s=%s in `org-table-formula-constants'."
3708 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3709 (message "Constant: $%s=%s, from `constants.el'%s."
3710 var e
(format " (%s units)" constants-unit-system
)))
3711 (t (error "Undefined name $%s" var
)))))
3713 (when (and org-show-positions
3714 (not (memq this-command
'(org-table-fedit-scroll
3715 org-table-fedit-scroll-down
))))
3716 (push pos org-show-positions
)
3717 (push org-table-current-begin-pos org-show-positions
)
3718 (let ((min (apply 'min org-show-positions
))
3719 (max (apply 'max org-show-positions
)))
3720 (goto-char min
) (recenter 0)
3722 (or (pos-visible-in-window-p max
) (recenter -
1))))
3723 (select-window win
))))
3725 (defun org-table-force-dataline ()
3726 "Make sure the cursor is in a dataline in a table."
3727 (unless (save-excursion
3728 (beginning-of-line 1)
3729 (looking-at org-table-dataline-regexp
))
3730 (let* ((re org-table-dataline-regexp
)
3731 (p1 (save-excursion (re-search-forward re nil
'move
)))
3732 (p2 (save-excursion (re-search-backward re nil
'move
))))
3734 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3736 ((or p1 p2
) (goto-char (or p1 p2
)))
3737 (t (error "No table dataline around here"))))))
3739 (defun org-table-fedit-line-up ()
3740 "Move cursor one line up in the window showing the table."
3742 (org-table-fedit-move 'previous-line
))
3744 (defun org-table-fedit-line-down ()
3745 "Move cursor one line down in the window showing the table."
3747 (org-table-fedit-move 'next-line
))
3749 (defun org-table-fedit-move (command)
3750 "Move the cursor in the window showing the table.
3751 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3752 (let ((org-table-allow-automatic-line-recalculation nil
)
3753 (pos org-pos
) (win (selected-window)) p
)
3754 (select-window (get-buffer-window (marker-buffer org-pos
)))
3756 (call-interactively command
)
3757 (while (and (org-at-table-p)
3758 (org-at-table-hline-p))
3759 (call-interactively command
))
3760 (or (org-at-table-p) (goto-char p
))
3761 (move-marker pos
(point))
3762 (select-window win
)))
3764 (defun org-table-fedit-scroll (N)
3766 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3767 (scroll-other-window N
)))
3769 (defun org-table-fedit-scroll-down (N)
3771 (org-table-fedit-scroll (- N
)))
3773 (defvar org-table-rectangle-overlays nil
)
3775 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3776 "Add a new overlay."
3777 (let ((ov (make-overlay beg end
)))
3778 (overlay-put ov
'face
(or face
'secondary-selection
))
3779 (push ov org-table-rectangle-overlays
)))
3781 (defun org-table-highlight-rectangle (&optional beg end face
)
3782 "Highlight rectangular region in a table."
3783 (setq beg
(or beg
(point)) end
(or end
(point)))
3784 (let ((b (min beg end
))
3787 (and (boundp 'org-show-positions
)
3788 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3789 (goto-char (min beg end
))
3790 (setq l1
(org-current-line)
3791 c1
(org-table-current-column))
3792 (goto-char (max beg end
))
3793 (setq l2
(org-current-line)
3794 c2
(org-table-current-column))
3795 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3797 (beginning-of-line 1)
3798 (loop for line from l1 to l2 do
3799 (when (looking-at org-table-dataline-regexp
)
3800 (org-table-goto-column c1
)
3801 (skip-chars-backward "^|\n") (setq beg
(point))
3802 (org-table-goto-column c2
)
3803 (skip-chars-forward "^|\n") (setq end
(point))
3804 (org-table-add-rectangle-overlay beg end face
))
3805 (beginning-of-line 2))
3807 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3809 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3810 "Remove the rectangle overlays."
3811 (unless org-inhibit-highlight-removal
3812 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3813 (mapc 'delete-overlay org-table-rectangle-overlays
)
3814 (setq org-table-rectangle-overlays nil
)))
3816 (defvar org-table-coordinate-overlays nil
3817 "Collects the coordinate grid overlays, so that they can be removed.")
3818 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3820 (defun org-table-overlay-coordinates ()
3821 "Add overlays to the table at point, to show row/column coordinates."
3823 (mapc 'delete-overlay org-table-coordinate-overlays
)
3824 (setq org-table-coordinate-overlays nil
)
3826 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3827 (goto-char (org-table-begin))
3828 (while (org-at-table-p)
3829 (setq eol
(point-at-eol))
3830 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
3831 (push ov org-table-coordinate-overlays
)
3832 (setq hline
(looking-at org-table-hline-regexp
))
3833 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3834 (format "%4d" (setq id
(1+ id
)))))
3835 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3838 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3839 (setq beg
(1+ (match-beginning 0))
3841 s1
(concat "$" (int-to-string ic
))
3842 s2
(org-number-to-letters ic
)
3843 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3844 (setq ov
(make-overlay beg
(+ beg
(length str
))))
3845 (push ov org-table-coordinate-overlays
)
3846 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3847 (beginning-of-line 2)))))
3850 (defun org-table-toggle-coordinate-overlays ()
3851 "Toggle the display of Row/Column numbers in tables."
3853 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3854 (message "Tables Row/Column numbers display turned %s"
3855 (if org-table-overlay-coordinates
"on" "off"))
3856 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3858 (unless org-table-overlay-coordinates
3859 (mapc 'delete-overlay org-table-coordinate-overlays
)
3860 (setq org-table-coordinate-overlays nil
)))
3863 (defun org-table-toggle-formula-debugger ()
3864 "Toggle the formula debugger in tables."
3866 (setq org-table-formula-debug
(not org-table-formula-debug
))
3867 (message "Formula debugging has been turned %s"
3868 (if org-table-formula-debug
"on" "off")))
3870 ;;; The orgtbl minor mode
3872 ;; Define a minor mode which can be used in other modes in order to
3873 ;; integrate the org-mode table editor.
3875 ;; This is really a hack, because the org-mode table editor uses several
3876 ;; keys which normally belong to the major mode, for example the TAB and
3877 ;; RET keys. Here is how it works: The minor mode defines all the keys
3878 ;; necessary to operate the table editor, but wraps the commands into a
3879 ;; function which tests if the cursor is currently inside a table. If that
3880 ;; is the case, the table editor command is executed. However, when any of
3881 ;; those keys is used outside a table, the function uses `key-binding' to
3882 ;; look up if the key has an associated command in another currently active
3883 ;; keymap (minor modes, major mode, global), and executes that command.
3884 ;; There might be problems if any of the keys used by the table editor is
3885 ;; otherwise used as a prefix key.
3887 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3888 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3889 ;; addresses this by checking explicitly for both bindings.
3891 ;; The optimized version (see variable `orgtbl-optimized') takes over
3892 ;; all keys which are bound to `self-insert-command' in the *global map*.
3893 ;; Some modes bind other commands to simple characters, for example
3894 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3895 ;; active, this binding is ignored inside tables and replaced with a
3896 ;; modified self-insert.
3899 (defvar orgtbl-mode-map
(make-keymap)
3900 "Keymap for `orgtbl-mode'.")
3902 (defvar org-old-auto-fill-inhibit-regexp nil
3903 "Local variable used by `orgtbl-mode'.")
3905 (defconst orgtbl-line-start-regexp
3906 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
3907 "Matches a line belonging to an orgtbl.")
3909 (defconst orgtbl-extra-font-lock-keywords
3910 (list (list (concat "^" orgtbl-line-start-regexp
".*")
3911 0 (quote 'org-table
) 'prepend
))
3912 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
3914 ;; Install it as a minor mode.
3915 (put 'orgtbl-mode
:included t
)
3916 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
3919 (define-minor-mode orgtbl-mode
3920 "The `org-mode' table editor as a minor mode for use in other modes."
3921 :lighter
" OrgTbl" :keymap orgtbl-mode-map
3922 (org-load-modules-maybe)
3924 ((derived-mode-p 'org-mode
)
3925 ;; Exit without error, in case some hook functions calls this
3926 ;; by accident in org-mode.
3927 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
3929 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
3930 ;; Make sure we are first in minor-mode-map-alist
3931 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
3932 ;; FIXME: maybe it should use emulation-mode-map-alists?
3933 (and c
(setq minor-mode-map-alist
3934 (cons c
(delq c minor-mode-map-alist
)))))
3935 (org-set-local (quote org-table-may-need-update
) t
)
3936 (org-add-hook 'before-change-functions
'org-before-change-function
3938 (org-set-local 'org-old-auto-fill-inhibit-regexp
3939 auto-fill-inhibit-regexp
)
3940 (org-set-local 'auto-fill-inhibit-regexp
3941 (if auto-fill-inhibit-regexp
3942 (concat orgtbl-line-start-regexp
"\\|"
3943 auto-fill-inhibit-regexp
)
3944 orgtbl-line-start-regexp
))
3945 (add-to-invisibility-spec '(org-cwidth))
3946 (when (fboundp 'font-lock-add-keywords
)
3947 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
3948 (org-restart-font-lock))
3949 (easy-menu-add orgtbl-mode-menu
))
3951 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
3952 (org-table-cleanup-narrow-column-properties)
3953 (org-remove-from-invisibility-spec '(org-cwidth))
3954 (remove-hook 'before-change-functions
'org-before-change-function t
)
3955 (when (fboundp 'font-lock-remove-keywords
)
3956 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
3957 (org-restart-font-lock))
3958 (easy-menu-remove orgtbl-mode-menu
)
3959 (force-mode-line-update 'all
))))
3961 (defun org-table-cleanup-narrow-column-properties ()
3962 "Remove all properties related to narrow-column invisibility."
3963 (let ((s (point-min)))
3964 (while (setq s
(text-property-any s
(point-max)
3965 'display org-narrow-column-arrow
))
3966 (remove-text-properties s
(1+ s
) '(display t
)))
3967 (setq s
(point-min))
3968 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
3969 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
3970 (setq s
(point-min))
3971 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
3972 (remove-text-properties s
(1+ s
) '(invisible t
)))))
3974 (defun orgtbl-make-binding (fun n
&rest keys
)
3975 "Create a function for binding in the table minor mode.
3976 FUN is the command to call inside a table. N is used to create a unique
3977 command name. KEYS are keys that should be checked in for a command
3978 to execute outside of tables."
3981 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
3983 (concat "In tables, run `" (symbol-name fun
) "'.\n"
3984 "Outside of tables, run the binding of `"
3985 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
3990 (list 'call-interactively
(list 'quote fun
))
3991 (list 'let
'(orgtbl-mode)
3992 (list 'call-interactively
3995 (list 'key-binding k
))
3997 '('orgtbl-error
))))))))
3999 (defun orgtbl-error ()
4000 "Error when there is no default binding for a table key."
4002 (error "This key has no function outside tables"))
4004 (defun orgtbl-setup ()
4005 "Setup orgtbl keymaps."
4008 '(([(meta shift left
)] org-table-delete-column
)
4009 ([(meta left
)] org-table-move-column-left
)
4010 ([(meta right
)] org-table-move-column-right
)
4011 ([(meta shift right
)] org-table-insert-column
)
4012 ([(meta shift up
)] org-table-kill-row
)
4013 ([(meta shift down
)] org-table-insert-row
)
4014 ([(meta up
)] org-table-move-row-up
)
4015 ([(meta down
)] org-table-move-row-down
)
4016 ("\C-c\C-w" org-table-cut-region
)
4017 ("\C-c\M-w" org-table-copy-region
)
4018 ("\C-c\C-y" org-table-paste-rectangle
)
4019 ("\C-c\C-w" org-table-wrap-region
)
4020 ("\C-c-" org-table-insert-hline
)
4021 ("\C-c}" org-table-toggle-coordinate-overlays
)
4022 ("\C-c{" org-table-toggle-formula-debugger
)
4023 ("\C-m" org-table-next-row
)
4024 ([(shift return
)] org-table-copy-down
)
4025 ("\C-c?" org-table-field-info
)
4026 ("\C-c " org-table-blank-field
)
4027 ("\C-c+" org-table-sum
)
4028 ("\C-c=" org-table-eval-formula
)
4029 ("\C-c'" org-table-edit-formulas
)
4030 ("\C-c`" org-table-edit-field
)
4031 ("\C-c*" org-table-recalculate
)
4032 ("\C-c^" org-table-sort-lines
)
4033 ("\M-a" org-table-beginning-of-field
)
4034 ("\M-e" org-table-end-of-field
)
4035 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4037 (while (setq elt
(pop bindings
))
4038 (setq nfunc
(1+ nfunc
))
4039 (setq key
(org-key (car elt
))
4041 cmd
(orgtbl-make-binding fun nfunc key
))
4042 (org-defkey orgtbl-mode-map key cmd
))
4044 ;; Special treatment needed for TAB and RET
4045 (org-defkey orgtbl-mode-map
[(return)]
4046 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4047 (org-defkey orgtbl-mode-map
"\C-m"
4048 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4050 (org-defkey orgtbl-mode-map
[(tab)]
4051 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4052 (org-defkey orgtbl-mode-map
"\C-i"
4053 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4055 (org-defkey orgtbl-mode-map
[(shift tab
)]
4056 (orgtbl-make-binding 'org-table-previous-field
104
4057 [(shift tab
)] [(tab)] "\C-i"))
4060 (unless (featurep 'xemacs
)
4061 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4062 (orgtbl-make-binding 'org-table-previous-field
107
4063 [S-iso-lefttab
] [backtab] [(shift tab)]
4066 (org-defkey orgtbl-mode-map [backtab]
4067 (orgtbl-make-binding 'org-table-previous-field
108
4068 [backtab] [S-iso-lefttab] [(shift tab)]
4071 (org-defkey orgtbl-mode-map "\M-\C-m"
4072 (orgtbl-make-binding 'org-table-wrap-region 105
4073 "\M-\C-m" [(meta return)]))
4074 (org-defkey orgtbl-mode-map [(meta return)]
4075 (orgtbl-make-binding 'org-table-wrap-region 106
4076 [(meta return)] "\M-\C-m"))
4078 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4079 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4081 (when orgtbl-optimized
4082 ;; If the user wants maximum table support, we need to hijack
4083 ;; some standard editing functions
4084 (org-remap orgtbl-mode-map
4085 'self-insert-command 'orgtbl-self-insert-command
4086 'delete-char 'org-delete-char
4087 'delete-backward-char 'org-delete-backward-char)
4088 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4089 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4091 ["Create or convert" org-table-create-or-convert-from-region
4092 :active (not (org-at-table-p)) :keys "C-c |" ]
4094 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4095 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4096 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4097 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4099 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4100 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4101 ["Copy Field from Above"
4102 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4105 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4106 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4107 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4108 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4110 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4111 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4112 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4113 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4114 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4116 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4118 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4119 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4120 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4121 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4124 ["Insert table template" orgtbl-insert-radio-table
4125 (assq major-mode orgtbl-radio-table-templates)]
4126 ["Comment/uncomment table" orgtbl-toggle-comment t])
4128 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4129 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4130 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4131 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4132 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4133 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4134 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4135 ["Sum Column/Rectangle" org-table-sum
4136 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4137 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4139 org-table-toggle-formula-debugger :active (org-at-table-p)
4141 :style toggle :selected org-table-formula-debug]
4142 ["Show Col/Row Numbers"
4143 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4145 :style toggle :selected org-table-overlay-coordinates]
4149 (defun orgtbl-ctrl-c-ctrl-c (arg)
4150 "If the cursor is inside a table, realign the table.
4151 If it is a table to be sent away to a receiver, do it.
4152 With prefix arg, also recompute table."
4154 (let ((case-fold-search t) (pos (point)) action consts-str consts cst const-str)
4156 (beginning-of-line 1)
4158 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4159 ((looking-at "[ \t]*|") pos)
4160 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4164 (org-table-maybe-eval-formula)
4166 (call-interactively 'org-table-recalculate)
4167 (org-table-maybe-recalculate-line))
4168 (call-interactively 'org-table-align)
4169 (when (orgtbl-send-table 'maybe)
4170 (run-hooks 'orgtbl-after-send-table-hook)))
4171 ((eq action 'recalc)
4173 (goto-char (point-min))
4174 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t)
4175 (setq const-str (substring-no-properties (match-string 1)))
4176 (setq consts (append consts (org-split-string const-str "[ \t]+")))
4179 (while (setq e (pop consts))
4180 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4181 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4182 (setq org-table-formula-constants-local cst)))))
4184 (beginning-of-line 1)
4185 (skip-chars-backward " \r\n\t")
4186 (if (org-at-table-p)
4187 (org-call-with-arg 'org-table-recalculate t))))
4188 (t (let (orgtbl-mode)
4189 (call-interactively (key-binding "\C-c\C-c")))))))
4191 (defun orgtbl-create-or-convert-from-region (arg)
4192 "Create table or convert region to table, if no conflicting binding.
4193 This installs the table binding `C-c |', but only if there is no
4194 conflicting binding to this key outside orgtbl-mode."
4196 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4198 (call-interactively cmd)
4199 (call-interactively 'org-table-create-or-convert-from-region))))
4201 (defun orgtbl-tab (arg)
4202 "Justification and field motion for `orgtbl-mode'."
4204 (if arg (org-table-edit-field t)
4205 (org-table-justify-field-maybe)
4206 (org-table-next-field)))
4208 (defun orgtbl-ret ()
4209 "Justification and field motion for `orgtbl-mode'."
4213 (org-table-justify-field-maybe)
4214 (org-table-next-row)))
4216 (defun orgtbl-self-insert-command (N)
4217 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4218 If the cursor is in a table looking at whitespace, the whitespace is
4219 overwritten, and the table is not marked as requiring realignment."
4221 (if (and (org-at-table-p)
4223 (and org-table-auto-blank-field
4224 (member last-command
4225 '(orgtbl-hijacker-command-100
4226 orgtbl-hijacker-command-101
4227 orgtbl-hijacker-command-102
4228 orgtbl-hijacker-command-103
4229 orgtbl-hijacker-command-104
4230 orgtbl-hijacker-command-105
4232 (org-table-blank-field))
4235 (looking-at "[^|\n]* +|"))
4236 (let (org-table-may-need-update)
4237 (goto-char (1- (match-end 0)))
4238 (org-delete-backward-char 1)
4239 (goto-char (match-beginning 0))
4240 (self-insert-command N))
4241 (setq org-table-may-need-update t)
4244 (cmd (or (key-binding
4245 (or (and (listp function-key-map)
4246 (setq a (assoc last-input-event function-key-map))
4248 (vector last-input-event)))
4249 'self-insert-command)))
4250 (call-interactively cmd)
4251 (if (and org-self-insert-cluster-for-undo
4252 (eq cmd 'self-insert-command))
4253 (if (not (eq last-command 'orgtbl-self-insert-command))
4254 (setq org-self-insert-command-undo-counter 1)
4255 (if (>= org-self-insert-command-undo-counter 20)
4256 (setq org-self-insert-command-undo-counter 1)
4257 (and (> org-self-insert-command-undo-counter 0)
4259 (not (cadr buffer-undo-list)) ; remove nil entry
4260 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4261 (setq org-self-insert-command-undo-counter
4262 (1+ org-self-insert-command-undo-counter))))))))
4264 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4265 "Regular expression matching exponentials as produced by calc.")
4267 (defun orgtbl-export (table target)
4269 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
4270 (lines (org-split-string table "[ \t]*\n[ \t]*"))
4271 org-table-last-alignment org-table-last-column-widths
4273 (if (not (fboundp func))
4274 (error "Cannot export orgtbl table to %s" target))
4275 (setq lines (org-table-clean-before-export lines))
4279 (if (string-match org-table-hline-regexp x)
4281 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4283 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
4285 (loop for i from (1- maxcol) downto 0 do
4286 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
4287 (setq column (delq nil column))
4288 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
4289 (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))
4290 (funcall func table nil)))
4292 (defun orgtbl-gather-send-defs ()
4293 "Gather a plist of :name, :transform, :params for each destination before
4296 (goto-char (org-table-begin))
4298 (beginning-of-line 0)
4299 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4300 (let ((name (org-no-properties (match-string 1)))
4301 (transform (intern (match-string 2)))
4302 (params (if (match-end 3)
4303 (read (concat "(" (match-string 3) ")")))))
4304 (push (list :name name :transform transform :params params)
4306 (beginning-of-line 0)))
4309 (defun orgtbl-send-replace-tbl (name txt)
4310 "Find and replace table NAME with TXT."
4312 (goto-char (point-min))
4313 (unless (re-search-forward
4314 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4315 (error "Don't know where to insert translated table"))
4316 (goto-char (match-beginning 0))
4317 (beginning-of-line 2)
4319 (let ((beg (point)))
4320 (unless (re-search-forward
4321 (concat "END RECEIVE ORGTBL +" name) nil t)
4322 (error "Cannot find end of insertion region"))
4323 (beginning-of-line 1)
4324 (delete-region beg (point))))
4328 (defun org-table-to-lisp (&optional txt)
4329 "Convert the table at point to a Lisp structure.
4330 The structure will be a list. Each item is either the symbol `hline'
4331 for a horizontal separator line, or a list of field values as strings.
4332 The table is taken from the parameter TXT, or from the buffer at point."
4334 (unless (org-at-table-p)
4335 (error "No table at point")))
4337 (buffer-substring-no-properties (org-table-begin)
4339 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4343 (if (string-match org-table-hline-regexp x)
4345 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4348 (defun orgtbl-send-table (&optional maybe)
4349 "Send a transformed version of this table to the receiver position.
4350 With argument MAYBE, fail quietly if no transformation is defined for
4354 (unless (org-at-table-p) (error "Not at a table"))
4355 ;; when non-interactive, we assume align has just happened.
4356 (when (org-called-interactively-p 'any) (org-table-align))
4357 (let ((dests (orgtbl-gather-send-defs))
4358 (txt (buffer-substring-no-properties (org-table-begin)
4361 (unless dests (if maybe (throw 'exit nil)
4362 (error "Don't know how to transform this table")))
4363 (dolist (dest dests)
4364 (let* ((name (plist-get dest :name))
4365 (transform (plist-get dest :transform))
4366 (params (plist-get dest :params))
4367 (skip (plist-get params :skip))
4368 (skipcols (plist-get params :skipcols))
4369 (no-escape (plist-get params :no-escape))
4371 (lines (org-table-clean-before-export
4373 (org-split-string txt "[ \t]*\n[ \t]*"))))
4374 (i0 (if org-table-clean-did-remove-column 2 1))
4375 (lines (if no-escape lines
4376 (mapcar (lambda(l) (replace-regexp-in-string
4377 "\\([&%#_^]\\)" "\\\\\\1{}" l)) lines)))
4380 (if (string-match org-table-hline-regexp x)
4382 (org-remove-by-index
4383 (org-split-string (org-trim x) "\\s-*|\\s-*")
4386 (fun (if (= i0 2) 'cdr 'identity))
4387 (org-table-last-alignment
4388 (org-remove-by-index (funcall fun org-table-last-alignment)
4390 (org-table-last-column-widths
4391 (org-remove-by-index (funcall fun org-table-last-column-widths)
4393 (txt (if (fboundp transform)
4394 (funcall transform table params)
4395 (error "No such transformation function %s" transform))))
4396 (orgtbl-send-replace-tbl name txt))
4397 (setq ntbl (1+ ntbl)))
4398 (message "Table converted and installed at %d receiver location%s"
4399 ntbl (if (> ntbl 1) "s" ""))
4404 (defun org-remove-by-index (list indices &optional i0)
4405 "Remove the elements in LIST with indices in INDICES.
4406 First element has index 0, or I0 if given."
4409 (if (integerp indices) (setq indices (list indices)))
4410 (setq i0 (1- (or i0 0)))
4411 (delq :rm (mapcar (lambda (x)
4413 (if (memq i0 indices) :rm x))
4416 (defun orgtbl-toggle-comment ()
4417 "Comment or uncomment the orgtbl at point."
4419 (let* ((case-fold-search t)
4420 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4421 (re2 (concat "^" orgtbl-line-start-regexp))
4422 (commented (save-excursion (beginning-of-line 1)
4423 (cond ((looking-at re1) t)
4424 ((looking-at re2) nil)
4425 (t (error "Not at an org table")))))
4426 (re (if commented re1 re2))
4429 (beginning-of-line 1)
4430 (while (looking-at re) (beginning-of-line 0))
4431 (beginning-of-line 2)
4433 (while (looking-at re) (beginning-of-line 2))
4435 (comment-region beg end (if commented '(4) nil))))
4437 (defun orgtbl-insert-radio-table ()
4438 "Insert a radio table template appropriate for this major mode."
4440 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4443 (unless e (error "No radio table setup defined for %s" major-mode))
4444 (setq name (read-string "Table name: "))
4445 (while (string-match "%n" txt)
4446 (setq txt (replace-match name t t txt)))
4447 (or (bolp) (insert "\n"))
4452 ;; Dynamically bound input and output for table formatting.
4453 (defvar *orgtbl-table* nil
4454 "Carries the current table through formatting routines.")
4455 (defvar *orgtbl-rtn* nil
4456 "Formatting routines push the output lines here.")
4457 ;; Formatting parameters for the current table section.
4458 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4459 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4460 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4461 (defvar *orgtbl-fmt* nil "Format for each entry.")
4462 (defvar *orgtbl-efmt* nil "Format for numbers.")
4463 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4464 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4465 (defvar *orgtbl-lstart* nil "Text starting a row.")
4466 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4467 (defvar *orgtbl-lend* nil "Text ending a row.")
4468 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4470 (defsubst orgtbl-get-fmt (fmt i)
4471 "Retrieve the format from FMT corresponding to the Ith column."
4472 (if (and (not (functionp fmt)) (consp fmt))
4476 (defsubst orgtbl-apply-fmt (fmt &rest args)
4477 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4478 (cond ((functionp fmt) (apply fmt args))
4479 (fmt (apply 'format fmt args))
4483 (defsubst orgtbl-eval-str (str)
4484 "If STR is a function, evaluate it with no arguments."
4489 (defun orgtbl-format-line (line)
4490 "Format LINE as a table row."
4491 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4497 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4498 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4499 (orgtbl-apply-fmt efmt (match-string 1 f)
4502 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4503 *orgtbl-default-fmt*)
4506 (push (if *orgtbl-lfmt*
4507 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4508 (concat (orgtbl-eval-str *orgtbl-lstart*)
4509 (mapconcat 'identity line *orgtbl-sep*)
4510 (orgtbl-eval-str *orgtbl-lend*)))
4513 (defun orgtbl-format-section (section-stopper)
4514 "Format lines until the first occurrence of SECTION-STOPPER."
4517 (while (not (eq (car *orgtbl-table*) section-stopper))
4518 (if prevline (orgtbl-format-line prevline))
4519 (setq prevline (pop *orgtbl-table*)))
4520 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4521 (*orgtbl-lend* *orgtbl-llend*)
4522 (*orgtbl-lfmt* *orgtbl-llfmt*))
4523 (orgtbl-format-line prevline))))))
4526 (defun orgtbl-to-generic (table params)
4527 "Convert the orgtbl-mode TABLE to some other format.
4528 This generic routine can be used for many standard cases.
4529 TABLE is a list, each entry either the symbol `hline' for a horizontal
4530 separator line, or a list of fields for that line.
4531 PARAMS is a property list of parameters that can influence the conversion.
4532 For the generic converter, some parameters are obligatory: you need to
4533 specify either :lfmt, or all of (:lstart :lend :sep).
4535 Valid parameters are:
4537 :splice When set to t, return only table body lines, don't wrap
4538 them into :tstart and :tend. Default is nil. When :splice
4539 is non-nil, this also means that the exporter should not look
4540 for and interpret header and footer sections.
4542 :hline String to be inserted on horizontal separation lines.
4543 May be nil to ignore hlines.
4545 :sep Separator between two fields
4546 :remove-nil-lines Do not include lines that evaluate to nil.
4548 Each in the following group may be either a string or a function
4549 of no arguments returning a string:
4551 :tstart String to start the table. Ignored when :splice is t.
4552 :tend String to end the table. Ignored when :splice is t.
4553 :lstart String to start a new table line.
4554 :llstart String to start the last table line, defaults to :lstart.
4555 :lend String to end a table line
4556 :llend String to end the last table line, defaults to :lend.
4558 Each in the following group may be a string, a function of one
4559 argument (the field or line) returning a string, or a plist
4560 mapping columns to either of the above:
4562 :lfmt Format for entire line, with enough %s to capture all fields.
4563 If this is present, :lstart, :lend, and :sep are ignored.
4564 :llfmt Format for the entire last line, defaults to :lfmt.
4565 :fmt A format to be used to wrap the field, should contain
4566 %s for the original field value. For example, to wrap
4567 everything in dollars, you could use :fmt \"$%s$\".
4568 This may also be a property list with column numbers and
4569 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4570 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4571 Same as above, specific for the header lines in the table.
4572 All lines before the first hline are treated as header.
4573 If any of these is not present, the data line value is used.
4575 This may be either a string or a function of two arguments:
4577 :efmt Use this format to print numbers with exponentials.
4578 The format should have %s twice for inserting mantissa
4579 and exponent, for example \"%s\\\\times10^{%s}\". This
4580 may also be a property list with column numbers and
4581 formats. :fmt will still be applied after :efmt.
4583 In addition to this, the parameters :skip and :skipcols are always handled
4584 directly by `orgtbl-send-table'. See manual."
4585 (let* ((splicep (plist-get params :splice))
4586 (hline (plist-get params :hline))
4587 (skipheadrule (plist-get params :skipheadrule))
4588 (remove-nil-linesp (plist-get params :remove-nil-lines))
4589 (remove-newlines (plist-get params :remove-newlines))
4590 (*orgtbl-hline* hline)
4591 (*orgtbl-table* table)
4592 (*orgtbl-sep* (plist-get params :sep))
4593 (*orgtbl-efmt* (plist-get params :efmt))
4594 (*orgtbl-lstart* (plist-get params :lstart))
4595 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4596 (*orgtbl-lend* (plist-get params :lend))
4597 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4598 (*orgtbl-lfmt* (plist-get params :lfmt))
4599 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4600 (*orgtbl-fmt* (plist-get params :fmt))
4605 (when (plist-member params :tstart)
4606 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4607 (if tstart (push tstart *orgtbl-rtn*)))))
4609 ;; Do we have a heading section? If so, format it and handle the
4611 (if (and (not splicep)
4612 (or (consp (car *orgtbl-table*))
4613 (consp (nth 1 *orgtbl-table*)))
4614 (memq 'hline (cdr *orgtbl-table*)))
4616 (when (eq 'hline (car *orgtbl-table*))
4617 ;; there is a hline before the first data line
4618 (and hline (push hline *orgtbl-rtn*))
4619 (pop *orgtbl-table*))
4620 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4622 (*orgtbl-llstart* (or (plist-get params :hllstart)
4624 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4625 (*orgtbl-llend* (or (plist-get params :hllend)
4626 (plist-get params :hlend) *orgtbl-llend*))
4627 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4628 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4629 (plist-get params :hlfmt) *orgtbl-llfmt*))
4630 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4631 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4632 (orgtbl-format-section 'hline))
4633 (if (and hline (not skipheadrule)) (push hline *orgtbl-rtn*))
4634 (pop *orgtbl-table*)))
4636 ;; Now format the main section.
4637 (orgtbl-format-section nil)
4640 (when (plist-member params :tend)
4641 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4642 (if tend (push tend *orgtbl-rtn*)))))
4644 (mapconcat (if remove-newlines
4646 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4648 (nreverse (if remove-nil-linesp
4649 (remq nil *orgtbl-rtn*)
4650 *orgtbl-rtn*)) "\n")))
4653 (defun orgtbl-to-tsv (table params)
4654 "Convert the orgtbl-mode table to TAB separated material."
4655 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4657 (defun orgtbl-to-csv (table params)
4658 "Convert the orgtbl-mode table to CSV material.
4659 This does take care of the proper quoting of fields with comma or quotes."
4660 (orgtbl-to-generic table (org-combine-plists
4661 '(:sep "," :fmt org-quote-csv-field)
4665 (defun orgtbl-to-latex (table params)
4666 "Convert the orgtbl-mode TABLE to LaTeX.
4667 TABLE is a list, each entry either the symbol `hline' for a horizontal
4668 separator line, or a list of fields for that line.
4669 PARAMS is a property list of parameters that can influence the conversion.
4670 Supports all parameters from `orgtbl-to-generic'. Most important for
4673 :splice When set to t, return only table body lines, don't wrap
4674 them into a tabular environment. Default is nil.
4676 :fmt A format to be used to wrap the field, should contain %s for the
4677 original field value. For example, to wrap everything in dollars,
4678 use :fmt \"$%s$\". This may also be a property list with column
4679 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4680 The format may also be a function that formats its one argument.
4682 :efmt Format for transforming numbers with exponentials. The format
4683 should have %s twice for inserting mantissa and exponent, for
4684 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4685 This may also be a property list with column numbers and formats.
4686 The format may also be a function that formats its two arguments.
4688 :llend If you find too much space below the last line of a table,
4689 pass a value of \"\" for :llend to suppress the final \\\\.
4691 The general parameters :skip and :skipcols have already been applied when
4692 this function is called."
4693 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4694 org-table-last-alignment ""))
4697 :tstart (concat "\\begin{tabular}{" alignment "}")
4698 :tend "\\end{tabular}"
4699 :lstart "" :lend " \\\\" :sep " & "
4700 :efmt "%s\\,(%s)" :hline "\\hline")))
4701 (orgtbl-to-generic table (org-combine-plists params2 params))))
4704 (defun orgtbl-to-html (table params)
4705 "Convert the orgtbl-mode TABLE to HTML.
4706 TABLE is a list, each entry either the symbol `hline' for a horizontal
4707 separator line, or a list of fields for that line.
4708 PARAMS is a property list of parameters that can influence the conversion.
4709 Currently this function recognizes the following parameters:
4711 :splice When set to t, return only table body lines, don't wrap
4712 them into a <table> environment. Default is nil.
4714 The general parameters :skip and :skipcols have already been applied when
4715 this function is called. The function does *not* use `orgtbl-to-generic',
4716 so you cannot specify parameters for it."
4717 (let* ((splicep (plist-get params :splice))
4718 (html-table-tag org-export-html-table-tag)
4720 ;; Just call the formatter we already have
4721 ;; We need to make text lines for it, so put the fields back together.
4722 (setq html (org-format-org-table-html
4727 (concat "| " (mapconcat 'org-html-expand x " | ") " |")))
4730 (if (string-match "\n+\\'" html)
4731 (setq html (replace-match "" t t html)))
4735 (defun orgtbl-to-texinfo (table params)
4736 "Convert the orgtbl-mode TABLE to TeXInfo.
4737 TABLE is a list, each entry either the symbol `hline' for a horizontal
4738 separator line, or a list of fields for that line.
4739 PARAMS is a property list of parameters that can influence the conversion.
4740 Supports all parameters from `orgtbl-to-generic'. Most important for
4743 :splice nil/t When set to t, return only table body lines, don't wrap
4744 them into a multitable environment. Default is nil.
4746 :fmt fmt A format to be used to wrap the field, should contain
4747 %s for the original field value. For example, to wrap
4748 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4749 This may also be a property list with column numbers and
4750 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4751 Each format also may be a function that formats its one
4754 :cf \"f1 f2..\" The column fractions for the table. By default these
4755 are computed automatically from the width of the columns
4758 The general parameters :skip and :skipcols have already been applied when
4759 this function is called."
4760 (let* ((total (float (apply '+ org-table-last-column-widths)))
4761 (colfrac (or (plist-get params :cf)
4763 (lambda (x) (format "%.3f" (/ (float x) total)))
4764 org-table-last-column-widths " ")))
4767 :tstart (concat "@multitable @columnfractions " colfrac)
4768 :tend "@end multitable"
4769 :lstart "@item " :lend "" :sep " @tab "
4770 :hlstart "@headitem ")))
4771 (orgtbl-to-generic table (org-combine-plists params2 params))))
4774 (defun orgtbl-to-orgtbl (table params)
4775 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4776 Useful when slicing one table into many. The :hline, :sep,
4777 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4778 and :tend suppress strings without splicing; they can be set to
4779 provide ORGTBL directives for the generated table."
4783 :tstart nil :tend nil
4788 (params (org-combine-plists params2 params)))
4790 (insert (orgtbl-to-generic table params))
4791 (goto-char (point-min))
4792 (while (re-search-forward org-table-hline-regexp nil t)
4794 (buffer-substring 1 (buffer-size)))))
4796 (defun orgtbl-to-table.el (table params)
4797 "Convert the orgtbl-mode TABLE into a table.el table."
4799 (insert (orgtbl-to-orgtbl table params))
4801 (replace-regexp-in-string
4803 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
4805 (defun orgtbl-to-unicode (table params)
4806 "Convert the orgtbl-mode TABLE into a table with unicode characters.
4807 You need the ascii-art-to-unicode.el package for this. You can download
4808 it here: http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el."
4810 (insert (orgtbl-to-table.el table params))
4811 (goto-char (point-min))
4812 (if (or (featurep 'ascii-art-to-unicode)
4813 (require 'ascii-art-to-unicode nil t))
4815 (unless (delq nil (mapcar (lambda (l) (string-match "aa2u" (car l))) org-stored-links))
4816 (push '("http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el"
4817 "Link to ascii-art-to-unicode.el") org-stored-links))
4818 (error "Please download ascii-art-to-unicode.el (use C-c C-l to insert the link to it)"))
4821 (defun org-table-get-remote-range (name-or-id form)
4822 "Get a field value or a list of values in a range from table at ID.
4824 NAME-OR-ID may be the name of a table in the current file as set by
4825 a \"#+TBLNAME:\" directive. The first table following this line
4826 will then be used. Alternatively, it may be an ID referring to
4827 any entry, also in a different file. In this case, the first table
4828 in that entry will be referenced.
4829 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
4830 \"@I$2..@II$2\". All the references must be absolute, not relative.
4832 The return value is either a single string for a single field, or a
4833 list of the fields in the rectangle ."
4835 (let ((case-fold-search t) (id-loc nil)
4836 ;; Protect a bunch of variables from being overwritten
4837 ;; by the context of the remote table
4838 org-table-column-names org-table-column-name-regexp
4839 org-table-local-parameters org-table-named-field-locations
4840 org-table-current-line-types org-table-current-begin-line
4841 org-table-current-begin-pos org-table-dlines
4842 org-table-current-ncol
4843 org-table-hlines org-table-last-alignment
4844 org-table-last-column-widths org-table-last-alignment
4845 org-table-last-column-widths tbeg
4847 (setq form (org-table-convert-refs-to-rc form))
4852 (goto-char (point-min))
4853 (if (re-search-forward
4854 (concat "^[ \t]*#\\+tblname:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4856 (setq buffer (current-buffer) loc (match-beginning 0))
4857 (setq id-loc (org-id-find name-or-id 'marker))
4858 (unless (and id-loc (markerp id-loc))
4859 (error "Can't find remote table \"%s\"" name-or-id))
4860 (setq buffer (marker-buffer id-loc)
4861 loc (marker-position id-loc))
4862 (move-marker id-loc nil)))
4863 (with-current-buffer buffer
4869 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4870 (not (match-beginning 1)))
4871 (error "Cannot find a table at NAME or ID %s" name-or-id))
4872 (setq tbeg (point-at-bol))
4873 (org-table-get-specials)
4874 (setq form (org-table-formula-substitute-names
4875 (org-table-formula-handle-first/last-rc form)))
4876 (if (and (string-match org-table-range-regexp form)
4877 (> (length (match-string 0 form)) 1))
4879 (org-table-get-range (match-string 0 form) tbeg 1))
4882 (provide 'org-table)
4885 ;; generated-autoload-file: "org-loaddefs.el"
4888 ;;; org-table.el ends here