1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004-2011 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 (defvar orgtbl-mode
) ; defined below
45 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
46 (defvar org-export-html-table-tag
) ; defined in org-exp.el
47 (defvar constants-unit-system
)
48 (defvar org-table-follow-field-mode
)
50 (defvar orgtbl-after-send-table-hook nil
51 "Hook for functions attaching to `C-c C-c', if the table is sent.
52 This can be used to add additional functionality after the table is sent
53 to the receiver position, othewise, if table is not sent, the functions
56 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
57 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
58 In the optimized version, the table editor takes over all simple keys that
59 normally just insert a character. In tables, the characters are inserted
60 in a way to minimize disturbing the table structure (i.e. in overwrite mode
61 for empty fields). Outside tables, the correct binding of the keys is
64 The default for this option is t if the optimized version is also used in
65 Org-mode. See the variable `org-enable-table-editor' for details. Changing
66 this variable requires a restart of Emacs to become effective."
70 (defcustom orgtbl-radio-table-templates
71 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
72 % END RECEIVE ORGTBL %n
74 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
77 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
78 @c END RECEIVE ORGTBL %n
80 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
83 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
84 <!-- END RECEIVE ORGTBL %n -->
86 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
89 "Templates for radio tables in different major modes.
90 All occurrences of %n in a template will be replaced with the name of the
91 table, obtained by prompting the user."
94 (list (symbol :tag
"Major mode")
95 (string :tag
"Format"))))
97 (defgroup org-table-settings nil
98 "Settings for tables in Org-mode."
99 :tag
"Org Table Settings"
102 (defcustom org-table-default-size
"5x2"
103 "The default size for newly created tables, Columns x Rows."
104 :group
'org-table-settings
107 (defcustom org-table-number-regexp
108 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
109 "Regular expression for recognizing numbers in table columns.
110 If a table column contains mostly numbers, it will be aligned to the
111 right. If not, it will be aligned to the left.
113 The default value of this option is a regular expression which allows
114 anything which looks remotely like a number as used in scientific
115 context. For example, all of the following will be considered a
117 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
119 Other options offered by the customize interface are more restrictive."
120 :group
'org-table-settings
122 (const :tag
"Positive Integers"
124 (const :tag
"Integers"
126 (const :tag
"Floating Point Numbers"
127 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
128 (const :tag
"Floating Point Number or Integer"
129 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
130 (const :tag
"Exponential, Floating point, Integer"
131 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
132 (const :tag
"Very General Number-Like, including hex"
133 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
134 (string :tag
"Regexp:")))
136 (defcustom org-table-number-fraction
0.5
137 "Fraction of numbers in a column required to make the column align right.
138 In a column all non-white fields are considered. If at least this
139 fraction of fields is matched by `org-table-number-fraction',
140 alignment to the right border applies."
141 :group
'org-table-settings
144 (defgroup org-table-editing nil
145 "Behavior of tables during editing in Org-mode."
146 :tag
"Org Table Editing"
149 (defcustom org-table-automatic-realign t
150 "Non-nil means automatically re-align table when pressing TAB or RETURN.
151 When nil, aligning is only done with \\[org-table-align], or after column
153 :group
'org-table-editing
156 (defcustom org-table-auto-blank-field t
157 "Non-nil means automatically blank table field when starting to type into it.
158 This only happens when typing immediately after a field motion
159 command (TAB, S-TAB or RET).
160 Only relevant when `org-enable-table-editor' is equal to `optimized'."
161 :group
'org-table-editing
164 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
165 "Non-nil means automatically exit the follow mode.
166 When nil, the follow mode will stay on and be active in any table
167 the cursor enters. Since the table follow filed mode messes with the
168 window configuration, it is not recommended to set this variable to nil,
169 except maybe locally in a special file that has mostly tables with long
174 (defcustom org-table-fix-formulas-confirm nil
175 "Whether the user should confirm when Org fixes formulas."
176 :group
'org-table-editing
178 (const :tag
"with yes-or-no" yes-or-no-p
)
179 (const :tag
"with y-or-n" y-or-n-p
)
180 (const :tag
"no confirmation" nil
)))
181 (put 'org-table-fix-formulas-confirm
183 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
185 (defcustom org-table-tab-jumps-over-hlines t
186 "Non-nil means tab in the last column of a table with jump over a hline.
187 If a horizontal separator line is following the current line,
188 `org-table-next-field' can either create a new row before that line, or jump
189 over the line. When this option is nil, a new line will be created before
191 :group
'org-table-editing
194 (defgroup org-table-calculation nil
195 "Options concerning tables in Org-mode."
196 :tag
"Org Table Calculation"
199 (defcustom org-table-use-standard-references
'from
200 "Should org-mode work with table references like B3 instead of @3$2?
203 from accept as input, do not present for editing
204 t accept as input and present for editing"
205 :group
'org-table-calculation
207 (const :tag
"Never, don't even check user input for them" nil
)
208 (const :tag
"Always, both as user input, and when editing" t
)
209 (const :tag
"Convert user input, don't offer during editing" from
)))
211 (defcustom org-table-copy-increment t
212 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
213 :group
'org-table-calculation
216 (defcustom org-calc-default-modes
217 '(calc-internal-prec 12
218 calc-float-format
(float 8)
221 calc-symbolic-mode nil
222 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
223 calc-display-working-message t
225 "List with Calc mode settings for use in `calc-eval' for table formulas.
226 The list must contain alternating symbols (Calc modes variables and values).
227 Don't remove any of the default settings, just change the values. Org-mode
228 relies on the variables to be present in the list."
229 :group
'org-table-calculation
232 (defcustom org-table-duration-custom-format
'hours
233 "Format for the output of calc computations like $1+$2;t.
234 The default value is 'hours, and will output the results as a
235 number of hours. Other allowed values are 'seconds, 'minutes and
236 'days, and the output will be a fraction of seconds, minutes or
238 :group
'org-table-calculation
239 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
240 (symbol :tag
"Minutes" 'minutes
)
241 (symbol :tag
"Hours " 'hours
)
242 (symbol :tag
"Days " 'days
)))
244 (defcustom org-table-formula-field-format
"%s"
245 "Format for fields which contain the result of a formula.
246 For example, using \"~%s~\" will display the result within tilde
247 characters. Beware that modifying the display can prevent the
248 field from being used in another formula."
249 :group
'org-table-settings
252 (defcustom org-table-formula-evaluate-inline t
253 "Non-nil means TAB and RET evaluate a formula in current table field.
254 If the current field starts with an equal sign, it is assumed to be a formula
255 which should be evaluated as described in the manual and in the documentation
256 string of the command `org-table-eval-formula'. This feature requires the
258 When this variable is nil, formula calculation is only available through
259 the command \\[org-table-eval-formula]."
260 :group
'org-table-calculation
263 (defcustom org-table-formula-use-constants t
264 "Non-nil means interpret constants in formulas in tables.
265 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
266 by the value given in `org-table-formula-constants', or by a value obtained
267 from the `constants.el' package."
268 :group
'org-table-calculation
271 (defcustom org-table-formula-constants nil
272 "Alist with constant names and values, for use in table formulas.
273 The car of each element is a name of a constant, without the `$' before it.
274 The cdr is the value as a string. For example, if you'd like to use the
275 speed of light in a formula, you would configure
277 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
279 and then use it in an equation like `$1*$c'.
281 Constants can also be defined on a per-file basis using a line like
283 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
284 :group
'org-table-calculation
286 (cons (string :tag
"name")
287 (string :tag
"value"))))
289 (defcustom org-table-allow-automatic-line-recalculation t
290 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
291 Automatically means when TAB or RET or C-c C-c are pressed in the line."
292 :group
'org-table-calculation
295 (defcustom org-table-error-on-row-ref-crossing-hline t
296 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
300 (defcustom org-table-relative-ref-may-cross-hline t
301 "Non-nil means relative formula references may cross hlines.
302 Here are the allowed values:
304 nil Relative references may not cross hlines. They will reference the
305 field next to the hline instead. Coming from below, the reference
306 will be to the field below the hline. Coming from above, it will be
308 t Relative references may cross hlines.
309 error An attempt to cross a hline will throw an error.
311 It is probably good to never set this variable to nil, for the sake of
312 portability of tables."
313 :group
'org-table-calculation
315 (const :tag
"Allow to cross" t
)
316 (const :tag
"Stick to hline" nil
)
317 (const :tag
"Error on attempt to cross" error
)))
319 (defgroup org-table-import-export nil
320 "Options concerning table import and export in Org-mode."
321 :tag
"Org Table Import Export"
324 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
325 "Default export parameters for `org-table-export'.
326 These can be overridden for a specific table by setting the
327 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
328 radio tables for the different export transformations and
329 available parameters."
330 :group
'org-table-import-export
333 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
334 "Detects a table line marked for automatic recalculation.")
335 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
336 "Detects a table line marked for automatic recalculation.")
337 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
338 "Detects a table line marked for automatic recalculation.")
339 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
340 "Searching from within a table (any type) this finds the first line outside the table.")
341 (defvar org-table-last-highlighted-reference nil
)
342 (defvar org-table-formula-history nil
)
344 (defvar org-table-column-names nil
345 "Alist with column names, derived from the `!' line.")
346 (defvar org-table-column-name-regexp nil
347 "Regular expression matching the current column names.")
348 (defvar org-table-local-parameters nil
349 "Alist with parameter names, derived from the `$' line.")
350 (defvar org-table-named-field-locations nil
351 "Alist with locations of named fields.")
353 (defvar org-table-current-line-types nil
354 "Table row types, non-nil only for the duration of a command.")
355 (defvar org-table-current-begin-line nil
356 "Table begin line, non-nil only for the duration of a command.")
357 (defvar org-table-current-begin-pos nil
358 "Table begin position, non-nil only for the duration of a command.")
359 (defvar org-table-current-ncol nil
360 "Number of columns in table, non-nil only for the duration of a command.")
361 (defvar org-table-dlines nil
362 "Vector of data line line numbers in the current table.")
363 (defvar org-table-hlines nil
364 "Vector of hline line numbers in the current table.")
366 (defconst org-table-range-regexp
367 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
369 "Regular expression for matching ranges in formulas.")
371 (defconst org-table-range-regexp2
373 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
375 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
376 "Match a range for reference display.")
378 (defun org-table-colgroup-line-p (line)
379 "Is this a table line colgroup information?"
381 (and (string-match "[<>]\\|&[lg]t;" line
)
382 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
388 (not (member s
'("" "<" ">" "<>" "<" ">" "<>"))))
389 (org-split-string (match-string 1 line
) "[ \t]*|[ \t]*")))))))
391 (defun org-table-cookie-line-p (line)
392 "Is this a table line with only alignment/width cookies?"
394 (and (string-match "[<>]\\|&[lg]t;" line
)
396 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line
)
397 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line
))
398 (not (delq nil
(mapcar
400 (not (or (equal s
"")
402 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s
)
404 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'"
406 (org-split-string (match-string 1 line
)
407 "[ \t]*|[ \t]*")))))))
409 (defconst org-table-translate-regexp
410 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
411 "Match a reference that needs translation, for reference display.")
413 (defun org-table-create-with-table.el
()
414 "Use the table.el package to insert a new table.
415 If there is already a table at point, convert between Org-mode tables
416 and table.el tables."
421 (if (y-or-n-p "Convert table to Org-mode table? ")
422 (org-table-convert)))
424 (when (y-or-n-p "Convert table to table.el table? ")
426 (org-table-convert)))
427 (t (call-interactively 'table-insert
))))
429 (defun org-table-create-or-convert-from-region (arg)
430 "Convert region to table, or create an empty table.
431 If there is an active region, convert it to a table, using the function
432 `org-table-convert-region'. See the documentation of that function
433 to learn how the prefix argument is interpreted to determine the field
435 If there is no such region, create an empty table with `org-table-create'."
437 (if (org-region-active-p)
438 (org-table-convert-region (region-beginning) (region-end) arg
)
439 (org-table-create arg
)))
441 (defun org-table-create (&optional size
)
442 "Query for a size and insert a table skeleton.
443 SIZE is a string Columns x Rows like for example \"3x2\"."
446 (setq size
(read-string
447 (concat "Table size Columns x Rows [e.g. "
448 org-table-default-size
"]: ")
449 "" nil org-table-default-size
)))
452 (indent (make-string (current-column) ?\
))
453 (split (org-split-string size
" *x *"))
454 (rows (string-to-number (nth 1 split
)))
455 (columns (string-to-number (car split
)))
456 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
458 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
459 (point-at-bol) (point)))
460 (beginning-of-line 1)
462 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
463 (dotimes (i rows
) (insert line
))
466 ;; Insert a hline after the first row.
473 (defun org-table-convert-region (beg0 end0
&optional separator
)
474 "Convert region to a table.
475 The region goes from BEG0 to END0, but these borders will be moved
476 slightly, to make sure a beginning of line in the first line is included.
478 SEPARATOR specifies the field separator in the lines. It can have the
481 '(4) Use the comma as a field separator
482 '(16) Use a TAB as field separator
483 integer When a number, use that many spaces as field separator
484 nil When nil, the command tries to be smart and figure out the
485 separator in the following way:
486 - when each line contains a TAB, assume TAB-separated material
487 - when each line contains a comma, assume CSV material
488 - else, assume one or more SPACE characters as separator."
490 (let* ((beg (min beg0 end0
))
491 (end (max beg0 end0
))
494 (beginning-of-line 1)
495 (setq beg
(move-marker (make-marker) (point)))
497 (if (bolp) (backward-char 1) (end-of-line 1))
498 (setq end
(move-marker (make-marker) (point)))
499 ;; Get the right field separator
504 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
505 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
508 (if (equal separator
'(4))
509 (while (< (point) end
)
510 ;; parse the csv stuff
512 ((looking-at "^") (insert "| "))
513 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
514 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
515 (replace-match "\\1")
516 (if (looking-at "\"") (insert "\"")))
517 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
518 ((looking-at "[ \t]*,") (replace-match " | "))
519 (t (beginning-of-line 2))))
521 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
522 ((equal separator
'(16)) "^\\|\t")
523 ((integerp separator
)
525 (error "Number of spaces in separator must be >= 1")
526 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
527 (t (error "This should not happen"))))
528 (while (re-search-forward re end t
)
529 (replace-match "| " t t
)))
533 (defun org-table-import (file arg
)
534 "Import FILE as a table.
535 The file is assumed to be tab-separated. Such files can be produced by most
536 spreadsheet and database applications. If no tabs (at least one per line)
537 are found, lines will be split on whitespace into fields."
539 (or (bolp) (newline))
542 (insert-file-contents file
)
543 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
546 (defvar org-table-last-alignment
)
547 (defvar org-table-last-column-widths
)
548 (defun org-table-export (&optional file format
)
549 "Export table to a file, with configurable format.
550 Such a file can be imported into a spreadsheet program like Excel.
551 FILE can be the output file name. If not given, it will be taken from
552 a TABLE_EXPORT_FILE property in the current entry or higher up in the
553 hierarchy, or the user will be prompted for a file name.
554 FORMAT can be an export format, of the same kind as it used when
555 `orgtbl-mode' sends a table in a different format. The default format can
556 be found in the variable `org-table-export-default-format', but the function
557 first checks if there is an export format specified in a TABLE_EXPORT_FORMAT
558 property, locally or anywhere up in the hierarchy."
560 (unless (org-at-table-p)
561 (error "No table at point"))
563 (org-table-align) ;; make sure we have everything we need
564 (let* ((beg (org-table-begin))
565 (end (org-table-end))
566 (txt (buffer-substring-no-properties beg end
))
567 (file (or file
(org-entry-get beg
"TABLE_EXPORT_FILE" t
)))
569 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)))
572 (setq file
(read-file-name "Export table to: "))
573 (unless (or (not (file-exists-p file
))
574 (y-or-n-p (format "Overwrite file %s? " file
)))
576 (if (file-directory-p file
)
577 (error "This is a directory path, not a file"))
578 (if (and (buffer-file-name)
579 (equal (file-truename file
)
580 (file-truename (buffer-file-name))))
581 (error "Please specify a file name that is different from current"))
583 (setq deffmt-readable org-table-export-default-format
)
584 (while (string-match "\t" deffmt-readable
)
585 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
586 (while (string-match "\n" deffmt-readable
)
587 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
588 (setq format
(org-completing-read
590 '("orgtbl-to-tsv" "orgtbl-to-csv"
591 "orgtbl-to-latex" "orgtbl-to-html"
592 "orgtbl-to-generic" "orgtbl-to-texinfo"
593 "orgtbl-to-orgtbl") nil nil
595 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
596 (let* ((transform (intern (match-string 1 format
)))
597 (params (if (match-end 2)
598 (read (concat "(" (match-string 2 format
) ")"))))
599 (skip (plist-get params
:skip
))
600 (skipcols (plist-get params
:skipcols
))
601 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
602 (lines (org-table-clean-before-export lines
))
603 (i0 (if org-table-clean-did-remove-column
2 1))
606 (if (string-match org-table-hline-regexp x
)
609 (org-split-string (org-trim x
) "\\s-*|\\s-*")
612 (fun (if (= i0
2) 'cdr
'identity
))
613 (org-table-last-alignment
614 (org-remove-by-index (funcall fun org-table-last-alignment
)
616 (org-table-last-column-widths
617 (org-remove-by-index (funcall fun org-table-last-column-widths
)
620 (unless (fboundp transform
)
621 (error "No such transformation function %s" transform
))
622 (setq txt
(funcall transform table params
))
624 (with-current-buffer (find-file-noselect file
)
625 (setq buf
(current-buffer))
631 (message "Export done."))
632 (error "TABLE_EXPORT_FORMAT invalid"))))
634 (defvar org-table-aligned-begin-marker
(make-marker)
635 "Marker at the beginning of the table last aligned.
636 Used to check if cursor still is in that table, to minimize realignment.")
637 (defvar org-table-aligned-end-marker
(make-marker)
638 "Marker at the end of the table last aligned.
639 Used to check if cursor still is in that table, to minimize realignment.")
640 (defvar org-table-last-alignment nil
641 "List of flags for flushright alignment, from the last re-alignment.
642 This is being used to correctly align a single field after TAB or RET.")
643 (defvar org-table-last-column-widths nil
644 "List of max width of fields in each column.
645 This is being used to correctly align a single field after TAB or RET.")
646 (defvar org-table-formula-debug nil
647 "Non-nil means debug table formulas.
648 When nil, simply write \"#ERROR\" in corrupted fields.")
649 (make-variable-buffer-local 'org-table-formula-debug
)
650 (defvar org-table-overlay-coordinates nil
651 "Overlay coordinates after each align of a table.")
652 (make-variable-buffer-local 'org-table-overlay-coordinates
)
654 (defvar org-last-recalc-line nil
)
655 (defvar org-table-do-narrow t
) ; for dynamic scoping
656 (defconst org-narrow-column-arrow
"=>"
657 "Used as display property in narrowed table columns.")
659 (defun org-table-align ()
660 "Align the table at point by aligning all vertical bars."
664 (beg (org-table-begin))
665 (end (org-table-end))
666 ;; Current cursor position
667 (linepos (org-current-line))
668 (colpos (org-table-current-column))
669 (winstart (window-start))
670 (winstartline (org-current-line (min winstart
(1- (point-max)))))
671 lines
(new "") lengths l typenums ty fields maxfields i
679 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
681 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
682 emptystrings links dates emph raise narrow
683 falign falign1 fmax f1 len c e space
)
685 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
686 ;; Check if we have links or dates
688 (setq links
(re-search-forward org-bracket-link-regexp end t
))
690 (setq emph
(and org-hide-emphasis-markers
691 (re-search-forward org-emph-re end t
)))
693 (setq raise
(and org-use-sub-superscripts
694 (re-search-forward org-match-substring-regexp end t
)))
696 (setq dates
(and org-display-custom-times
697 (re-search-forward org-ts-regexp-both end t
)))
698 ;; Make sure the link properties are right
699 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
700 ;; Make sure the date properties are right
701 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
702 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
703 (when raise
(goto-char beg
) (while (org-raise-scripts end
)))
705 ;; Check if we are narrowing any columns
707 (setq narrow
(and org-table-do-narrow
708 org-format-transports-properties-p
709 (re-search-forward "<[lrc]?[0-9]+>" end t
)))
711 (setq falign
(re-search-forward "<[lrc][0-9]*>" end t
))
714 (setq lines
(org-split-string
715 (buffer-substring beg end
) "\n"))
716 ;; Store the indentation of the first line
717 (if (string-match "^ *" (car lines
))
718 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
719 ;; Mark the hlines by setting the corresponding element to nil
720 ;; At the same time, we remove trailing space.
721 (setq lines
(mapcar (lambda (l)
722 (if (string-match "^ *|-" l
)
724 (if (string-match "[ \t]+$" l
)
725 (substring l
0 (match-beginning 0))
728 ;; Get the data fields by splitting the lines.
731 (org-split-string l
" *| *"))
732 (delq nil
(copy-sequence lines
))))
733 ;; How many fields in the longest line?
735 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
737 (kill-region beg end
)
738 (org-table-create org-table-default-size
)
739 (error "Empty table - created default table")))
740 ;; A list of empty strings to fill any short rows on output
741 (setq emptystrings
(make-list maxfields
""))
742 ;; Check for special formatting.
744 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
745 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
746 ;; Check if there is an explicit width specified
748 (when (or narrow falign
)
749 (setq c column fmax nil falign1 nil
)
752 (when (and (stringp e
) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e
))
753 (if (match-end 1) (setq falign1
(match-string 1 e
)))
754 (if (and org-table-do-narrow
(match-end 2))
755 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
756 ;; Find fields that are wider than fmax, and shorten them
758 (loop for xx in column do
759 (when (and (stringp xx
)
760 (> (org-string-width xx
) fmax
))
761 (org-add-props xx nil
763 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
764 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
766 (error "Cannot narrow field starting with wide link \"%s\""
767 (match-string 0 xx
)))
768 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
769 (add-text-properties (- f1
2) f1
770 (list 'display org-narrow-column-arrow
)
772 ;; Get the maximum width for each column
773 (push (apply 'max
(or fmax
1) 1 (mapcar 'org-string-width column
))
775 ;; Get the fraction of numbers, to decide about alignment of the column
777 (push (equal (downcase falign1
) "r") typenums
)
778 (setq cnt
0 frac
0.0)
779 (loop for x in column do
782 (setq frac
( / (+ (* frac cnt
)
783 (if (string-match org-table-number-regexp x
) 1 0))
784 (setq cnt
(1+ cnt
))))))
785 (push (>= frac org-table-number-fraction
) typenums
)))
786 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
788 ;; Store the alignment of this table, for later editing of single fields
789 (setq org-table-last-alignment typenums
790 org-table-last-column-widths lengths
)
792 ;; With invisible characters, `format' does not get the field width right
793 ;; So we need to make these fields wide by hand.
794 (when (or links emph raise
)
795 (loop for i from
0 upto
(1- maxfields
) do
796 (setq len
(nth i lengths
))
797 (loop for j from
0 upto
(1- (length fields
)) do
798 (setq c
(nthcdr i
(car (nthcdr j fields
))))
799 (if (and (stringp (car c
))
800 (or (text-property-any 0 (length (car c
))
801 'invisible
'org-link
(car c
))
802 (text-property-any 0 (length (car c
))
803 'org-dwidth t
(car c
)))
804 (< (org-string-width (car c
)) len
))
806 (setq space
(make-string (- len
(org-string-width (car c
))) ?\
))
807 (setcar c
(if (nth i typenums
)
808 (concat space
(car c
))
809 (concat (car c
) space
))))))))
811 ;; Compute the formats needed for output of the table
812 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
813 (while (setq l
(pop lengths
))
814 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
815 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
816 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
817 (setq rfmt
(concat rfmt
"\n")
818 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
822 (if l
(apply 'format rfmt
823 (append (pop fields
) emptystrings
))
826 (move-marker org-table-aligned-begin-marker
(point))
828 ;; Replace the old one
829 (delete-region (point) end
)
830 (move-marker end nil
)
831 (move-marker org-table-aligned-end-marker
(point))
832 (when (and orgtbl-mode
(not (eq major-mode
'org-mode
)))
833 (goto-char org-table-aligned-begin-marker
)
834 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
835 ;; Try to move to the old location
836 (org-goto-line winstartline
)
837 (setq winstart
(point-at-bol))
838 (org-goto-line linepos
)
839 (set-window-start (selected-window) winstart
'noforce
)
840 (org-table-goto-column colpos
)
841 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
842 (setq org-table-may-need-update nil
)
845 (defun org-table-begin (&optional table-type
)
846 "Find the beginning of the table and return its position.
847 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
849 (if (not (re-search-backward
850 (if table-type org-table-any-border-regexp
851 org-table-border-regexp
)
853 (progn (goto-char (point-min)) (point))
854 (goto-char (match-beginning 0))
855 (beginning-of-line 2)
858 (defun org-table-end (&optional table-type
)
859 "Find the end of the table and return its position.
860 With argument TABLE-TYPE, go to the end of a table.el-type table."
862 (if (not (re-search-forward
863 (if table-type org-table-any-border-regexp
864 org-table-border-regexp
)
866 (goto-char (point-max))
867 (goto-char (match-beginning 0)))
870 (defun org-table-justify-field-maybe (&optional new
)
871 "Justify the current field, text to left, number to right.
872 Optional argument NEW may specify text to replace the current field content."
874 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
875 ((org-at-table-hline-p))
877 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
879 (< (point) org-table-aligned-begin-marker
)
880 (>= (point) org-table-aligned-end-marker
)))
881 ;; This is not the same table, force a full re-align
882 (setq org-table-may-need-update t
))
883 (t ;; realign the current field, based on previous full realign
884 (let* ((pos (point)) s
885 (col (org-table-current-column))
886 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
889 (skip-chars-backward "^|\n")
890 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
892 (setq s
(match-string 1)
894 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
895 e
(not (= (match-beginning 2) (match-end 2))))
896 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
897 l
(if e
"|" (setq org-table-may-need-update t
) ""))
900 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
901 (setq n
(format f new
))
902 (setq n
(concat new
"|") org-table-may-need-update t
)))
903 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
905 (let (org-table-may-need-update)
906 (replace-match n t t
))))
907 (setq org-table-may-need-update t
))
910 (defun org-table-next-field ()
911 "Go to the next field in the current table, creating new lines as needed.
912 Before doing so, re-align the table if necessary."
914 (org-table-maybe-eval-formula)
915 (org-table-maybe-recalculate-line)
916 (if (and org-table-automatic-realign
917 org-table-may-need-update
)
919 (let ((end (org-table-end)))
920 (if (org-at-table-hline-p)
924 (re-search-forward "|" end
)
925 (if (looking-at "[ \t]*$")
926 (re-search-forward "|" end
))
927 (if (and (looking-at "-")
928 org-table-tab-jumps-over-hlines
929 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
930 (goto-char (match-beginning 1)))
933 (beginning-of-line 0)
934 (org-table-insert-row 'below
))
935 (if (looking-at " ") (forward-char 1))))
937 (org-table-insert-row 'below
)))))
939 (defun org-table-previous-field ()
940 "Go to the previous field in the table.
941 Before doing so, re-align the table if necessary."
943 (org-table-justify-field-maybe)
944 (org-table-maybe-recalculate-line)
945 (if (and org-table-automatic-realign
946 org-table-may-need-update
)
948 (if (org-at-table-hline-p)
952 (re-search-backward "|" (org-table-begin))
953 (re-search-backward "|" (org-table-begin)))
954 (error (error "Cannot move to previous table field")))
955 (while (looking-at "|\\(-\\|[ \t]*$\\)")
956 (re-search-backward "|" (org-table-begin)))
957 (if (looking-at "| ?")
958 (goto-char (match-end 0))))
960 (defun org-table-beginning-of-field (&optional n
)
961 "Move to the end of the current table field.
962 If already at or after the end, move to the end of the next table field.
963 With numeric argument N, move N-1 fields forward first."
968 (org-table-previous-field))
969 (if (not (re-search-backward "|" (point-at-bol 0) t
))
970 (error "No more table fields before the current")
971 (goto-char (match-end 0))
972 (and (looking-at " ") (forward-char 1)))
973 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
975 (defun org-table-end-of-field (&optional n
)
976 "Move to the beginning of the current table field.
977 If already at or before the beginning, move to the beginning of the
979 With numeric argument N, move N-1 fields backward first."
984 (org-table-next-field))
985 (when (re-search-forward "|" (point-at-eol 1) t
)
987 (skip-chars-backward " ")
988 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
990 (if (<= (point) pos
) (org-table-end-of-field 2))))
992 (defun org-table-next-row ()
993 "Go to the next row (same column) in the current table.
994 Before doing so, re-align the table if necessary."
996 (org-table-maybe-eval-formula)
997 (org-table-maybe-recalculate-line)
998 (if (or (looking-at "[ \t]*$")
999 (save-excursion (skip-chars-backward " \t") (bolp)))
1001 (if (and org-table-automatic-realign
1002 org-table-may-need-update
)
1004 (let ((col (org-table-current-column)))
1005 (beginning-of-line 2)
1006 (if (or (not (org-at-table-p))
1007 (org-at-table-hline-p))
1009 (beginning-of-line 0)
1010 (org-table-insert-row 'below
)))
1011 (org-table-goto-column col
)
1012 (skip-chars-backward "^|\n\r")
1013 (if (looking-at " ") (forward-char 1)))))
1015 (defun org-table-copy-down (n)
1016 "Copy a field down in the current column.
1017 If the field at the cursor is empty, copy into it the content of
1018 the nearest non-empty field above. With argument N, use the Nth
1019 non-empty field. If the current field is not empty, it is copied
1020 down to the next row, and the cursor is moved with it.
1021 Therefore, repeating this command causes the column to be filled
1023 If the variable `org-table-copy-increment' is non-nil and the
1024 field is an integer or a timestamp, it will be incremented while
1025 copying. In the case of a timestamp, increment by one day."
1027 (let* ((colpos (org-table-current-column))
1028 (col (current-column))
1029 (field (org-table-get-field))
1030 (non-empty (string-match "[^ \t]" field
))
1031 (beg (org-table-begin))
1034 (org-table-check-inside-data-field)
1037 (setq txt
(org-trim field
))
1038 (org-table-next-row)
1039 (org-table-blank-field))
1043 (while (progn (beginning-of-line 1)
1044 (re-search-backward org-table-dataline-regexp
1046 (org-table-goto-column colpos t
)
1047 (if (and (looking-at
1048 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1049 (<= (setq n
(1- n
)) 0))
1050 (throw 'exit
(match-string 1))))))))
1053 (if (and org-table-copy-increment
1054 (not (equal orig-n
0))
1055 (string-match "^[0-9]+$" txt
)
1056 (< (string-to-number txt
) 100000000))
1057 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
1059 (org-move-to-column col
)
1060 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1061 (org-timestamp-up-day)
1062 (org-table-maybe-recalculate-line))
1064 (org-move-to-column col
))
1065 (error "No non-empty field found"))))
1067 (defun org-table-check-inside-data-field (&optional noerror
)
1068 "Is point inside a table data field?
1069 I.e. not on a hline or before the first or after the last column?
1070 This actually throws an error, so it aborts the current command."
1071 (if (or (not (org-at-table-p))
1072 (= (org-table-current-column) 0)
1073 (org-at-table-hline-p)
1074 (looking-at "[ \t]*$"))
1077 (error "Not in table data field"))
1080 (defvar org-table-clip nil
1081 "Clipboard for table regions.")
1083 (defun org-table-get (line column
)
1084 "Get the field in table line LINE, column COLUMN.
1085 If LINE is larger than the number of data lines in the table, the function
1086 returns nil. However, if COLUMN is too large, we will simply return an
1088 If LINE is nil, use the current line.
1089 If column is nil, use the current column."
1090 (setq column
(or column
(org-table-current-column)))
1092 (and (or (not line
) (org-table-goto-line line
))
1093 (org-trim (org-table-get-field column
)))))
1095 (defun org-table-put (line column value
&optional align
)
1096 "Put VALUE into line LINE, column COLUMN.
1097 When ALIGN is set, also realign the table."
1098 (setq column
(or column
(org-table-current-column)))
1099 (prog1 (save-excursion
1100 (and (or (not line
) (org-table-goto-line line
))
1101 (progn (org-table-goto-column column nil
'force
) t
)
1102 (org-table-get-field column value
)))
1103 (and align
(org-table-align))))
1105 (defun org-table-current-line ()
1106 "Return the index of the current data line."
1107 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1109 (goto-char (org-table-begin))
1110 (while (and (re-search-forward org-table-dataline-regexp end t
)
1112 (< (point-at-eol) pos
))))
1115 (defun org-table-goto-line (N)
1116 "Go to the Nth data line in the current table.
1117 Return t when the line exists, nil if it does not exist."
1118 (goto-char (org-table-begin))
1119 (let ((end (org-table-end)) (cnt 0))
1120 (while (and (re-search-forward org-table-dataline-regexp end t
)
1121 (< (setq cnt
(1+ cnt
)) N
)))
1124 (defun org-table-blank-field ()
1125 "Blank the current table field or active region."
1127 (org-table-check-inside-data-field)
1128 (if (and (org-called-interactively-p 'any
) (org-region-active-p))
1129 (let (org-table-clip)
1130 (org-table-cut-region (region-beginning) (region-end)))
1131 (skip-chars-backward "^|")
1133 (if (looking-at "|[^|\n]+")
1134 (let* ((pos (match-beginning 0))
1135 (match (match-string 0))
1136 (len (org-string-width match
)))
1137 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1138 (goto-char (+ 2 pos
))
1139 (substring match
1)))))
1141 (defun org-table-get-field (&optional n replace
)
1142 "Return the value of the field in column N of current row.
1143 N defaults to current field.
1144 If REPLACE is a string, replace field with this value. The return value
1145 is always the old value."
1146 (and n
(org-table-goto-column n
))
1147 (skip-chars-backward "^|\n")
1149 (if (looking-at "|[^|\r\n]*")
1150 (let* ((pos (match-beginning 0))
1151 (val (buffer-substring (1+ pos
) (match-end 0))))
1153 (replace-match (concat "|" (if (equal replace
"") " " replace
))
1155 (goto-char (min (point-at-eol) (+ 2 pos
)))
1157 (forward-char 1) ""))
1159 (defun org-table-field-info (arg)
1160 "Show info about the current field, and highlight any reference at point."
1162 (org-table-get-specials)
1164 (let* ((pos (point))
1165 (col (org-table-current-column))
1166 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1167 (name (car (rassoc (list (org-current-line) col
)
1168 org-table-named-field-locations
)))
1169 (eql (org-table-expand-lhs-ranges
1172 (cons (org-table-formula-handle-first/last-rc
1174 (org-table-get-stored-formulas))))
1175 (dline (org-table-current-dline))
1176 (ref (format "@%d$%d" dline col
))
1177 (ref1 (org-table-convert-refs-to-an ref
))
1178 (fequation (or (assoc name eql
) (assoc ref eql
)))
1179 (cequation (assoc (int-to-string col
) eql
))
1180 (eqn (or fequation cequation
)))
1181 (if (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))
1182 (setq eqn
(get-text-property 0 :orig-eqn
(car eqn
))))
1185 (org-table-show-reference 'local
)
1187 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1189 (if cname
(concat " or $" cname
) "")
1191 (if name
(concat " or $" name
) "")
1192 ;; FIXME: formula info not correct if special table line
1194 (concat ", formula: "
1195 (org-table-formula-to-user
1197 (if (string-match "^[$@]"(car eqn
)) "" "$")
1198 (car eqn
) "=" (cdr eqn
))))
1201 (defun org-table-current-column ()
1202 "Find out which column we are in."
1204 (if (org-called-interactively-p 'any
) (org-table-check-inside-data-field))
1206 (let ((cnt 0) (pos (point)))
1207 (beginning-of-line 1)
1208 (while (search-forward "|" pos t
)
1209 (setq cnt
(1+ cnt
)))
1210 (when (org-called-interactively-p 'interactive
)
1211 (message "In table column %d" cnt
))
1214 (defun org-table-current-dline ()
1215 "Find out what table data line we are in.
1216 Only data lines count for this."
1218 (when (org-called-interactively-p 'any
)
1219 (org-table-check-inside-data-field))
1221 (let ((cnt 0) (pos (point)))
1222 (goto-char (org-table-begin))
1223 (while (<= (point) pos
)
1224 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1225 (beginning-of-line 2))
1226 (when (org-called-interactively-p 'any
)
1227 (message "This is table line %d" cnt
))
1230 (defun org-table-goto-column (n &optional on-delim force
)
1231 "Move the cursor to the Nth column in the current table line.
1232 With optional argument ON-DELIM, stop with point before the left delimiter
1234 If there are less than N fields, just go to after the last delimiter.
1235 However, when FORCE is non-nil, create new columns if necessary."
1237 (beginning-of-line 1)
1239 (while (and (> (setq n
(1- n
)) -
1)
1240 (or (search-forward "|" (point-at-eol) t
)
1242 (progn (end-of-line 1)
1243 (skip-chars-backward "^|")
1246 (when (and force
(not (looking-at ".*|")))
1247 (save-excursion (end-of-line 1) (insert " | ")))
1250 (if (looking-at " ") (forward-char 1)))))
1252 (defun org-table-insert-column ()
1253 "Insert a new column into the table."
1255 (if (not (org-at-table-p))
1256 (error "Not at a table"))
1257 (org-table-find-dataline)
1258 (let* ((col (max 1 (org-table-current-column)))
1259 (beg (org-table-begin))
1260 (end (org-table-end))
1261 ;; Current cursor position
1262 (linepos (org-current-line))
1265 (while (< (point) end
)
1266 (if (org-at-table-hline-p)
1268 (org-table-goto-column col t
)
1270 (beginning-of-line 2))
1271 (move-marker end nil
)
1272 (org-goto-line linepos
)
1273 (org-table-goto-column colpos
)
1275 (when (or (not org-table-fix-formulas-confirm
)
1276 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1277 (org-table-fix-formulas "$" nil
(1- col
) 1)
1278 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1280 (defun org-table-find-dataline ()
1281 "Find a data line in the current table, which is needed for column commands."
1282 (if (and (org-at-table-p)
1283 (not (org-at-table-hline-p)))
1285 (let ((col (current-column))
1286 (end (org-table-end)))
1287 (org-move-to-column col
)
1288 (while (and (< (point) end
)
1289 (or (not (= (current-column) col
))
1290 (org-at-table-hline-p)))
1291 (beginning-of-line 2)
1292 (org-move-to-column col
))
1293 (if (and (org-at-table-p)
1294 (not (org-at-table-hline-p)))
1297 "Please position cursor in a data line for column operations")))))
1299 (defun org-table-line-to-dline (line &optional above
)
1300 "Turn a buffer line number into a data line number.
1301 If there is no data line in this line, return nil.
1302 If there is no matchin dline (most likely te refrence was a hline), the
1303 first dline below it is used. When ABOVE is non-nil, the one above is used."
1305 (let ((ll (length org-table-dlines
))
1311 (if (<= (aref org-table-dlines i
) line
)
1316 (if (>= (aref org-table-dlines i
) line
)
1321 (defun org-table-delete-column ()
1322 "Delete a column from the table."
1324 (if (not (org-at-table-p))
1325 (error "Not at a table"))
1326 (org-table-find-dataline)
1327 (org-table-check-inside-data-field)
1328 (let* ((col (org-table-current-column))
1329 (beg (org-table-begin))
1330 (end (org-table-end))
1331 ;; Current cursor position
1332 (linepos (org-current-line))
1335 (while (< (point) end
)
1336 (if (org-at-table-hline-p)
1338 (org-table-goto-column col t
)
1339 (and (looking-at "|[^|\n]+|")
1340 (replace-match "|")))
1341 (beginning-of-line 2))
1342 (move-marker end nil
)
1343 (org-goto-line linepos
)
1344 (org-table-goto-column colpos
)
1346 (when (or (not org-table-fix-formulas-confirm
)
1347 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1348 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1350 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1353 (defun org-table-move-column-right ()
1354 "Move column to the right."
1356 (org-table-move-column nil
))
1357 (defun org-table-move-column-left ()
1358 "Move column to the left."
1360 (org-table-move-column 'left
))
1362 (defun org-table-move-column (&optional left
)
1363 "Move the current column to the right. With arg LEFT, move to the left."
1365 (if (not (org-at-table-p))
1366 (error "Not at a table"))
1367 (org-table-find-dataline)
1368 (org-table-check-inside-data-field)
1369 (let* ((col (org-table-current-column))
1370 (col1 (if left
(1- col
) col
))
1371 (beg (org-table-begin))
1372 (end (org-table-end))
1373 ;; Current cursor position
1374 (linepos (org-current-line))
1375 (colpos (if left
(1- col
) (1+ col
))))
1376 (if (and left
(= col
1))
1377 (error "Cannot move column further left"))
1378 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1379 (error "Cannot move column further right"))
1381 (while (< (point) end
)
1382 (if (org-at-table-hline-p)
1384 (org-table-goto-column col1 t
)
1385 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1386 (replace-match "|\\2|\\1|")))
1387 (beginning-of-line 2))
1388 (move-marker end nil
)
1389 (org-goto-line linepos
)
1390 (org-table-goto-column colpos
)
1392 (when (or (not org-table-fix-formulas-confirm
)
1393 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1394 (org-table-fix-formulas
1395 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1396 (cons (number-to-string colpos
) (number-to-string col
))))
1397 (org-table-fix-formulas
1398 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1399 (cons (number-to-string colpos
) (number-to-string col
)))))))
1401 (defun org-table-move-row-down ()
1402 "Move table row down."
1404 (org-table-move-row nil
))
1405 (defun org-table-move-row-up ()
1406 "Move table row up."
1408 (org-table-move-row 'up
))
1410 (defun org-table-move-row (&optional up
)
1411 "Move the current table line down. With arg UP, move it up."
1413 (let* ((col (current-column))
1415 (hline1p (save-excursion (beginning-of-line 1)
1416 (looking-at org-table-hline-regexp
)))
1417 (dline1 (org-table-current-dline))
1418 (dline2 (+ dline1
(if up -
1 1)))
1421 (beginning-of-line tonew
)
1422 (unless (org-at-table-p)
1424 (error "Cannot move row further"))
1425 (setq hline2p
(looking-at org-table-hline-regexp
))
1427 (beginning-of-line 1)
1429 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1430 (delete-region (point) (1+ (point-at-eol)))
1431 (beginning-of-line tonew
)
1433 (beginning-of-line 0)
1434 (org-move-to-column col
)
1435 (unless (or hline1p hline2p
1436 (not (or (not org-table-fix-formulas-confirm
)
1437 (funcall org-table-fix-formulas-confirm
1438 "Fix formulas? "))))
1439 (org-table-fix-formulas
1440 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1441 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1443 (defun org-table-insert-row (&optional arg
)
1444 "Insert a new row above the current line into the table.
1445 With prefix ARG, insert below the current line."
1447 (if (not (org-at-table-p))
1448 (error "Not at a table"))
1449 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1450 (new (org-table-clean-line line
)))
1451 ;; Fix the first field if necessary
1452 (if (string-match "^[ \t]*| *[#$] *|" line
)
1453 (setq new
(replace-match (match-string 0 line
) t t new
)))
1454 (beginning-of-line (if arg
2 1))
1455 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1456 (beginning-of-line 0)
1457 (re-search-forward "| ?" (point-at-eol) t
)
1458 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1460 (when (or (not org-table-fix-formulas-confirm
)
1461 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1462 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1464 (defun org-table-insert-hline (&optional above
)
1465 "Insert a horizontal-line below the current line into the table.
1466 With prefix ABOVE, insert above the current line."
1468 (if (not (org-at-table-p))
1469 (error "Not at a table"))
1470 (when (eobp) (insert "\n") (backward-char 1))
1471 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1473 (let ((line (org-table-clean-line
1474 (buffer-substring (point-at-bol) (point-at-eol))))
1475 (col (current-column)))
1476 (while (string-match "|\\( +\\)|" line
)
1477 (setq line
(replace-match
1478 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1479 ?-
) "|") t t line
)))
1480 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1481 (beginning-of-line (if above
1 2))
1483 (beginning-of-line (if above
1 -
1))
1484 (org-move-to-column col
)
1485 (and org-table-overlay-coordinates
(org-table-align))))
1487 (defun org-table-hline-and-move (&optional same-column
)
1488 "Insert a hline and move to the row below that line."
1490 (let ((col (org-table-current-column)))
1491 (org-table-maybe-eval-formula)
1492 (org-table-maybe-recalculate-line)
1493 (org-table-insert-hline)
1495 (if (looking-at "\n[ \t]*|-")
1496 (progn (insert "\n|") (org-table-align))
1497 (org-table-next-field))
1498 (if same-column
(org-table-goto-column col
))))
1500 (defun org-table-clean-line (s)
1501 "Convert a table line S into a string with only \"|\" and space.
1502 In particular, this does handle wide and invisible characters."
1503 (if (string-match "^[ \t]*|-" s
)
1504 ;; It's a hline, just map the characters
1505 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1506 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1507 (setq s
(replace-match
1508 (concat "|" (make-string (org-string-width (match-string 1 s
))
1513 (defun org-table-kill-row ()
1514 "Delete the current row or horizontal line from the table."
1516 (if (not (org-at-table-p))
1517 (error "Not at a table"))
1518 (let ((col (current-column))
1519 (dline (org-table-current-dline)))
1520 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1521 (if (not (org-at-table-p)) (beginning-of-line 0))
1522 (org-move-to-column col
)
1523 (when (or (not org-table-fix-formulas-confirm
)
1524 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1525 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1528 (defun org-table-sort-lines (with-case &optional sorting-type
)
1529 "Sort table lines according to the column at point.
1531 The position of point indicates the column to be used for
1532 sorting, and the range of lines is the range between the nearest
1533 horizontal separator lines, or the entire table of no such lines
1534 exist. If point is before the first column, you will be prompted
1535 for the sorting column. If there is an active region, the mark
1536 specifies the first line and the sorting column, while point
1537 should be in the last line to be included into the sorting.
1539 The command then prompts for the sorting type which can be
1540 alphabetically, numerically, or by time (as given in a time stamp
1541 in the field). Sorting in reverse order is also possible.
1543 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1545 If SORTING-TYPE is specified when this function is called from a Lisp
1546 program, no prompting will take place. SORTING-TYPE must be a character,
1547 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1548 should be done in reverse order."
1550 (let* ((thisline (org-current-line))
1551 (thiscol (org-table-current-column))
1552 beg end bcol ecol tend tbeg column lns pos
)
1553 (when (equal thiscol
0)
1554 (if (org-called-interactively-p 'any
)
1557 (read-string "Use column N for sorting: ")))
1559 (org-table-goto-column thiscol
))
1560 (org-table-check-inside-data-field)
1561 (if (org-region-active-p)
1563 (setq beg
(region-beginning) end
(region-end))
1565 (setq column
(org-table-current-column)
1568 (setq end
(point-at-bol 2)))
1569 (setq column
(org-table-current-column)
1571 tbeg
(org-table-begin)
1572 tend
(org-table-end))
1573 (if (re-search-backward org-table-hline-regexp tbeg t
)
1574 (setq beg
(point-at-bol 2))
1576 (setq beg
(point-at-bol 1)))
1578 (if (re-search-forward org-table-hline-regexp tend t
)
1579 (setq end
(point-at-bol 1))
1581 (setq end
(point-at-bol))))
1582 (setq beg
(move-marker (make-marker) beg
)
1583 end
(move-marker (make-marker) end
))
1586 (org-table-goto-column column
)
1587 (skip-chars-backward "^|")
1588 (setq bcol
(current-column))
1589 (org-table-goto-column (1+ column
))
1590 (skip-chars-backward "^|")
1591 (setq ecol
(1- (current-column)))
1592 (org-table-goto-column column
)
1593 (setq lns
(mapcar (lambda(x) (cons
1594 (org-sort-remove-invisible
1596 (org-split-string x
"[ \t]*|[ \t]*")))
1598 (org-split-string (buffer-substring beg end
) "\n")))
1599 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1600 (delete-region beg end
)
1601 (move-marker beg nil
)
1602 (move-marker end nil
)
1603 (insert (mapconcat 'cdr lns
"\n") "\n")
1604 (org-goto-line thisline
)
1605 (org-table-goto-column thiscol
)
1606 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1609 (defun org-table-cut-region (beg end
)
1610 "Copy region in table to the clipboard and blank all relevant fields.
1611 If there is no active region, use just the field at point."
1613 (if (org-region-active-p) (region-beginning) (point))
1614 (if (org-region-active-p) (region-end) (point))))
1615 (org-table-copy-region beg end
'cut
))
1617 (defun org-table-copy-region (beg end
&optional cut
)
1618 "Copy rectangular region in table to clipboard.
1619 A special clipboard is used which can only be accessed
1620 with `org-table-paste-rectangle'."
1622 (if (org-region-active-p) (region-beginning) (point))
1623 (if (org-region-active-p) (region-end) (point))
1624 current-prefix-arg
))
1625 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1627 (rpl (if cut
" " nil
)))
1629 (org-table-check-inside-data-field)
1630 (setq l01
(org-current-line)
1631 c01
(org-table-current-column))
1633 (org-table-check-inside-data-field)
1634 (setq l02
(org-current-line)
1635 c02
(org-table-current-column))
1636 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1637 c1
(min c01 c02
) c2
(max c01 c02
))
1641 (if (> l1 l2
) (throw 'exit t
))
1643 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1644 (setq cols nil ic1 c1 ic2 c2
)
1645 (while (< ic1
(1+ ic2
))
1646 (push (org-table-get-field ic1 rpl
) cols
)
1647 (setq ic1
(1+ ic1
)))
1648 (push (nreverse cols
) region
)
1649 (setq l1
(1+ l1
)))))
1650 (setq org-table-clip
(nreverse region
))
1651 (if cut
(org-table-align))
1654 (defun org-table-paste-rectangle ()
1655 "Paste a rectangular region into a table.
1656 The upper right corner ends up in the current field. All involved fields
1657 will be overwritten. If the rectangle does not fit into the present table,
1658 the table is enlarged as needed. The process ignores horizontal separator
1661 (unless (and org-table-clip
(listp org-table-clip
))
1662 (error "First cut/copy a region to paste!"))
1663 (org-table-check-inside-data-field)
1664 (let* ((clip org-table-clip
)
1665 (line (org-current-line))
1666 (col (org-table-current-column))
1667 (org-enable-table-editor t
)
1668 (org-table-automatic-realign nil
)
1670 (while (setq cols
(pop clip
))
1671 (while (org-at-table-hline-p) (beginning-of-line 2))
1672 (if (not (org-at-table-p))
1673 (progn (end-of-line 0) (org-table-next-field)))
1675 (while (setq field
(pop cols
))
1676 (org-table-goto-column c nil
'force
)
1677 (org-table-get-field nil field
)
1679 (beginning-of-line 2))
1680 (org-goto-line line
)
1681 (org-table-goto-column col
)
1684 (defun org-table-convert ()
1685 "Convert from `org-mode' table to table.el and back.
1686 Obviously, this only works within limits. When an Org-mode table is
1687 converted to table.el, all horizontal separator lines get lost, because
1688 table.el uses these as cell boundaries and has no notion of horizontal lines.
1689 A table.el table can be converted to an Org-mode table only if it does not
1690 do row or column spanning. Multiline cells will become multiple cells.
1691 Beware, Org-mode does not test if the table can be successfully converted - it
1692 blindly applies a recipe that works for simple tables."
1695 (if (org-at-table.el-p
)
1696 ;; convert to Org-mode table
1697 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1698 (end (move-marker (make-marker) (org-table-end t
))))
1699 (table-unrecognize-region beg end
)
1701 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1704 (if (org-at-table-p)
1705 ;; convert to table.el table
1706 (let ((beg (move-marker (make-marker) (org-table-begin)))
1707 (end (move-marker (make-marker) (org-table-end))))
1708 ;; first, get rid of all horizontal lines
1710 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1712 ;; insert a hline before first
1714 (org-table-insert-hline 'above
)
1715 (beginning-of-line -
1)
1716 ;; insert a hline after each line
1717 (while (progn (beginning-of-line 3) (< (point) end
))
1718 (org-table-insert-hline))
1720 (setq end
(move-marker end
(org-table-end)))
1721 ;; replace "+" at beginning and ending of hlines
1722 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1723 (replace-match "\\1+-"))
1725 (while (re-search-forward "-|[ \t]*$" end t
)
1726 (replace-match "-+"))
1729 (defun org-table-transpose-table-at-point ()
1730 "Transpose orgmode table at point and eliminate hlines.
1738 will be transposed as
1745 Note that horizontal lines disappeared."
1748 (apply #'mapcar
* #'list
1749 ;; remove 'hline from list
1750 (remove-if-not 'listp
1751 ;; signals error if not table
1752 (org-table-to-lisp)))))
1753 (delete-region (org-table-begin) (org-table-end))
1754 (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1758 (defun org-table-wrap-region (arg)
1759 "Wrap several fields in a column like a paragraph.
1760 This is useful if you'd like to spread the contents of a field over several
1761 lines, in order to keep the table compact.
1763 If there is an active region, and both point and mark are in the same column,
1764 the text in the column is wrapped to minimum width for the given number of
1765 lines. Generally, this makes the table more compact. A prefix ARG may be
1766 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1767 formats the selected text to two lines. If the region was longer than two
1768 lines, the remaining lines remain empty. A negative prefix argument reduces
1769 the current number of lines by that amount. The wrapped text is pasted back
1770 into the table. If you formatted it to more lines than it was before, fields
1771 further down in the table get overwritten - so you might need to make space in
1774 If there is no region, the current field is split at the cursor position and
1775 the text fragment to the right of the cursor is prepended to the field one
1778 If there is no region, but you specify a prefix ARG, the current field gets
1779 blank, and the content is appended to the field above."
1781 (org-table-check-inside-data-field)
1782 (if (org-region-active-p)
1783 ;; There is a region: fill as a paragraph
1784 (let* ((beg (region-beginning))
1785 (cline (save-excursion (goto-char beg
) (org-current-line)))
1786 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1788 (org-table-cut-region (region-beginning) (region-end))
1789 (if (> (length (car org-table-clip
)) 1)
1790 (error "Region must be limited to single column"))
1791 (setq nlines
(if arg
1793 (+ (length org-table-clip
) arg
)
1795 (length org-table-clip
)))
1796 (setq org-table-clip
1797 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1799 (org-goto-line cline
)
1800 (org-table-goto-column ccol
)
1801 (org-table-paste-rectangle))
1802 ;; No region, split the current field at point
1803 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1804 (skip-chars-forward "^\r\n|"))
1806 ;; combine with field above
1807 (let ((s (org-table-blank-field))
1808 (col (org-table-current-column)))
1809 (beginning-of-line 0)
1810 (while (org-at-table-hline-p) (beginning-of-line 0))
1811 (org-table-goto-column col
)
1812 (skip-chars-forward "^|")
1813 (skip-chars-backward " ")
1814 (insert " " (org-trim s
))
1817 (if (looking-at "\\([^|]+\\)+|")
1818 (let ((s (match-string 1)))
1819 (replace-match " |")
1820 (goto-char (match-beginning 0))
1821 (org-table-next-row)
1822 (insert (org-trim s
) " ")
1824 (org-table-next-row)))))
1826 (defvar org-field-marker nil
)
1828 (defun org-table-edit-field (arg)
1829 "Edit table field in a different window.
1830 This is mainly useful for fields that contain hidden parts.
1831 When called with a \\[universal-argument] prefix, just make the full field visible so that
1832 it can be edited in place."
1836 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
1838 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1839 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1840 (remove-text-properties b e
'(org-cwidth t invisible t
1841 display t intangible t
))
1842 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1843 (font-lock-fontify-block))))
1845 (let ((pos (move-marker (make-marker) (point)))
1847 (if (eq org-table-use-standard-references t
)
1848 (concat (org-number-to-letters (org-table-current-column))
1849 (int-to-string (org-table-current-dline)))
1850 (concat "@" (int-to-string (org-table-current-dline))
1851 "$" (int-to-string (org-table-current-column)))))
1852 (field (org-table-get-field))
1853 (cw (current-window-configuration))
1856 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
1857 (when (and (local-variable-p 'org-field-marker
)
1858 (markerp org-field-marker
))
1859 (move-marker org-field-marker nil
))
1861 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
1862 (let ((org-inhibit-startup t
)) (org-mode))
1864 (setq truncate-lines nil
)
1866 (goto-char (setq p
(point-max)))
1867 (insert (org-trim field
))
1868 (remove-text-properties p
(point-max)
1869 '(invisible t org-cwidth t display t
1872 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1873 (org-set-local 'org-window-configuration cw
)
1874 (org-set-local 'org-field-marker pos
)
1875 (message "Edit and finish with C-c C-c")))))
1877 (defun org-table-finish-edit-field ()
1878 "Finish editing a table data field.
1879 Remove all newline characters, insert the result into the table, realign
1880 the table and kill the editing buffer."
1881 (let ((pos org-field-marker
)
1882 (cw org-window-configuration
)
1883 (cb (current-buffer))
1885 (goto-char (point-min))
1886 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1887 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1888 (replace-match " "))
1889 (setq text
(org-trim (buffer-string)))
1890 (set-window-configuration cw
)
1892 (select-window (get-buffer-window (marker-buffer pos
)))
1894 (move-marker pos nil
)
1895 (org-table-check-inside-data-field)
1896 (org-table-get-field nil text
)
1898 (message "New field value inserted")))
1900 (define-minor-mode org-table-follow-field-mode
1901 "Minor mode to make the table field editor window follow the cursor.
1902 When this mode is active, the field editor window will always show the
1903 current field. The mode exits automatically when the cursor leaves the
1904 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
1905 nil
" TblFollow" nil
1906 (if org-table-follow-field-mode
1907 (org-add-hook 'post-command-hook
'org-table-follow-fields-with-editor
1909 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
1910 (let* ((buf (get-buffer "*Org Table Edit Field*"))
1911 (win (and buf
(get-buffer-window buf
))))
1912 (when win
(delete-window win
))
1914 (with-current-buffer buf
1915 (move-marker org-field-marker nil
))
1916 (kill-buffer buf
)))))
1918 (defun org-table-follow-fields-with-editor ()
1919 (if (and org-table-exit-follow-field-mode-when-leaving-table
1920 (not (org-at-table-p)))
1921 ;; We have left the table, exit the follow mode
1922 (org-table-follow-field-mode -
1)
1923 (when (org-table-check-inside-data-field 'noerror
)
1924 (let ((win (selected-window)))
1925 (org-table-edit-field nil
)
1926 (org-fit-window-to-buffer)
1927 (select-window win
)))))
1929 (defvar org-timecnt
) ; dynamically scoped parameter
1931 (defun org-table-sum (&optional beg end nlast
)
1932 "Sum numbers in region of current table column.
1933 The result will be displayed in the echo area, and will be available
1934 as kill to be inserted with \\[yank].
1936 If there is an active region, it is interpreted as a rectangle and all
1937 numbers in that rectangle will be summed. If there is no active
1938 region and point is located in a table column, sum all numbers in that
1941 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1942 numbers are assumed to be times as well (in decimal hours) and the
1943 numbers are added as such.
1945 If NLAST is a number, only the NLAST fields will actually be summed."
1948 (let (col (org-timecnt 0) diff h m s org-table-clip
)
1950 ((and beg end
)) ; beg and end given explicitly
1951 ((org-region-active-p)
1952 (setq beg
(region-beginning) end
(region-end)))
1954 (setq col
(org-table-current-column))
1955 (goto-char (org-table-begin))
1956 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
1957 (error "No table data"))
1958 (org-table-goto-column col
)
1960 (goto-char (org-table-end))
1961 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
1962 (error "No table data"))
1963 (org-table-goto-column col
)
1964 (setq end
(point))))
1965 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
1966 (items1 (cond ((not nlast
) items
)
1967 ((>= nlast
(length items
)) items
)
1968 (t (setq items
(reverse items
))
1969 (setcdr (nthcdr (1- nlast
) items
) nil
)
1971 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
1973 (res (apply '+ numbers
))
1974 (sres (if (= org-timecnt
0)
1975 (number-to-string res
)
1976 (setq diff
(* 3600 res
)
1977 h
(floor (/ diff
3600)) diff
(mod diff
3600)
1978 m
(floor (/ diff
60)) diff
(mod diff
60)
1980 (format "%d:%02d:%02d" h m s
))))
1982 (if (org-called-interactively-p 'interactive
)
1984 (substitute-command-keys
1985 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
1986 (length numbers
) sres
))))
1989 (defun org-table-get-number-for-summing (s)
1991 (if (string-match "^ *|? *" s
)
1992 (setq s
(replace-match "" nil nil s
)))
1993 (if (string-match " *|? *$" s
)
1994 (setq s
(replace-match "" nil nil s
)))
1995 (setq n
(string-to-number s
))
1997 ((and (string-match "0" s
)
1998 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
1999 ((string-match "\\`[ \t]+\\'" s
) nil
)
2000 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2001 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2002 (m (string-to-number (or (match-string 2 s
) "0")))
2003 (s (string-to-number (or (match-string 4 s
) "0"))))
2004 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2005 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2009 (defun org-table-current-field-formula (&optional key noerror
)
2010 "Return the formula active for the current field.
2011 Assumes that specials are in place.
2012 If KEY is given, return the key to this formula.
2013 Otherwise return the formula preceded with \"=\" or \":=\"."
2014 (let* ((name (car (rassoc (list (org-current-line)
2015 (org-table-current-column))
2016 org-table-named-field-locations
)))
2017 (col (org-table-current-column))
2018 (scol (int-to-string col
))
2019 (ref (format "@%d$%d" (org-table-current-dline) col
))
2020 (stored-list (org-table-get-stored-formulas noerror
))
2021 (ass (or (assoc name stored-list
)
2022 (assoc ref stored-list
)
2023 (assoc scol stored-list
))))
2026 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
2029 (defun org-table-get-formula (&optional equation named
)
2030 "Read a formula from the minibuffer, offer stored formula as default.
2031 When NAMED is non-nil, look for a named equation."
2032 (let* ((stored-list (org-table-get-stored-formulas))
2033 (name (car (rassoc (list (org-current-line)
2034 (org-table-current-column))
2035 org-table-named-field-locations
)))
2036 (ref (format "@%d$%d" (org-table-current-dline)
2037 (org-table-current-column)))
2038 (refass (assoc ref stored-list
))
2039 (nameass (assoc name stored-list
))
2041 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
2044 (int-to-string (org-table-current-column))))
2045 (dummy (and (or nameass refass
) (not named
)
2046 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2048 (name (or name ref
))
2049 (org-table-may-need-update nil
)
2050 (stored (cdr (assoc scol stored-list
)))
2052 ((and stored equation
(string-match "^ *=? *$" equation
))
2056 (t (org-table-formula-from-user
2058 (org-table-formula-to-user
2059 (format "%s formula %s%s="
2060 (if named
"Field" "Column")
2061 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
2063 (if stored
(org-table-formula-to-user stored
) "")
2064 'org-table-formula-history
2067 (when (not (string-match "\\S-" eq
))
2069 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2070 (org-table-store-formulas stored-list
)
2071 (error "Formula removed"))
2072 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2073 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2074 (if (and name
(not named
))
2075 ;; We set the column equation, delete the named one.
2076 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2079 (setcdr (assoc scol stored-list
) eq
)
2080 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2081 (if (or mustsave
(not (equal stored eq
)))
2082 (org-table-store-formulas stored-list
))
2085 (defun org-table-store-formulas (alist)
2086 "Store the list of formulas below the current table."
2087 (setq alist
(sort alist
'org-table-formula-less-p
))
2089 (goto-char (org-table-end))
2090 (if (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM:\\(.*\n?\\)")
2092 ;; don't overwrite TBLFM, we might use text properties to store stuff
2093 (goto-char (match-beginning 2))
2094 (delete-region (match-beginning 2) (match-end 0)))
2095 (org-indent-line-function)
2096 (insert "#+TBLFM:"))
2098 (mapconcat (lambda (x)
2100 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2101 (car x
) "=" (cdr x
)))
2105 (defsubst org-table-formula-make-cmp-string
(a)
2106 (when (string-match "\\`$[<>]" a
)
2107 (let ((arrow (string-to-char (substring a
1))))
2108 ;; Fake a high number to make sure this is sorted at the end.
2109 (setq a
(org-table-formula-handle-first/last-rc a
))
2110 (setq a
(format "$%d" (+ 10000
2111 (if (= arrow ?
<) -
1000 0)
2112 (string-to-number (substring a
1)))))))
2114 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2118 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2120 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2122 (concat "@@" (match-string 5 a
))))))
2124 (defun org-table-formula-less-p (a b
)
2125 "Compare two formulas for sorting."
2126 (let ((as (org-table-formula-make-cmp-string (car a
)))
2127 (bs (org-table-formula-make-cmp-string (car b
))))
2128 (and as bs
(string< as bs
))))
2130 (defun org-table-get-stored-formulas (&optional noerror
)
2131 "Return an alist with the stored formulas directly after current table."
2133 (let (scol eq eq-alist strings string seen
)
2135 (goto-char (org-table-end))
2136 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
2137 (setq strings
(org-split-string (org-match-string-no-properties 2)
2139 (while (setq string
(pop strings
))
2140 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2141 (setq scol
(if (match-end 2)
2142 (match-string 2 string
)
2143 (match-string 1 string
))
2144 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2145 (concat "$" scol
) scol
)
2146 eq
(match-string 3 string
)
2147 eq-alist
(cons (cons scol eq
) eq-alist
))
2148 (if (member scol seen
)
2151 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2154 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2155 (push scol seen
))))))
2156 (nreverse eq-alist
)))
2158 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2159 "Modify the equations after the table structure has been edited.
2160 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2161 For all numbers larger than LIMIT, shift them by DELTA."
2163 (goto-char (org-table-end))
2164 (when (looking-at "[ \t]*#\\+TBLFM:")
2165 (let ((re (concat key
"\\([0-9]+\\)"))
2168 (if (or (equal key
"$") (equal key
"$LR"))
2169 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2170 (regexp-quote key
) remove
)
2171 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2174 (while (re-search-forward re2
(point-at-eol) t
)
2175 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2176 (if (equal (char-before (match-beginning 0)) ?.
)
2177 (error "Change makes TBLFM term %s invalid. Use undo to recover."
2179 (replace-match "")))))
2180 (while (re-search-forward re
(point-at-eol) t
)
2181 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2182 (setq s
(match-string 1) n
(string-to-number s
))
2184 ((setq a
(assoc s replace
))
2185 (replace-match (concat key
(cdr a
)) t t
))
2186 ((and limit
(> n limit
))
2187 (replace-match (concat key
(int-to-string (+ n delta
)))
2190 (defun org-table-get-specials ()
2191 "Get the column names and local parameters for this table."
2193 (let ((beg (org-table-begin)) (end (org-table-end))
2194 names name fields fields1 field cnt
2195 c v l line col types dlines hlines last-dline
)
2196 (setq org-table-column-names nil
2197 org-table-local-parameters nil
2198 org-table-named-field-locations nil
2199 org-table-current-begin-line nil
2200 org-table-current-begin-pos nil
2201 org-table-current-line-types nil
2202 org-table-current-ncol
0)
2204 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2205 (setq names
(org-split-string (match-string 1) " *| *")
2207 (while (setq name
(pop names
))
2209 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name
)
2210 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2211 (setq org-table-column-names
(nreverse org-table-column-names
))
2212 (setq org-table-column-name-regexp
2213 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2215 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2216 (setq fields
(org-split-string (match-string 1) " *| *"))
2217 (while (setq field
(pop fields
))
2218 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2219 (push (cons (match-string 1 field
) (match-string 2 field
))
2220 org-table-local-parameters
))))
2222 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2223 (setq c
(match-string 1)
2224 fields
(org-split-string (match-string 2) " *| *"))
2226 (beginning-of-line (if (equal c
"_") 2 0))
2227 (setq line
(org-current-line) col
1)
2228 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2229 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2230 (while (and fields1
(setq field
(pop fields
)))
2231 (setq v
(pop fields1
) col
(1+ col
))
2232 (when (and (stringp field
) (stringp v
)
2233 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field
))
2234 (push (cons field v
) org-table-local-parameters
)
2235 (push (list field line col
) org-table-named-field-locations
))))
2236 ;; Analyse the line types
2238 (setq org-table-current-begin-line
(org-current-line)
2239 org-table-current-begin-pos
(point)
2240 l org-table-current-begin-line
)
2241 (while (looking-at "[ \t]*|\\(-\\)?")
2242 (push (if (match-end 1) 'hline
'dline
) types
)
2243 (if (match-end 1) (push l hlines
) (push l dlines
))
2244 (beginning-of-line 2)
2246 (push 'hline types
) ;; add an imaginary extra hline to the end
2247 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2248 last-dline
(car dlines
)
2249 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2250 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2251 (org-goto-line last-dline
)
2252 (let* ((l last-dline
)
2253 (fields (org-split-string
2254 (buffer-substring (point-at-bol) (point-at-eol))
2256 (nfields (length fields
))
2258 (setq org-table-current-ncol nfields
)
2259 (loop for i from
1 to nfields do
2260 (push (list (format "LR%d" i
) l i
) al
)
2261 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2262 (setq org-table-named-field-locations
2263 (append org-table-named-field-locations al
))
2264 (setq org-table-local-parameters
2265 (append org-table-local-parameters al2
))))))
2267 (defun org-table-maybe-eval-formula ()
2268 "Check if the current field starts with \"=\" or \":=\".
2269 If yes, store the formula and apply it."
2270 ;; We already know we are in a table. Get field will only return a formula
2271 ;; when appropriate. It might return a separator line, but no problem.
2272 (when org-table-formula-evaluate-inline
2273 (let* ((field (org-trim (or (org-table-get-field) "")))
2275 (when (string-match "^:?=\\(.*\\)" field
)
2276 (setq named
(equal (string-to-char field
) ?
:)
2277 eq
(match-string 1 field
))
2278 (if (or (fboundp 'calc-eval
)
2279 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2280 (org-table-eval-formula (if named
'(4) nil
)
2281 (org-table-formula-from-user eq
))
2282 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2284 (defvar org-recalc-commands nil
2285 "List of commands triggering the recalculation of a line.
2286 Will be filled automatically during use.")
2288 (defvar org-recalc-marks
2289 '((" " .
"Unmarked: no special line, no automatic recalculation")
2290 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2291 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2292 ("!" .
"Column name definition line. Reference in formula as $name.")
2293 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2294 ("_" .
"Names for values in row below this one.")
2295 ("^" .
"Names for values in row above this one.")))
2297 (defun org-table-rotate-recalc-marks (&optional newchar
)
2298 "Rotate the recalculation mark in the first column.
2299 If in any row, the first field is not consistent with a mark,
2300 insert a new column for the markers.
2301 When there is an active region, change all the lines in the region,
2302 after prompting for the marking character.
2303 After each change, a message will be displayed indicating the meaning
2306 (unless (org-at-table-p) (error "Not at a table"))
2307 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2308 (beg (org-table-begin))
2309 (end (org-table-end))
2310 (l (org-current-line))
2311 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2312 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2316 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2317 (col (org-table-current-column))
2318 (forcenew (car (assoc newchar org-recalc-marks
)))
2321 (message "Change region to what mark? Type # * ! $ or SPC: ")
2322 (setq newchar
(char-to-string (read-char-exclusive))
2323 forcenew
(car (assoc newchar org-recalc-marks
))))
2324 (if (and newchar
(not forcenew
))
2325 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2327 (if l1
(org-goto-line l1
))
2329 (beginning-of-line 1)
2330 (unless (looking-at org-table-dataline-regexp
)
2331 (error "Not at a table data line")))
2333 (org-table-goto-column 1)
2334 (org-table-insert-column)
2335 (org-table-goto-column (1+ col
)))
2336 (setq epos
(point-at-eol))
2338 (beginning-of-line 1)
2339 (org-table-get-field
2340 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2342 (setq new
(or forcenew
2343 (cadr (member (match-string 1) marks
))))
2349 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2350 (and (looking-at org-table-dataline-regexp
)
2351 (org-table-get-field 1 (concat " " new
" "))))
2352 (org-goto-line l1
)))
2353 (if (not (= epos
(point-at-eol))) (org-table-align))
2355 (and (org-called-interactively-p 'interactive
)
2356 (message "%s" (cdr (assoc new org-recalc-marks
))))))
2358 (defun org-table-maybe-recalculate-line ()
2359 "Recompute the current line if marked for it, and if we haven't just done it."
2361 (and org-table-allow-automatic-line-recalculation
2362 (not (and (memq last-command org-recalc-commands
)
2363 (equal org-last-recalc-line
(org-current-line))))
2364 (save-excursion (beginning-of-line 1)
2365 (looking-at org-table-auto-recalculate-regexp
))
2366 (org-table-recalculate) t
))
2369 (defsubst org-set-calc-mode
(var &optional value
)
2371 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2372 ("R" calc-angle-mode rad
)
2373 ("F" calc-prefer-frac t
)
2374 ("S" calc-symbolic-mode t
)))
2375 value
(nth 2 var
) var
(nth 1 var
)))
2376 (if (memq var modes
)
2377 (setcar (cdr (memq var modes
)) value
)
2378 (cons var
(cons value modes
)))
2381 (defun org-table-eval-formula (&optional arg equation
2382 suppress-align suppress-const
2383 suppress-store suppress-analysis
)
2384 "Replace the table field value at the cursor by the result of a calculation.
2386 This function makes use of Dave Gillespie's Calc package, in my view the
2387 most exciting program ever written for GNU Emacs. So you need to have Calc
2388 installed in order to use this function.
2390 In a table, this command replaces the value in the current field with the
2391 result of a formula. It also installs the formula as the \"current\" column
2392 formula, by storing it in a special line below the table. When called
2393 with a `C-u' prefix, the current field must be a named field, and the
2394 formula is installed as valid in only this specific field.
2396 When called with two `C-u' prefixes, insert the active equation
2397 for the field back into the current field, so that it can be
2398 edited there. This is useful in order to use \\[org-table-show-reference]
2399 to check the referenced fields.
2401 When called, the command first prompts for a formula, which is read in
2402 the minibuffer. Previously entered formulas are available through the
2403 history list, and the last used formula is offered as a default.
2404 These stored formulas are adapted correctly when moving, inserting, or
2405 deleting columns with the corresponding commands.
2407 The formula can be any algebraic expression understood by the Calc package.
2408 For details, see the Org-mode manual.
2410 This function can also be called from Lisp programs and offers
2411 additional arguments: EQUATION can be the formula to apply. If this
2412 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2413 used to speed-up recursive calls by by-passing unnecessary aligns.
2414 SUPPRESS-CONST suppresses the interpretation of constants in the
2415 formula, assuming that this has been done already outside the function.
2416 SUPPRESS-STORE means the formula should not be stored, either because
2417 it is already stored, or because it is a modified equation that should
2418 not overwrite the stored one."
2420 (org-table-check-inside-data-field)
2421 (or suppress-analysis
(org-table-get-specials))
2422 (if (equal arg
'(16))
2423 (let ((eq (org-table-current-field-formula)))
2424 (or eq
(error "No equation active for current field"))
2425 (org-table-get-field nil eq
)
2427 (setq org-table-may-need-update t
))
2429 (ndown (if (integerp arg
) arg
1))
2430 (org-table-automatic-realign nil
)
2431 (case-fold-search nil
)
2433 (formula (if (and equation suppress-store
)
2435 (org-table-get-formula equation
(equal arg
'(4)))))
2436 (n0 (org-table-current-column))
2437 (modes (copy-sequence org-calc-default-modes
))
2438 (numbers nil
) ; was a variable, now fixed default
2440 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2441 duration duration-output-format
)
2442 ;; Parse the format string. Since we have a lot of modes, this is
2443 ;; a lot of work. However, I think calc still uses most of the time.
2444 (if (string-match ";" formula
)
2445 (let ((tmp (org-split-string formula
";")))
2446 (setq formula
(car tmp
)
2447 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2449 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2450 (setq c
(string-to-char (match-string 1 fmt
))
2451 n
(string-to-number (match-string 2 fmt
)))
2453 (setq modes
(org-set-calc-mode 'calc-internal-prec n
))
2454 (setq modes
(org-set-calc-mode
2456 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2457 (?s . sci
) (?e . eng
))))
2459 (setq fmt
(replace-match "" t t fmt
)))
2460 (if (string-match "T" fmt
)
2461 (setq duration t numbers t
2462 duration-output-format nil
2463 fmt
(replace-match "" t t fmt
)))
2464 (if (string-match "t" fmt
)
2466 duration-output-format org-table-duration-custom-format
2468 fmt
(replace-match "" t t fmt
)))
2469 (if (string-match "N" fmt
)
2471 fmt
(replace-match "" t t fmt
)))
2472 (if (string-match "L" fmt
)
2474 fmt
(replace-match "" t t fmt
)))
2475 (if (string-match "E" fmt
)
2477 fmt
(replace-match "" t t fmt
)))
2478 (while (string-match "[DRFS]" fmt
)
2479 (setq modes
(org-set-calc-mode (match-string 0 fmt
)))
2480 (setq fmt
(replace-match "" t t fmt
)))
2481 (unless (string-match "\\S-" fmt
)
2483 (if (and (not suppress-const
) org-table-formula-use-constants
)
2484 (setq formula
(org-table-formula-substitute-names formula
)))
2485 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2487 (setq fields
(org-split-string
2489 (buffer-substring (point-at-bol) (point-at-eol)))
2491 ;; replace fields with duration values if relevant
2494 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2497 (setq fields
(mapcar
2498 (lambda (x) (number-to-string (string-to-number x
)))
2500 (setq ndown
(1- ndown
))
2501 (setq form
(copy-sequence formula
)
2502 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2503 (if (and lispp literal
) (setq lispp
'literal
))
2505 ;; Insert row and column number of formula result field
2506 (while (string-match "[@$]#" form
)
2511 (if (equal (substring form
(match-beginning 0)
2512 (1+ (match-beginning 0)))
2514 (org-table-current-dline)
2515 (org-table-current-column))))
2518 ;; Check for old vertical references
2519 (setq form
(org-table-rewrite-old-row-references form
))
2520 ;; Insert remote references
2521 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2525 (org-table-make-reference
2526 (org-table-get-remote-range
2527 (match-string 1 form
) (match-string 2 form
))
2528 keep-empty numbers lispp
))
2530 ;; Insert complex ranges
2531 (while (and (string-match org-table-range-regexp form
)
2532 (> (length (match-string 0 form
)) 1))
2533 (setq formrg
(save-match-data
2534 (org-table-get-range (match-string 0 form
) nil n0
)))
2537 (org-table-make-reference
2538 ;; possibly handle durations
2541 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2542 (org-table-time-string-to-seconds formrg
))
2544 keep-empty numbers lispp
)))
2545 (if (not (save-match-data
2546 (string-match (regexp-quote form
) formrpl
)))
2547 (setq form
(replace-match formrpl t t form
))
2548 (error "Spreadsheet error: invalid reference \"%s\"" form
)))
2549 ;; Insert simple ranges
2550 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2554 (org-table-make-reference
2556 fields
(string-to-number (match-string 1 form
))
2557 (string-to-number (match-string 2 form
)))
2558 keep-empty numbers lispp
))
2561 ;; Insert the references to fields in same row
2562 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2563 (setq n
(+ (string-to-number (match-string 1 form
))
2564 (if (match-end 2) n0
0))
2565 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
))
2566 (unless x
(error "Invalid field specifier \"%s\""
2567 (match-string 0 form
)))
2568 (setq form
(replace-match
2570 (org-table-make-reference x nil numbers lispp
))
2574 (setq ev
(condition-case nil
2575 (eval (eval (read form
)))
2577 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2578 ev
(if duration
(org-table-time-seconds-to-string
2579 (string-to-number ev
)
2580 duration-output-format
) ev
))
2581 (or (fboundp 'calc-eval
)
2582 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2583 (setq ev
(calc-eval (cons form modes
) (if numbers
'num
))
2584 ev
(if duration
(org-table-time-seconds-to-string
2585 (string-to-number ev
)
2586 duration-output-format
) ev
)))
2588 (when org-table-formula-debug
2589 (with-output-to-temp-buffer "*Substitution History*"
2590 (princ (format "Substitution history of formula
2594 $1-> %s\n" orig formula form0 form
))
2596 (princ (format " %s^\nError: %s"
2597 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2598 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2600 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2601 (setq bw
(get-buffer-window "*Substitution History*"))
2602 (org-fit-window-to-buffer bw
)
2603 (unless (and (org-called-interactively-p 'any
) (not ndown
))
2604 (unless (let (inhibit-redisplay)
2605 (y-or-n-p "Debugging Formula. Continue to next? "))
2610 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2611 (org-table-justify-field-maybe
2612 (format org-table-formula-field-format
2613 (if fmt
(format fmt
(string-to-number ev
)) ev
)))
2614 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2615 (call-interactively 'org-return
)
2617 (and down
(org-table-maybe-recalculate-line))
2618 (or suppress-align
(and org-table-may-need-update
2619 (org-table-align))))))
2621 (defun org-table-put-field-property (prop value
)
2623 (put-text-property (progn (skip-chars-backward "^|") (point))
2624 (progn (skip-chars-forward "^|") (point))
2627 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2628 "Get a calc vector from a column, according to descriptor DESC.
2629 Optional arguments TBEG and COL can give the beginning of the table and
2630 the current column, to avoid unnecessary parsing.
2632 HIGHLIGHT means just highlight the range.
2634 When CORNERS-ONLY is set, only return the corners of the range as
2635 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2636 in the buffer and column1 and column2 are table column numbers."
2637 (if (not (equal (string-to-char desc
) ?
@))
2638 (setq desc
(concat "@" desc
)))
2640 (or tbeg
(setq tbeg
(org-table-begin)))
2641 (or col
(setq col
(org-table-current-column)))
2642 (let ((thisline (org-current-line))
2643 beg end c1 c2 r1 r2 rangep tmp
)
2644 (unless (string-match org-table-range-regexp desc
)
2645 (error "Invalid table range specifier `%s'" desc
))
2646 (setq rangep
(match-end 3)
2647 r1
(and (match-end 1) (match-string 1 desc
))
2648 r2
(and (match-end 4) (match-string 4 desc
))
2649 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2650 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2652 (and c1
(setq c1
(+ (string-to-number c1
)
2653 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2654 (and c2
(setq c2
(+ (string-to-number c2
)
2655 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2656 (if (equal r1
"") (setq r1 nil
))
2657 (if (equal r2
"") (setq r2 nil
))
2658 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2659 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2660 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2661 (if (not r1
) (setq r1 thisline
))
2662 (if (not r2
) (setq r2 thisline
))
2663 (if (not c1
) (setq c1 col
))
2664 (if (not c2
) (setq c2 col
))
2665 (if (and (not corners-only
)
2666 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2670 (while (not (looking-at org-table-dataline-regexp
))
2671 (beginning-of-line 2))
2672 (prog1 (org-trim (org-table-get-field c1
))
2673 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2674 ;; A range, return a vector
2675 ;; First sort the numbers to get a regular ractangle
2676 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2677 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2679 ;; Only return the corners of the range
2681 ;; Copy the range values into a list
2683 (while (not (looking-at org-table-dataline-regexp
))
2684 (beginning-of-line 2))
2685 (org-table-goto-column c1
)
2688 (while (not (looking-at org-table-dataline-regexp
))
2689 (beginning-of-line 0))
2690 (org-table-goto-column c2
)
2693 (org-table-highlight-rectangle
2694 beg
(progn (skip-chars-forward "^|\n") (point))))
2695 ;; return string representation of calc vector
2697 (apply 'append
(org-table-copy-region beg end
))))))))
2699 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2700 "Analyze descriptor DESC and retrieve the corresponding line number.
2701 The cursor is currently in line CLINE, the table begins in line BLINE,
2702 and TABLE is a vector with line types."
2703 (if (string-match "^[0-9]+$" desc
)
2704 (aref org-table-dlines
(string-to-number desc
))
2705 (setq cline
(or cline
(org-current-line))
2706 bline
(or bline org-table-current-begin-line
)
2707 table
(or table org-table-current-line-types
))
2709 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2711 (and (not (match-end 3)) (not (match-end 6)))
2712 (and (match-end 3) (match-end 6) (not (match-end 5))))
2713 (error "Invalid row descriptor `%s'" desc
))
2714 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2715 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2716 (odir (and (match-end 5) (match-string 5 desc
)))
2717 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2719 (rel (and (match-end 6)
2720 (or (and (match-end 1) (not (match-end 3)))
2722 (if (and hn
(not hdir
))
2725 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2726 (if (and (not hn
) on
(not odir
))
2727 (error "Should never happen");;(aref org-table-dlines on)
2728 (if (and hn
(> hn
0))
2729 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2730 nil hn cline desc
)))
2732 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2733 rel on cline desc
)))
2736 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2737 "FIXME: Needs more documentation."
2738 (let ((l (length table
)))
2740 (while (and (setq i
(+ i
(if backwards -
1 1)))
2742 (not (eq (aref table i
) type
))
2743 (if (and relative
(eq (aref table i
) 'hline
))
2745 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2746 ((eq org-table-relative-ref-may-cross-hline
'error
)
2747 (error "Row descriptor %s used in line %d crosses hline" desc cline
))
2748 (t (setq i
(- i
(if backwards -
1 1))
2753 (if (or (< i
0) (>= i l
))
2754 (error "Row descriptor %s used in line %d leads outside table"
2758 (defun org-table-rewrite-old-row-references (s)
2759 (if (string-match "&[-+0-9I]" s
)
2760 (error "Formula contains old &row reference, please rewrite using @-syntax")
2763 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2764 "Convert list ELEMENTS to something appropriate to insert into formula.
2765 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2766 NUMBERS indicates that everything should be converted to numbers.
2767 LISPP means to return something appropriate for a Lisp list."
2768 (if (stringp elements
) ; just a single val
2770 (if (eq lispp
'literal
)
2772 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2773 (if (equal elements
"") (setq elements
"0"))
2774 (if numbers
(setq elements
(number-to-string (string-to-number elements
))))
2775 (concat "(" elements
")"))
2779 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2781 (setq elements
(or elements
'("0")))
2785 (if (eq lispp
'literal
)
2787 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2789 (concat "[" (mapconcat
2791 (if numbers
(number-to-string (string-to-number x
)) x
))
2795 (defun org-table-recalculate (&optional all noalign
)
2796 "Recalculate the current table line by applying all stored formulas.
2797 With prefix arg ALL, do this for all lines in the table.
2798 With the prefix argument ALL is `(16)' \
2799 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2800 it is the symbol `iterate', recompute the table until it no longer changes.
2801 If NOALIGN is not nil, do not re-align the table after the computations
2802 are done. This is typically used internally to save time, if it is
2803 known that the table will be realigned a little later anyway."
2805 (or (memq this-command org-recalc-commands
)
2806 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2807 (unless (org-at-table-p) (error "Not at a table"))
2808 (if (or (eq all
'iterate
) (equal all
'(16)))
2810 (org-table-get-specials)
2811 (let* ((eqlist (sort (org-table-get-stored-formulas)
2812 (lambda (a b
) (string< (car a
) (car b
)))))
2813 (eqlist1 (copy-sequence eqlist
))
2814 (inhibit-redisplay (not debug-on-error
))
2815 (line-re org-table-dataline-regexp
)
2816 (thisline (org-current-line))
2817 (thiscol (org-table-current-column))
2819 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
2820 ;; Insert constants in all formulas
2823 (when (string-match "\\`$[<>]" (car x
))
2825 (setq x
(cons (substring
2826 (org-table-formula-handle-first/last-rc
2829 (if (assoc (car x
) eqlist1
)
2830 (error "\"%s=\" formula tries to overwrite existing formula for column %s"
2833 (org-table-formula-handle-first/last-rc
(car x
))
2834 (org-table-formula-substitute-names
2835 (org-table-formula-handle-first/last-rc
(cdr x
)))))
2837 ;; Split the equation list
2838 (while (setq eq
(pop eqlist
))
2839 (if (<= (string-to-char (car eq
)) ?
9)
2842 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
2843 ;; Expand ranges in lhs of formulas
2844 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
2846 ;; Get the correct line range to process
2849 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
2850 (goto-char (setq beg
(org-table-begin)))
2851 (if (re-search-forward org-table-calculate-mark-regexp end t
)
2852 ;; This is a table with marked lines, compute selected lines
2853 (setq line-re org-table-recalculate-regexp
)
2854 ;; Move forward to the first non-header line
2855 (if (and (re-search-forward org-table-dataline-regexp end t
)
2856 (re-search-forward org-table-hline-regexp end t
)
2857 (re-search-forward org-table-dataline-regexp end t
))
2858 (setq beg
(match-beginning 0))
2859 nil
))) ;; just leave beg where it is
2860 (setq beg
(point-at-bol)
2861 end
(move-marker (make-marker) (1+ (point-at-eol)))))
2863 (and all
(message "Re-applying formulas to full table..."))
2865 ;; First find the named fields, and mark them untouchable.
2866 ;; Also check if several field/range formulas try to set the same field.
2867 (remove-text-properties beg end
'(org-untouchable t
))
2868 (while (setq eq
(pop eqlname
))
2870 a
(assoc name org-table-named-field-locations
))
2872 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
2874 (when (member name1 seen-fields
)
2875 (error "Several field/range formulas try to set %s" name1
))
2876 (push name1 seen-fields
)
2879 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
2882 (aref org-table-dlines
2883 (string-to-number (match-string 1 name
)))
2884 (error (error "Invalid row number in %s"
2886 (string-to-number (match-string 2 name
)))))
2887 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
2888 (message "Re-applying formula to field: %s" name
)
2889 (org-goto-line (nth 1 a
))
2890 (org-table-goto-column (nth 2 a
))
2891 (push (append a
(list (cdr eq
))) eqlname1
)
2892 (org-table-put-field-property :org-untouchable t
)))
2893 (setq eqlname1
(nreverse eqlname1
))
2895 ;; Now evaluate the column formulas, but skip fields covered by
2898 (while (re-search-forward line-re end t
)
2899 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2900 ;; Unprotected line, recalculate
2901 (and all
(message "Re-applying formulas to full table...(line %d)"
2902 (setq cnt
(1+ cnt
))))
2903 (setq org-last-recalc-line
(org-current-line))
2905 (while (setq entry
(pop eql
))
2906 (org-goto-line org-last-recalc-line
)
2907 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
2908 (unless (get-text-property (point) :org-untouchable
)
2909 (org-table-eval-formula nil
(cdr entry
)
2910 'noalign
'nocst
'nostore
'noanalysis
)))))
2912 ;; Now evaluate the field formulas
2913 (while (setq eq
(pop eqlname1
))
2914 (message "Re-applying formula to field: %s" (car eq
))
2915 (org-goto-line (nth 1 eq
))
2916 (org-table-goto-column (nth 2 eq
))
2917 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
2918 'nostore
'noanalysis
))
2920 (org-goto-line thisline
)
2921 (org-table-goto-column thiscol
)
2922 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
2923 (or noalign
(and org-table-may-need-update
(org-table-align))
2924 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
2926 ;; back to initial position
2927 (message "Re-applying formulas...done")
2928 (org-goto-line thisline
)
2929 (org-table-goto-column thiscol
)
2930 (or noalign
(and org-table-may-need-update
(org-table-align))
2931 (and all
(message "Re-applying formulas...done"))))))
2933 (defun org-table-iterate (&optional arg
)
2934 "Recalculate the table until it does not change anymore.
2935 The maximun number of iterations is 10, but you can chose a different value
2936 with the prefix ARG."
2938 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
2940 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2945 (org-table-recalculate 'all
)
2946 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
2947 (if (not (string= lasttbl thistbl
))
2948 (setq lasttbl thistbl
)
2950 (message "Convergence after %d iterations" i
)
2951 (message "Table was already stable"))
2953 (error "No convergence after %d iterations" i
))))
2955 (defun org-table-recalculate-buffer-tables ()
2956 "Recalculate all tables in the current buffer."
2961 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
2963 (defun org-table-iterate-buffer-tables ()
2964 "Iterate all tables in the buffer, to converge inter-table dependencies."
2967 (checksum (md5 (buffer-string)))
2977 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
2978 (if (equal checksum
(setq c1
(md5 (buffer-string))))
2980 (message "Convergence after %d iterations" (- imax i
))
2982 (setq checksum c1
)))
2983 (error "No convergence after %d iterations" imax
))))))
2985 (defun org-table-expand-lhs-ranges (equations)
2986 "Expand list of formulas.
2987 If some of the RHS in the formulas are ranges or a row reference, expand
2988 them to individual field equations for each field."
2989 (let (e res lhs rhs range r1 r2 c1 c2
)
2990 (while (setq e
(pop equations
))
2991 (setq lhs
(car e
) rhs
(cdr e
))
2993 ((string-match "^@-?[-+I0-9]+\\$-?[0-9]+$" lhs
)
2994 ;; This just refers to one fixed field
2996 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs
)
2997 ;; This just refers to one fixed named field
2999 ((string-match "^@[0-9]+$" lhs
)
3000 (loop for ic from
1 to org-table-current-ncol do
3001 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
3002 (put-text-property 0 (length (caar res
))
3003 :orig-eqn e
(caar res
))))
3005 (setq range
(org-table-get-range lhs org-table-current-begin-pos
3007 (setq r1
(nth 0 range
) c1
(nth 1 range
)
3008 r2
(nth 2 range
) c2
(nth 3 range
))
3009 (setq r1
(org-table-line-to-dline r1
))
3010 (setq r2
(org-table-line-to-dline r2
'above
))
3011 (loop for ir from r1 to r2 do
3012 (loop for ic from c1 to c2 do
3013 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
3014 (put-text-property 0 (length (caar res
))
3015 :orig-eqn e
(caar res
)))))))
3018 (defun org-table-formula-handle-first/last-rc
(s)
3019 "Replace @<, @>, $<, $> with first/last row/column of the table.
3020 So @< and $< will always be replaced with @1 and $1, respectively.
3021 The advantage of these special markers are that structure editing of
3022 the table will not change them, while @1 and $1 will be modified
3023 when a line/row is swaped out of that privileged position. So for
3024 formulas that use a range of rows or columns, it may often be better
3025 to anchor the formula with \"I\" row markers, or to offset from the
3026 borders of the table using the @< @> $< $> makers."
3027 (let (n nmax len char
(start 0))
3028 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3031 (setq start
(match-end 3))
3032 (setq nmax
(if (equal (match-string 1 s
) "@")
3033 (1- (length org-table-dlines
))
3034 org-table-current-ncol
)
3035 len
(- (match-end 2) (match-beginning 2))
3036 char
(string-to-char (match-string 2 s
))
3040 (if (or (< n
1) (> n nmax
))
3041 (error "Reference \"%s\" in expression \"%s\" points outside table"
3042 (match-string 0 s
) s
))
3043 (setq start
(match-beginning 0))
3044 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3047 (defun org-table-formula-substitute-names (f)
3048 "Replace $const with values in string F."
3049 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
3050 ;; First, check for column names
3051 (while (setq start
(string-match org-table-column-name-regexp f start
))
3052 (setq start
(1+ start
))
3053 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
3054 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
3055 ;; Parameters and constants
3057 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
3059 (setq start
(match-end 2))
3060 (setq start
(1+ start
))
3061 (if (setq a
(save-match-data
3062 (org-table-get-constant (match-string 1 f
))))
3063 (setq f
(replace-match
3064 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
3065 (if org-table-formula-debug
3066 (put-text-property 0 (length f
) :orig-formula f1 f
))
3069 (defun org-table-get-constant (const)
3070 "Find the value for a parameter or constant in a formula.
3071 Parameters get priority."
3072 (or (cdr (assoc const org-table-local-parameters
))
3073 (cdr (assoc const org-table-formula-constants-local
))
3074 (cdr (assoc const org-table-formula-constants
))
3075 (and (fboundp 'constants-get
) (constants-get const
))
3076 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3077 (org-entry-get nil
(substring const
5) 'inherit
))
3080 (defvar org-table-fedit-map
3081 (let ((map (make-sparse-keymap)))
3082 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3083 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3084 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3085 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3086 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3087 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3088 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3089 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3090 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3091 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3092 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3093 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3094 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3095 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3096 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3097 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3098 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3099 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3100 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3101 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3104 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3106 ["Finish and Install" org-table-fedit-finish t
]
3107 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3108 ["Abort" org-table-fedit-abort t
]
3110 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3111 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3113 "Shift Reference at Point"
3114 ["Up" org-table-fedit-ref-up t
]
3115 ["Down" org-table-fedit-ref-down t
]
3116 ["Left" org-table-fedit-ref-left t
]
3117 ["Right" org-table-fedit-ref-right t
]
3119 "Change Test Row for Column Formulas"
3120 ["Up" org-table-fedit-line-up t
]
3121 ["Down" org-table-fedit-line-down t
]
3123 ["Scroll Table Window" org-table-fedit-scroll t
]
3124 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3125 ["Show Table Grid" org-table-fedit-toggle-coordinates
3126 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3127 org-table-overlay-coordinates
)]
3129 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3130 :style toggle
:selected org-table-buffer-is-an
]))
3134 (defun org-table-edit-formulas ()
3135 "Edit the formulas of the current table in a separate buffer."
3137 (when (save-excursion (beginning-of-line 1) (looking-at "[ \t]*#\\+TBLFM"))
3138 (beginning-of-line 0))
3139 (unless (org-at-table-p) (error "Not at a table"))
3140 (org-table-get-specials)
3141 (let ((key (org-table-current-field-formula 'key
'noerror
))
3142 (eql (sort (org-table-get-stored-formulas 'noerror
)
3143 'org-table-formula-less-p
))
3144 (pos (move-marker (make-marker) (point)))
3146 (wc (current-window-configuration))
3147 (sel-win (selected-window))
3148 (titles '((column .
"# Column Formulas\n")
3149 (field .
"# Field and Range Formulas\n")
3150 (named .
"# Named Field Formulas\n")))
3152 (org-switch-to-buffer-other-window "*Edit Formulas*")
3154 ;; Keep global-font-lock-mode from turning on font-lock-mode
3155 (let ((font-lock-global-modes '(not fundamental-mode
)))
3157 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
3158 (org-set-local 'org-pos pos
)
3159 (org-set-local 'org-window-configuration wc
)
3160 (org-set-local 'org-selected-window sel-win
)
3161 (use-local-map org-table-fedit-map
)
3162 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3163 (easy-menu-add org-table-fedit-menu
)
3164 (setq startline
(org-current-line))
3165 (while (setq entry
(pop eql
))
3167 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3168 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3169 ((string-match "^[0-9]" (car entry
)) 'column
)
3171 (when (setq title
(assq type titles
))
3172 (or (bobp) (insert "\n"))
3173 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3174 (setq titles
(remove title titles
)))
3175 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3176 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3177 (car entry
) " = " (cdr entry
) "\n"))
3178 (remove-text-properties 0 (length s
) '(face nil
) s
)
3180 (if (eq org-table-use-standard-references t
)
3181 (org-table-fedit-toggle-ref-type))
3182 (org-goto-line startline
)
3183 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3185 (defun org-table-fedit-post-command ()
3186 (when (not (memq this-command
'(lisp-complete-symbol)))
3187 (let ((win (selected-window)))
3190 (org-table-show-reference)
3192 (select-window win
)))))
3194 (defun org-table-formula-to-user (s)
3195 "Convert a formula from internal to user representation."
3196 (if (eq org-table-use-standard-references t
)
3197 (org-table-convert-refs-to-an s
)
3200 (defun org-table-formula-from-user (s)
3201 "Convert a formula from user to internal representation."
3202 (if org-table-use-standard-references
3203 (org-table-convert-refs-to-rc s
)
3206 (defun org-table-convert-refs-to-rc (s)
3207 "Convert spreadsheet references from A7 to @7$28.
3208 Works for single references, but also for entire formulas and even the
3211 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^)]*)\\)" s start
)
3214 ;; format match, just advance
3215 (setq start
(match-end 0)))
3216 ((and (> (match-beginning 0) 0)
3217 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3218 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3219 ;; 3.e5 or something like this.
3220 (setq start
(match-end 0)))
3221 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3222 ;; (member (match-string 1 s)
3223 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3225 ;; function name, just advance
3226 (setq start
(match-end 0)))
3228 (setq start
(match-beginning 0)
3230 (if (equal (match-string 2 s
) "&")
3231 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3233 (string-to-number (match-string 2 s
))
3234 (org-letters-to-number (match-string 1 s
))))
3238 (defun org-table-convert-refs-to-an (s)
3239 "Convert spreadsheet references from to @7$28 to AB7.
3240 Works for single references, but also for entire formulas and even the
3242 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3243 (setq s
(replace-match
3245 (org-number-to-letters
3246 (string-to-number (match-string 2 s
)))
3247 (string-to-number (match-string 1 s
)))
3249 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3250 (setq s
(replace-match (concat "\\1"
3251 (org-number-to-letters
3252 (string-to-number (match-string 2 s
))) "&")
3256 (defun org-letters-to-number (s)
3257 "Convert a base 26 number represented by letters into an integer.
3258 For example: AB -> 28."
3261 (while (> (length s
) 0)
3262 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3266 (defun org-number-to-letters (n)
3267 "Convert an integer into a base 26 number represented by letters.
3268 For example: 28 -> AB."
3271 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3275 (defun org-table-time-string-to-seconds (s)
3276 "Convert a time string into numerical duration in seconds.
3277 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3278 If S is a string representing a number, keep this number."
3279 (let (hour minus min sec res
)
3281 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3282 (setq minus
(< 0 (length (match-string 1 s
)))
3283 hour
(string-to-number (match-string 2 s
))
3284 min
(string-to-number (match-string 3 s
))
3285 sec
(string-to-number (match-string 4 s
)))
3287 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3288 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3289 ((and (not (string-match org-ts-regexp-both s
))
3290 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3291 (setq minus
(< 0 (length (match-string 1 s
)))
3292 hour
(string-to-number (match-string 2 s
))
3293 min
(string-to-number (match-string 3 s
)))
3295 (setq res
(- (+ (* hour
3600) (* min
60))))
3296 (setq res
(+ (* hour
3600) (* min
60)))))
3297 (t (setq res
(string-to-number s
))))
3298 (number-to-string res
)))
3300 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3301 "Convert a number of seconds to a time string.
3302 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3303 minutes or seconds."
3304 (cond ((eq output-format
'days
)
3305 (format "%.3f" (/ (float secs
) 86400)))
3306 ((eq output-format
'hours
)
3307 (format "%.2f" (/ (float secs
) 3600)))
3308 ((eq output-format
'minutes
)
3309 (format "%.1f" (/ (float secs
) 60)))
3310 ((eq output-format
'seconds
)
3312 (t (org-format-seconds "%.2h:%.2m:%.2s" secs
))))
3314 (defun org-table-fedit-convert-buffer (function)
3315 "Convert all references in this buffer, using FUNCTION."
3316 (let ((line (org-current-line)))
3317 (goto-char (point-min))
3319 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3320 (delete-region (point) (point-at-eol))
3321 (or (eobp) (forward-char 1)))
3322 (org-goto-line line
)))
3324 (defun org-table-fedit-toggle-ref-type ()
3325 "Convert all references in the buffer from B3 to @3$2 and back."
3327 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3328 (org-table-fedit-convert-buffer
3329 (if org-table-buffer-is-an
3330 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3331 (message "Reference type switched to %s"
3332 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3334 (defun org-table-fedit-ref-up ()
3335 "Shift the reference at point one row/hline up."
3337 (org-table-fedit-shift-reference 'up
))
3338 (defun org-table-fedit-ref-down ()
3339 "Shift the reference at point one row/hline down."
3341 (org-table-fedit-shift-reference 'down
))
3342 (defun org-table-fedit-ref-left ()
3343 "Shift the reference at point one field to the left."
3345 (org-table-fedit-shift-reference 'left
))
3346 (defun org-table-fedit-ref-right ()
3347 "Shift the reference at point one field to the right."
3349 (org-table-fedit-shift-reference 'right
))
3351 (defun org-table-fedit-shift-reference (dir)
3353 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3354 (if (memq dir
'(left right
))
3355 (org-rematch-and-replace 1 (eq dir
'left
))
3356 (error "Cannot shift reference in this direction")))
3357 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3358 ;; A B3-like reference
3359 (if (memq dir
'(up down
))
3360 (org-rematch-and-replace 2 (eq dir
'up
))
3361 (org-rematch-and-replace 1 (eq dir
'left
))))
3363 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3364 ;; An internal reference
3365 (if (memq dir
'(up down
))
3366 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3367 (org-rematch-and-replace 5 (eq dir
'left
))))))
3369 (defun org-rematch-and-replace (n &optional decr hline
)
3370 "Re-match the group N, and replace it with the shifted reference."
3371 (or (match-end n
) (error "Cannot shift reference in this direction"))
3372 (goto-char (match-beginning n
))
3373 (and (looking-at (regexp-quote (match-string n
)))
3374 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3377 (defun org-table-shift-refpart (ref &optional decr hline
)
3378 "Shift a reference part REF.
3379 If DECR is set, decrease the references row/column, else increase.
3380 If HLINE is set, this may be a hline reference, it certainly is not
3381 a translation reference."
3383 (let* ((sign (string-match "^[-+]" ref
)) n
)
3385 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3387 ((and hline
(string-match "^I+" ref
))
3388 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3389 (setq n
(+ n
(if decr -
1 1)))
3390 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3392 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3394 (concat sign
(make-string n ?I
)))
3396 ((string-match "^[0-9]+" ref
)
3397 (setq n
(string-to-number (concat sign ref
)))
3398 (setq n
(+ n
(if decr -
1 1)))
3400 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3401 (number-to-string (max 1 n
))))
3403 ((string-match "^[a-zA-Z]+" ref
)
3404 (org-number-to-letters
3405 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3407 (t (error "Cannot shift reference"))))))
3409 (defun org-table-fedit-toggle-coordinates ()
3410 "Toggle the display of coordinates in the referenced table."
3412 (let ((pos (marker-position org-pos
)))
3413 (with-current-buffer (marker-buffer org-pos
)
3416 (org-table-toggle-coordinate-overlays)))))
3418 (defun org-table-fedit-finish (&optional arg
)
3419 "Parse the buffer for formula definitions and install them.
3420 With prefix ARG, apply the new formulas to the table."
3422 (org-table-remove-rectangle-highlight)
3423 (if org-table-use-standard-references
3425 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3426 (setq org-table-buffer-is-an nil
)))
3427 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3428 (goto-char (point-min))
3429 (while (re-search-forward
3430 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3432 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3433 form
(match-string 3))
3434 (setq form
(org-trim form
))
3435 (when (not (equal form
""))
3436 (while (string-match "[ \t]*\n[ \t]*" form
)
3437 (setq form
(replace-match " " t t form
)))
3438 (when (assoc var eql
)
3439 (error "Double formulas for %s" var
))
3440 (push (cons var form
) eql
)))
3442 (set-window-configuration org-window-configuration
)
3443 (select-window sel-win
)
3445 (unless (org-at-table-p)
3446 (error "Lost table position - cannot install formulas"))
3447 (org-table-store-formulas eql
)
3448 (move-marker pos nil
)
3449 (kill-buffer "*Edit Formulas*")
3451 (org-table-recalculate 'all
)
3452 (message "New formulas installed - press C-u C-c C-c to apply."))))
3454 (defun org-table-fedit-abort ()
3455 "Abort editing formulas, without installing the changes."
3457 (org-table-remove-rectangle-highlight)
3458 (let ((pos org-pos
) (sel-win org-selected-window
))
3459 (set-window-configuration org-window-configuration
)
3460 (select-window sel-win
)
3462 (move-marker pos nil
)
3463 (message "Formula editing aborted without installing changes")))
3465 (defun org-table-fedit-lisp-indent ()
3466 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3468 (let ((pos (point)) beg end ind
)
3469 (beginning-of-line 1)
3471 ((looking-at "[ \t]")
3473 (call-interactively 'lisp-indent-line
))
3474 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3475 ((not (fboundp 'pp-buffer
))
3476 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3477 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3478 (goto-char (- (match-end 0) 2))
3480 (setq ind
(make-string (current-column) ?\
))
3481 (condition-case nil
(forward-sexp 1)
3483 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3486 (narrow-to-region beg end
)
3487 (if (eq last-command this-command
)
3489 (goto-char (point-min))
3490 (setq this-command nil
)
3491 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3492 (replace-match " ")))
3494 (untabify (point-min) (point-max))
3495 (goto-char (1+ (point-min)))
3496 (while (re-search-forward "^." nil t
)
3497 (beginning-of-line 1)
3499 (goto-char (point-max))
3500 (backward-delete-char 1)))
3504 (defvar org-show-positions nil
)
3506 (defun org-table-show-reference (&optional local
)
3507 "Show the location/value of the $ expression at point."
3509 (org-table-remove-rectangle-highlight)
3511 (let ((pos (if local
(point) org-pos
))
3513 (org-inhibit-highlight-removal t
)
3514 (win (selected-window))
3515 (org-show-positions nil
)
3516 var name e what match dest
)
3517 (if local
(org-table-get-specials))
3519 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3520 (setq match
(concat (substring (match-string 0) 0 -
1)
3522 (substring (match-string 0) 0 -
1)
3525 ((or (org-at-regexp-p org-table-range-regexp2
)
3526 (org-at-regexp-p org-table-translate-regexp
)
3527 (org-at-regexp-p org-table-range-regexp
))
3530 (org-table-convert-refs-to-rc (match-string 0))))
3532 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3533 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3535 (t (error "No reference at point")))
3536 match
(and what
(or match
(match-string 0))))
3537 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3538 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3539 'secondary-selection
))
3540 (org-add-hook 'before-change-functions
3541 'org-table-remove-rectangle-highlight
)
3542 (if (eq what
'name
) (setq var
(substring match
1)))
3543 (when (eq what
'range
)
3544 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3545 (setq match
(org-table-formula-substitute-names match
)))
3549 (re-search-backward "^\\S-" nil t
)
3550 (beginning-of-line 1)
3551 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3554 (org-table-convert-refs-to-rc (match-string 1))))
3555 (org-table-add-rectangle-overlay
3556 (match-beginning 1) (match-end 1) face2
))))
3557 (if (and (markerp pos
) (marker-buffer pos
))
3558 (if (get-buffer-window (marker-buffer pos
))
3559 (select-window (get-buffer-window (marker-buffer pos
)))
3560 (org-switch-to-buffer-other-window (get-buffer-window
3561 (marker-buffer pos
)))))
3563 (org-table-force-dataline)
3565 (setq name
(substring dest
1))
3567 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3568 (setq e
(assoc name org-table-named-field-locations
))
3569 (org-goto-line (nth 1 e
))
3570 (org-table-goto-column (nth 2 e
)))
3571 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3572 (let ((l (string-to-number (match-string 1 dest
)))
3573 (c (string-to-number (match-string 2 dest
))))
3574 (org-goto-line (aref org-table-dlines l
))
3575 (org-table-goto-column c
)))
3576 (t (org-table-goto-column (string-to-number name
))))
3577 (move-marker pos
(point))
3578 (org-table-highlight-rectangle nil nil face2
))
3580 ((equal dest match
))
3585 (org-table-get-range match nil nil
'highlight
))
3587 ((setq e
(assoc var org-table-named-field-locations
))
3588 (org-goto-line (nth 1 e
))
3589 (org-table-goto-column (nth 2 e
))
3590 (org-table-highlight-rectangle (point) (point))
3591 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3592 ((setq e
(assoc var org-table-column-names
))
3593 (org-table-goto-column (string-to-number (cdr e
)))
3594 (org-table-highlight-rectangle (point) (point))
3595 (goto-char (org-table-begin))
3596 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3599 (goto-char (match-beginning 1))
3600 (org-table-highlight-rectangle)
3601 (message "Named column (column %s)" (cdr e
)))
3602 (error "Column name not found")))
3605 (org-table-goto-column (string-to-number (substring match
1)))
3606 (org-table-highlight-rectangle (point) (point))
3607 (message "Column %s" (substring match
1)))
3608 ((setq e
(assoc var org-table-local-parameters
))
3609 (goto-char (org-table-begin))
3610 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3612 (goto-char (match-beginning 1))
3613 (org-table-highlight-rectangle)
3614 (message "Local parameter."))
3615 (error "Parameter not found")))
3618 ((not var
) (error "No reference at point"))
3619 ((setq e
(assoc var org-table-formula-constants-local
))
3620 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3622 ((setq e
(assoc var org-table-formula-constants
))
3623 (message "Constant: $%s=%s in `org-table-formula-constants'."
3625 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3626 (message "Constant: $%s=%s, from `constants.el'%s."
3627 var e
(format " (%s units)" constants-unit-system
)))
3628 (t (error "Undefined name $%s" var
)))))
3630 (when (and org-show-positions
3631 (not (memq this-command
'(org-table-fedit-scroll
3632 org-table-fedit-scroll-down
))))
3633 (push pos org-show-positions
)
3634 (push org-table-current-begin-pos org-show-positions
)
3635 (let ((min (apply 'min org-show-positions
))
3636 (max (apply 'max org-show-positions
)))
3637 (goto-char min
) (recenter 0)
3639 (or (pos-visible-in-window-p max
) (recenter -
1))))
3640 (select-window win
))))
3642 (defun org-table-force-dataline ()
3643 "Make sure the cursor is in a dataline in a table."
3644 (unless (save-excursion
3645 (beginning-of-line 1)
3646 (looking-at org-table-dataline-regexp
))
3647 (let* ((re org-table-dataline-regexp
)
3648 (p1 (save-excursion (re-search-forward re nil
'move
)))
3649 (p2 (save-excursion (re-search-backward re nil
'move
))))
3651 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3653 ((or p1 p2
) (goto-char (or p1 p2
)))
3654 (t (error "No table dataline around here"))))))
3656 (defun org-table-fedit-line-up ()
3657 "Move cursor one line up in the window showing the table."
3659 (org-table-fedit-move 'previous-line
))
3661 (defun org-table-fedit-line-down ()
3662 "Move cursor one line down in the window showing the table."
3664 (org-table-fedit-move 'next-line
))
3666 (defun org-table-fedit-move (command)
3667 "Move the cursor in the window showing the table.
3668 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3669 (let ((org-table-allow-automatic-line-recalculation nil
)
3670 (pos org-pos
) (win (selected-window)) p
)
3671 (select-window (get-buffer-window (marker-buffer org-pos
)))
3673 (call-interactively command
)
3674 (while (and (org-at-table-p)
3675 (org-at-table-hline-p))
3676 (call-interactively command
))
3677 (or (org-at-table-p) (goto-char p
))
3678 (move-marker pos
(point))
3679 (select-window win
)))
3681 (defun org-table-fedit-scroll (N)
3683 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3684 (scroll-other-window N
)))
3686 (defun org-table-fedit-scroll-down (N)
3688 (org-table-fedit-scroll (- N
)))
3690 (defvar org-table-rectangle-overlays nil
)
3692 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3693 "Add a new overlay."
3694 (let ((ov (make-overlay beg end
)))
3695 (overlay-put ov
'face
(or face
'secondary-selection
))
3696 (push ov org-table-rectangle-overlays
)))
3698 (defun org-table-highlight-rectangle (&optional beg end face
)
3699 "Highlight rectangular region in a table."
3700 (setq beg
(or beg
(point)) end
(or end
(point)))
3701 (let ((b (min beg end
))
3704 (and (boundp 'org-show-positions
)
3705 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3706 (goto-char (min beg end
))
3707 (setq l1
(org-current-line)
3708 c1
(org-table-current-column))
3709 (goto-char (max beg end
))
3710 (setq l2
(org-current-line)
3711 c2
(org-table-current-column))
3712 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3714 (beginning-of-line 1)
3715 (loop for line from l1 to l2 do
3716 (when (looking-at org-table-dataline-regexp
)
3717 (org-table-goto-column c1
)
3718 (skip-chars-backward "^|\n") (setq beg
(point))
3719 (org-table-goto-column c2
)
3720 (skip-chars-forward "^|\n") (setq end
(point))
3721 (org-table-add-rectangle-overlay beg end face
))
3722 (beginning-of-line 2))
3724 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3726 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3727 "Remove the rectangle overlays."
3728 (unless org-inhibit-highlight-removal
3729 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3730 (mapc 'delete-overlay org-table-rectangle-overlays
)
3731 (setq org-table-rectangle-overlays nil
)))
3733 (defvar org-table-coordinate-overlays nil
3734 "Collects the coordinate grid overlays, so that they can be removed.")
3735 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3737 (defun org-table-overlay-coordinates ()
3738 "Add overlays to the table at point, to show row/column coordinates."
3740 (mapc 'delete-overlay org-table-coordinate-overlays
)
3741 (setq org-table-coordinate-overlays nil
)
3743 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3744 (goto-char (org-table-begin))
3745 (while (org-at-table-p)
3746 (setq eol
(point-at-eol))
3747 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
3748 (push ov org-table-coordinate-overlays
)
3749 (setq hline
(looking-at org-table-hline-regexp
))
3750 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3751 (format "%4d" (setq id
(1+ id
)))))
3752 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3755 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3756 (setq beg
(1+ (match-beginning 0))
3758 s1
(concat "$" (int-to-string ic
))
3759 s2
(org-number-to-letters ic
)
3760 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3761 (setq ov
(make-overlay beg
(+ beg
(length str
))))
3762 (push ov org-table-coordinate-overlays
)
3763 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3764 (beginning-of-line 2)))))
3766 (defun org-table-toggle-coordinate-overlays ()
3767 "Toggle the display of Row/Column numbers in tables."
3769 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3770 (message "Row/Column number display turned %s"
3771 (if org-table-overlay-coordinates
"on" "off"))
3772 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3774 (unless org-table-overlay-coordinates
3775 (mapc 'delete-overlay org-table-coordinate-overlays
)
3776 (setq org-table-coordinate-overlays nil
)))
3778 (defun org-table-toggle-formula-debugger ()
3779 "Toggle the formula debugger in tables."
3781 (setq org-table-formula-debug
(not org-table-formula-debug
))
3782 (message "Formula debugging has been turned %s"
3783 (if org-table-formula-debug
"on" "off")))
3785 ;;; The orgtbl minor mode
3787 ;; Define a minor mode which can be used in other modes in order to
3788 ;; integrate the org-mode table editor.
3790 ;; This is really a hack, because the org-mode table editor uses several
3791 ;; keys which normally belong to the major mode, for example the TAB and
3792 ;; RET keys. Here is how it works: The minor mode defines all the keys
3793 ;; necessary to operate the table editor, but wraps the commands into a
3794 ;; function which tests if the cursor is currently inside a table. If that
3795 ;; is the case, the table editor command is executed. However, when any of
3796 ;; those keys is used outside a table, the function uses `key-binding' to
3797 ;; look up if the key has an associated command in another currently active
3798 ;; keymap (minor modes, major mode, global), and executes that command.
3799 ;; There might be problems if any of the keys used by the table editor is
3800 ;; otherwise used as a prefix key.
3802 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3803 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3804 ;; addresses this by checking explicitly for both bindings.
3806 ;; The optimized version (see variable `orgtbl-optimized') takes over
3807 ;; all keys which are bound to `self-insert-command' in the *global map*.
3808 ;; Some modes bind other commands to simple characters, for example
3809 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3810 ;; active, this binding is ignored inside tables and replaced with a
3811 ;; modified self-insert.
3814 (defvar orgtbl-mode-map
(make-keymap)
3815 "Keymap for `orgtbl-mode'.")
3818 (defun turn-on-orgtbl ()
3819 "Unconditionally turn on `orgtbl-mode'."
3822 (defvar org-old-auto-fill-inhibit-regexp nil
3823 "Local variable used by `orgtbl-mode'.")
3825 (defconst orgtbl-line-start-regexp
3826 "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\|TBLNAME\\):\\)"
3827 "Matches a line belonging to an orgtbl.")
3829 (defconst orgtbl-extra-font-lock-keywords
3830 (list (list (concat "^" orgtbl-line-start-regexp
".*")
3831 0 (quote 'org-table
) 'prepend
))
3832 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
3834 ;; Install it as a minor mode.
3835 (put 'orgtbl-mode
:included t
)
3836 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
3839 (define-minor-mode orgtbl-mode
3840 "The `org-mode' table editor as a minor mode for use in other modes."
3841 :lighter
" OrgTbl" :keymap orgtbl-mode-map
3842 (org-load-modules-maybe)
3844 ((eq major-mode
'org-mode
)
3845 ;; Exit without error, in case some hook functions calls this
3846 ;; by accident in org-mode.
3847 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
3849 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
3850 ;; Make sure we are first in minor-mode-map-alist
3851 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
3852 ;; FIXME: maybe it should use emulation-mode-map-alists?
3853 (and c
(setq minor-mode-map-alist
3854 (cons c
(delq c minor-mode-map-alist
)))))
3855 (org-set-local (quote org-table-may-need-update
) t
)
3856 (org-add-hook 'before-change-functions
'org-before-change-function
3858 (org-set-local 'org-old-auto-fill-inhibit-regexp
3859 auto-fill-inhibit-regexp
)
3860 (org-set-local 'auto-fill-inhibit-regexp
3861 (if auto-fill-inhibit-regexp
3862 (concat orgtbl-line-start-regexp
"\\|"
3863 auto-fill-inhibit-regexp
)
3864 orgtbl-line-start-regexp
))
3865 (add-to-invisibility-spec '(org-cwidth))
3866 (when (fboundp 'font-lock-add-keywords
)
3867 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
3868 (org-restart-font-lock))
3869 (easy-menu-add orgtbl-mode-menu
))
3871 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
3872 (org-table-cleanup-narrow-column-properties)
3873 (org-remove-from-invisibility-spec '(org-cwidth))
3874 (remove-hook 'before-change-functions
'org-before-change-function t
)
3875 (when (fboundp 'font-lock-remove-keywords
)
3876 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
3877 (org-restart-font-lock))
3878 (easy-menu-remove orgtbl-mode-menu
)
3879 (force-mode-line-update 'all
))))
3881 (defun org-table-cleanup-narrow-column-properties ()
3882 "Remove all properties related to narrow-column invisibility."
3883 (let ((s (point-min)))
3884 (while (setq s
(text-property-any s
(point-max)
3885 'display org-narrow-column-arrow
))
3886 (remove-text-properties s
(1+ s
) '(display t
)))
3887 (setq s
(point-min))
3888 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
3889 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
3890 (setq s
(point-min))
3891 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
3892 (remove-text-properties s
(1+ s
) '(invisible t
)))))
3894 (defun orgtbl-make-binding (fun n
&rest keys
)
3895 "Create a function for binding in the table minor mode.
3896 FUN is the command to call inside a table. N is used to create a unique
3897 command name. KEYS are keys that should be checked in for a command
3898 to execute outside of tables."
3901 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
3903 (concat "In tables, run `" (symbol-name fun
) "'.\n"
3904 "Outside of tables, run the binding of `"
3905 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
3910 (list 'call-interactively
(list 'quote fun
))
3911 (list 'let
'(orgtbl-mode)
3912 (list 'call-interactively
3915 (list 'key-binding k
))
3917 '('orgtbl-error
))))))))
3919 (defun orgtbl-error ()
3920 "Error when there is no default binding for a table key."
3922 (error "This key has no function outside tables"))
3924 (defun orgtbl-setup ()
3925 "Setup orgtbl keymaps."
3928 '(([(meta shift left
)] org-table-delete-column
)
3929 ([(meta left
)] org-table-move-column-left
)
3930 ([(meta right
)] org-table-move-column-right
)
3931 ([(meta shift right
)] org-table-insert-column
)
3932 ([(meta shift up
)] org-table-kill-row
)
3933 ([(meta shift down
)] org-table-insert-row
)
3934 ([(meta up
)] org-table-move-row-up
)
3935 ([(meta down
)] org-table-move-row-down
)
3936 ("\C-c\C-w" org-table-cut-region
)
3937 ("\C-c\M-w" org-table-copy-region
)
3938 ("\C-c\C-y" org-table-paste-rectangle
)
3939 ("\C-c\C-w" org-table-wrap-region
)
3940 ("\C-c-" org-table-insert-hline
)
3941 ("\C-c}" org-table-toggle-coordinate-overlays
)
3942 ("\C-c{" org-table-toggle-formula-debugger
)
3943 ("\C-m" org-table-next-row
)
3944 ([(shift return
)] org-table-copy-down
)
3945 ("\C-c?" org-table-field-info
)
3946 ("\C-c " org-table-blank-field
)
3947 ("\C-c+" org-table-sum
)
3948 ("\C-c=" org-table-eval-formula
)
3949 ("\C-c'" org-table-edit-formulas
)
3950 ("\C-c`" org-table-edit-field
)
3951 ("\C-c*" org-table-recalculate
)
3952 ("\C-c^" org-table-sort-lines
)
3953 ("\M-a" org-table-beginning-of-field
)
3954 ("\M-e" org-table-end-of-field
)
3955 ([(control ?
#)] org-table-rotate-recalc-marks
)))
3957 (while (setq elt
(pop bindings
))
3958 (setq nfunc
(1+ nfunc
))
3959 (setq key
(org-key (car elt
))
3961 cmd
(orgtbl-make-binding fun nfunc key
))
3962 (org-defkey orgtbl-mode-map key cmd
))
3964 ;; Special treatment needed for TAB and RET
3965 (org-defkey orgtbl-mode-map
[(return)]
3966 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
3967 (org-defkey orgtbl-mode-map
"\C-m"
3968 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
3970 (org-defkey orgtbl-mode-map
[(tab)]
3971 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
3972 (org-defkey orgtbl-mode-map
"\C-i"
3973 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
3975 (org-defkey orgtbl-mode-map
[(shift tab
)]
3976 (orgtbl-make-binding 'org-table-previous-field
104
3977 [(shift tab
)] [(tab)] "\C-i"))
3980 (unless (featurep 'xemacs
)
3981 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
3982 (orgtbl-make-binding 'org-table-previous-field
107
3983 [S-iso-lefttab
] [backtab] [(shift tab)]
3986 (org-defkey orgtbl-mode-map [backtab]
3987 (orgtbl-make-binding 'org-table-previous-field
108
3988 [backtab] [S-iso-lefttab] [(shift tab)]
3991 (org-defkey orgtbl-mode-map "\M-\C-m"
3992 (orgtbl-make-binding 'org-table-wrap-region 105
3993 "\M-\C-m" [(meta return)]))
3994 (org-defkey orgtbl-mode-map [(meta return)]
3995 (orgtbl-make-binding 'org-table-wrap-region 106
3996 [(meta return)] "\M-\C-m"))
3998 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
3999 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4001 (when orgtbl-optimized
4002 ;; If the user wants maximum table support, we need to hijack
4003 ;; some standard editing functions
4004 (org-remap orgtbl-mode-map
4005 'self-insert-command 'orgtbl-self-insert-command
4006 'delete-char 'org-delete-char
4007 'delete-backward-char 'org-delete-backward-char)
4008 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4009 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4011 ["Create or convert" org-table-create-or-convert-from-region
4012 :active (not (org-at-table-p)) :keys "C-c |" ]
4014 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4015 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4016 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4017 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4019 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4020 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4021 ["Copy Field from Above"
4022 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4025 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4026 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4027 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4028 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4030 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4031 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4032 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4033 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4034 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4036 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4038 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4039 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4040 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4041 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4044 ["Insert table template" orgtbl-insert-radio-table
4045 (assq major-mode orgtbl-radio-table-templates)]
4046 ["Comment/uncomment table" orgtbl-toggle-comment t])
4048 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4049 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4050 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4051 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4052 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4053 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4054 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4055 ["Sum Column/Rectangle" org-table-sum
4056 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4057 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4059 org-table-toggle-formula-debugger :active (org-at-table-p)
4061 :style toggle :selected org-table-formula-debug]
4062 ["Show Col/Row Numbers"
4063 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4065 :style toggle :selected org-table-overlay-coordinates]
4069 (defun orgtbl-ctrl-c-ctrl-c (arg)
4070 "If the cursor is inside a table, realign the table.
4071 If it is a table to be sent away to a receiver, do it.
4072 With prefix arg, also recompute table."
4074 (let ((pos (point)) action consts-str consts cst const-str)
4076 (beginning-of-line 1)
4078 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4079 ((looking-at "[ \t]*|") pos)
4080 ((looking-at "[ \t]*#\\+TBLFM:") 'recalc))))
4084 (org-table-maybe-eval-formula)
4086 (call-interactively 'org-table-recalculate)
4087 (org-table-maybe-recalculate-line))
4088 (call-interactively 'org-table-align)
4089 (when (orgtbl-send-table 'maybe)
4090 (run-hooks 'orgtbl-after-send-table-hook)))
4091 ((eq action 'recalc)
4093 (goto-char (point-min))
4094 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t)
4095 (setq const-str (substring-no-properties (match-string 1)))
4096 (setq consts (append consts (org-split-string const-str "[ \t]+")))
4099 (while (setq e (pop consts))
4100 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4101 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4102 (setq org-table-formula-constants-local cst)))))
4104 (beginning-of-line 1)
4105 (skip-chars-backward " \r\n\t")
4106 (if (org-at-table-p)
4107 (org-call-with-arg 'org-table-recalculate t))))
4108 (t (let (orgtbl-mode)
4109 (call-interactively (key-binding "\C-c\C-c")))))))
4111 (defun orgtbl-create-or-convert-from-region (arg)
4112 "Create table or convert region to table, if no conflicting binding.
4113 This installs the table binding `C-c |', but only if there is no
4114 conflicting binding to this key outside orgtbl-mode."
4116 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4118 (call-interactively cmd)
4119 (call-interactively 'org-table-create-or-convert-from-region))))
4121 (defun orgtbl-tab (arg)
4122 "Justification and field motion for `orgtbl-mode'."
4124 (if arg (org-table-edit-field t)
4125 (org-table-justify-field-maybe)
4126 (org-table-next-field)))
4128 (defun orgtbl-ret ()
4129 "Justification and field motion for `orgtbl-mode'."
4133 (org-table-justify-field-maybe)
4134 (org-table-next-row)))
4136 (defun orgtbl-self-insert-command (N)
4137 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4138 If the cursor is in a table looking at whitespace, the whitespace is
4139 overwritten, and the table is not marked as requiring realignment."
4141 (if (and (org-at-table-p)
4143 (and org-table-auto-blank-field
4144 (member last-command
4145 '(orgtbl-hijacker-command-100
4146 orgtbl-hijacker-command-101
4147 orgtbl-hijacker-command-102
4148 orgtbl-hijacker-command-103
4149 orgtbl-hijacker-command-104
4150 orgtbl-hijacker-command-105
4152 (org-table-blank-field))
4155 (looking-at "[^|\n]* +|"))
4156 (let (org-table-may-need-update)
4157 (goto-char (1- (match-end 0)))
4159 (goto-char (match-beginning 0))
4160 (self-insert-command N))
4161 (setq org-table-may-need-update t)
4164 (cmd (or (key-binding
4165 (or (and (listp function-key-map)
4166 (setq a (assoc last-input-event function-key-map))
4168 (vector last-input-event)))
4169 'self-insert-command)))
4170 (call-interactively cmd)
4171 (if (and org-self-insert-cluster-for-undo
4172 (eq cmd 'self-insert-command))
4173 (if (not (eq last-command 'orgtbl-self-insert-command))
4174 (setq org-self-insert-command-undo-counter 1)
4175 (if (>= org-self-insert-command-undo-counter 20)
4176 (setq org-self-insert-command-undo-counter 1)
4177 (and (> org-self-insert-command-undo-counter 0)
4179 (not (cadr buffer-undo-list)) ; remove nil entry
4180 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4181 (setq org-self-insert-command-undo-counter
4182 (1+ org-self-insert-command-undo-counter))))))))
4184 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4185 "Regular expression matching exponentials as produced by calc.")
4187 (defun orgtbl-export (table target)
4189 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
4190 (lines (org-split-string table "[ \t]*\n[ \t]*"))
4191 org-table-last-alignment org-table-last-column-widths
4193 (if (not (fboundp func))
4194 (error "Cannot export orgtbl table to %s" target))
4195 (setq lines (org-table-clean-before-export lines))
4199 (if (string-match org-table-hline-regexp x)
4201 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4203 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
4205 (loop for i from (1- maxcol) downto 0 do
4206 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
4207 (setq column (delq nil column))
4208 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
4209 (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))
4210 (funcall func table nil)))
4212 (defun orgtbl-gather-send-defs ()
4213 "Gather a plist of :name, :transform, :params for each destination before
4216 (goto-char (org-table-begin))
4218 (beginning-of-line 0)
4219 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4220 (let ((name (org-no-properties (match-string 1)))
4221 (transform (intern (match-string 2)))
4222 (params (if (match-end 3)
4223 (read (concat "(" (match-string 3) ")")))))
4224 (push (list :name name :transform transform :params params)
4226 (beginning-of-line 0)))
4229 (defun orgtbl-send-replace-tbl (name txt)
4230 "Find and replace table NAME with TXT."
4232 (goto-char (point-min))
4233 (unless (re-search-forward
4234 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4235 (error "Don't know where to insert translated table"))
4236 (goto-char (match-beginning 0))
4237 (beginning-of-line 2)
4239 (let ((beg (point)))
4240 (unless (re-search-forward
4241 (concat "END RECEIVE ORGTBL +" name) nil t)
4242 (error "Cannot find end of insertion region"))
4243 (beginning-of-line 1)
4244 (delete-region beg (point))))
4248 (defun org-table-to-lisp (&optional txt)
4249 "Convert the table at point to a Lisp structure.
4250 The structure will be a list. Each item is either the symbol `hline'
4251 for a horizontal separator line, or a list of field values as strings.
4252 The table is taken from the parameter TXT, or from the buffer at point."
4254 (unless (org-at-table-p)
4255 (error "No table at point")))
4257 (buffer-substring-no-properties (org-table-begin)
4259 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4263 (if (string-match org-table-hline-regexp x)
4265 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4268 (defun orgtbl-send-table (&optional maybe)
4269 "Send a transformed version of this table to the receiver position.
4270 With argument MAYBE, fail quietly if no transformation is defined for
4274 (unless (org-at-table-p) (error "Not at a table"))
4275 ;; when non-interactive, we assume align has just happened.
4276 (when (org-called-interactively-p 'any) (org-table-align))
4277 (let ((dests (orgtbl-gather-send-defs))
4278 (txt (buffer-substring-no-properties (org-table-begin)
4281 (unless dests (if maybe (throw 'exit nil)
4282 (error "Don't know how to transform this table")))
4283 (dolist (dest dests)
4284 (let* ((name (plist-get dest :name))
4285 (transform (plist-get dest :transform))
4286 (params (plist-get dest :params))
4287 (skip (plist-get params :skip))
4288 (skipcols (plist-get params :skipcols))
4290 (lines (org-table-clean-before-export
4292 (org-split-string txt "[ \t]*\n[ \t]*"))))
4293 (i0 (if org-table-clean-did-remove-column 2 1))
4296 (if (string-match org-table-hline-regexp x)
4298 (org-remove-by-index
4299 (org-split-string (org-trim x) "\\s-*|\\s-*")
4302 (fun (if (= i0 2) 'cdr 'identity))
4303 (org-table-last-alignment
4304 (org-remove-by-index (funcall fun org-table-last-alignment)
4306 (org-table-last-column-widths
4307 (org-remove-by-index (funcall fun org-table-last-column-widths)
4309 (txt (if (fboundp transform)
4310 (funcall transform table params)
4311 (error "No such transformation function %s" transform))))
4312 (orgtbl-send-replace-tbl name txt))
4313 (setq ntbl (1+ ntbl)))
4314 (message "Table converted and installed at %d receiver location%s"
4315 ntbl (if (> ntbl 1) "s" ""))
4320 (defun org-remove-by-index (list indices &optional i0)
4321 "Remove the elements in LIST with indices in INDICES.
4322 First element has index 0, or I0 if given."
4325 (if (integerp indices) (setq indices (list indices)))
4326 (setq i0 (1- (or i0 0)))
4327 (delq :rm (mapcar (lambda (x)
4329 (if (memq i0 indices) :rm x))
4332 (defun orgtbl-toggle-comment ()
4333 "Comment or uncomment the orgtbl at point."
4335 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4336 (re2 (concat "^" orgtbl-line-start-regexp))
4337 (commented (save-excursion (beginning-of-line 1)
4338 (cond ((looking-at re1) t)
4339 ((looking-at re2) nil)
4340 (t (error "Not at an org table")))))
4341 (re (if commented re1 re2))
4344 (beginning-of-line 1)
4345 (while (looking-at re) (beginning-of-line 0))
4346 (beginning-of-line 2)
4348 (while (looking-at re) (beginning-of-line 2))
4350 (comment-region beg end (if commented '(4) nil))))
4352 (defun orgtbl-insert-radio-table ()
4353 "Insert a radio table template appropriate for this major mode."
4355 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4358 (unless e (error "No radio table setup defined for %s" major-mode))
4359 (setq name (read-string "Table name: "))
4360 (while (string-match "%n" txt)
4361 (setq txt (replace-match name t t txt)))
4362 (or (bolp) (insert "\n"))
4367 ;; Dynamically bound input and output for table formatting.
4368 (defvar *orgtbl-table* nil
4369 "Carries the current table through formatting routines.")
4370 (defvar *orgtbl-rtn* nil
4371 "Formatting routines push the output lines here.")
4372 ;; Formatting parameters for the current table section.
4373 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4374 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4375 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4376 (defvar *orgtbl-fmt* nil "Format for each entry.")
4377 (defvar *orgtbl-efmt* nil "Format for numbers.")
4378 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4379 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4380 (defvar *orgtbl-lstart* nil "Text starting a row.")
4381 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4382 (defvar *orgtbl-lend* nil "Text ending a row.")
4383 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4385 (defsubst orgtbl-get-fmt (fmt i)
4386 "Retrieve the format from FMT corresponding to the Ith column."
4387 (if (and (not (functionp fmt)) (consp fmt))
4391 (defsubst orgtbl-apply-fmt (fmt &rest args)
4392 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4393 (cond ((functionp fmt) (apply fmt args))
4394 (fmt (apply 'format fmt args))
4398 (defsubst orgtbl-eval-str (str)
4399 "If STR is a function, evaluate it with no arguments."
4404 (defun orgtbl-format-line (line)
4405 "Format LINE as a table row."
4406 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4412 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4413 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4414 (orgtbl-apply-fmt efmt (match-string 1 f)
4417 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4418 *orgtbl-default-fmt*)
4421 (push (if *orgtbl-lfmt*
4422 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4423 (concat (orgtbl-eval-str *orgtbl-lstart*)
4424 (mapconcat 'identity line *orgtbl-sep*)
4425 (orgtbl-eval-str *orgtbl-lend*)))
4428 (defun orgtbl-format-section (section-stopper)
4429 "Format lines until the first occurrence of SECTION-STOPPER."
4432 (while (not (eq (car *orgtbl-table*) section-stopper))
4433 (if prevline (orgtbl-format-line prevline))
4434 (setq prevline (pop *orgtbl-table*)))
4435 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4436 (*orgtbl-lend* *orgtbl-llend*)
4437 (*orgtbl-lfmt* *orgtbl-llfmt*))
4438 (orgtbl-format-line prevline))))))
4440 (defun orgtbl-to-generic (table params)
4441 "Convert the orgtbl-mode TABLE to some other format.
4442 This generic routine can be used for many standard cases.
4443 TABLE is a list, each entry either the symbol `hline' for a horizontal
4444 separator line, or a list of fields for that line.
4445 PARAMS is a property list of parameters that can influence the conversion.
4446 For the generic converter, some parameters are obligatory: you need to
4447 specify either :lfmt, or all of (:lstart :lend :sep).
4449 Valid parameters are
4451 :splice When set to t, return only table body lines, don't wrap
4452 them into :tstart and :tend. Default is nil. When :splice
4453 is non-nil, this also means that the exporter should not look
4454 for and interpret header and footer sections.
4456 :hline String to be inserted on horizontal separation lines.
4457 May be nil to ignore hlines.
4459 :sep Separator between two fields
4460 :remove-nil-lines Do not include lines that evaluate to nil.
4463 Each in the following group may be either a string or a function
4464 of no arguments returning a string:
4465 :tstart String to start the table. Ignored when :splice is t.
4466 :tend String to end the table. Ignored when :splice is t.
4467 :lstart String to start a new table line.
4468 :llstart String to start the last table line, defaults to :lstart.
4469 :lend String to end a table line
4470 :llend String to end the last table line, defaults to :lend.
4472 Each in the following group may be a string, a function of one
4473 argument (the field or line) returning a string, or a plist
4474 mapping columns to either of the above:
4475 :lfmt Format for entire line, with enough %s to capture all fields.
4476 If this is present, :lstart, :lend, and :sep are ignored.
4477 :llfmt Format for the entire last line, defaults to :lfmt.
4478 :fmt A format to be used to wrap the field, should contain
4479 %s for the original field value. For example, to wrap
4480 everything in dollars, you could use :fmt \"$%s$\".
4481 This may also be a property list with column numbers and
4482 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4484 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4485 Same as above, specific for the header lines in the table.
4486 All lines before the first hline are treated as header.
4487 If any of these is not present, the data line value is used.
4489 This may be either a string or a function of two arguments:
4490 :efmt Use this format to print numbers with exponentials.
4491 The format should have %s twice for inserting mantissa
4492 and exponent, for example \"%s\\\\times10^{%s}\". This
4493 may also be a property list with column numbers and
4494 formats. :fmt will still be applied after :efmt.
4496 In addition to this, the parameters :skip and :skipcols are always handled
4497 directly by `orgtbl-send-table'. See manual."
4500 (let* ((splicep (plist-get params :splice))
4501 (hline (plist-get params :hline))
4502 (remove-nil-linesp (plist-get params :remove-nil-lines))
4503 (remove-newlines (plist-get params :remove-newlines))
4504 (*orgtbl-hline* hline)
4505 (*orgtbl-table* table)
4506 (*orgtbl-sep* (plist-get params :sep))
4507 (*orgtbl-efmt* (plist-get params :efmt))
4508 (*orgtbl-lstart* (plist-get params :lstart))
4509 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4510 (*orgtbl-lend* (plist-get params :lend))
4511 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4512 (*orgtbl-lfmt* (plist-get params :lfmt))
4513 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4514 (*orgtbl-fmt* (plist-get params :fmt))
4519 (when (plist-member params :tstart)
4520 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4521 (if tstart (push tstart *orgtbl-rtn*)))))
4523 ;; Do we have a heading section? If so, format it and handle the
4525 (if (and (not splicep)
4526 (or (consp (car *orgtbl-table*))
4527 (consp (nth 1 *orgtbl-table*)))
4528 (memq 'hline (cdr *orgtbl-table*)))
4530 (when (eq 'hline (car *orgtbl-table*))
4531 ;; there is a hline before the first data line
4532 (and hline (push hline *orgtbl-rtn*))
4533 (pop *orgtbl-table*))
4534 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4536 (*orgtbl-llstart* (or (plist-get params :hllstart)
4538 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4539 (*orgtbl-llend* (or (plist-get params :hllend)
4540 (plist-get params :hlend) *orgtbl-llend*))
4541 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4542 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4543 (plist-get params :hlfmt) *orgtbl-llfmt*))
4544 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4545 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4546 (orgtbl-format-section 'hline))
4547 (if hline (push hline *orgtbl-rtn*))
4548 (pop *orgtbl-table*)))
4550 ;; Now format the main section.
4551 (orgtbl-format-section nil)
4554 (when (plist-member params :tend)
4555 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4556 (if tend (push tend *orgtbl-rtn*)))))
4558 (mapconcat (if remove-newlines
4560 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4562 (nreverse (if remove-nil-linesp
4563 (remq nil *orgtbl-rtn*)
4564 *orgtbl-rtn*)) "\n")))
4566 (defun orgtbl-to-tsv (table params)
4567 "Convert the orgtbl-mode table to TAB separated material."
4568 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4569 (defun orgtbl-to-csv (table params)
4570 "Convert the orgtbl-mode table to CSV material.
4571 This does take care of the proper quoting of fields with comma or quotes."
4572 (orgtbl-to-generic table (org-combine-plists
4573 '(:sep "," :fmt org-quote-csv-field)
4576 (defun orgtbl-to-latex (table params)
4577 "Convert the orgtbl-mode TABLE to LaTeX.
4578 TABLE is a list, each entry either the symbol `hline' for a horizontal
4579 separator line, or a list of fields for that line.
4580 PARAMS is a property list of parameters that can influence the conversion.
4581 Supports all parameters from `orgtbl-to-generic'. Most important for
4584 :splice When set to t, return only table body lines, don't wrap
4585 them into a tabular environment. Default is nil.
4587 :fmt A format to be used to wrap the field, should contain %s for the
4588 original field value. For example, to wrap everything in dollars,
4589 use :fmt \"$%s$\". This may also be a property list with column
4590 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4591 The format may also be a function that formats its one argument.
4593 :efmt Format for transforming numbers with exponentials. The format
4594 should have %s twice for inserting mantissa and exponent, for
4595 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4596 This may also be a property list with column numbers and formats.
4597 The format may also be a function that formats its two arguments.
4599 :llend If you find too much space below the last line of a table,
4600 pass a value of \"\" for :llend to suppress the final \\\\.
4602 The general parameters :skip and :skipcols have already been applied when
4603 this function is called."
4604 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4605 org-table-last-alignment ""))
4608 :tstart (concat "\\begin{tabular}{" alignment "}")
4609 :tend "\\end{tabular}"
4610 :lstart "" :lend " \\\\" :sep " & "
4611 :efmt "%s\\,(%s)" :hline "\\hline")))
4612 (orgtbl-to-generic table (org-combine-plists params2 params))))
4614 (defun orgtbl-to-html (table params)
4615 "Convert the orgtbl-mode TABLE to HTML.
4616 TABLE is a list, each entry either the symbol `hline' for a horizontal
4617 separator line, or a list of fields for that line.
4618 PARAMS is a property list of parameters that can influence the conversion.
4619 Currently this function recognizes the following parameters:
4621 :splice When set to t, return only table body lines, don't wrap
4622 them into a <table> environment. Default is nil.
4624 The general parameters :skip and :skipcols have already been applied when
4625 this function is called. The function does *not* use `orgtbl-to-generic',
4626 so you cannot specify parameters for it."
4627 (let* ((splicep (plist-get params :splice))
4628 (html-table-tag org-export-html-table-tag)
4630 ;; Just call the formatter we already have
4631 ;; We need to make text lines for it, so put the fields back together.
4632 (setq html (org-format-org-table-html
4637 (concat "| " (mapconcat 'org-html-expand x " | ") " |")))
4640 (if (string-match "\n+\\'" html)
4641 (setq html (replace-match "" t t html)))
4644 (defun orgtbl-to-texinfo (table params)
4645 "Convert the orgtbl-mode TABLE to TeXInfo.
4646 TABLE is a list, each entry either the symbol `hline' for a horizontal
4647 separator line, or a list of fields for that line.
4648 PARAMS is a property list of parameters that can influence the conversion.
4649 Supports all parameters from `orgtbl-to-generic'. Most important for
4652 :splice nil/t When set to t, return only table body lines, don't wrap
4653 them into a multitable environment. Default is nil.
4655 :fmt fmt A format to be used to wrap the field, should contain
4656 %s for the original field value. For example, to wrap
4657 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4658 This may also be a property list with column numbers and
4659 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4660 Each format also may be a function that formats its one
4663 :cf \"f1 f2..\" The column fractions for the table. By default these
4664 are computed automatically from the width of the columns
4667 The general parameters :skip and :skipcols have already been applied when
4668 this function is called."
4669 (let* ((total (float (apply '+ org-table-last-column-widths)))
4670 (colfrac (or (plist-get params :cf)
4672 (lambda (x) (format "%.3f" (/ (float x) total)))
4673 org-table-last-column-widths " ")))
4676 :tstart (concat "@multitable @columnfractions " colfrac)
4677 :tend "@end multitable"
4678 :lstart "@item " :lend "" :sep " @tab "
4679 :hlstart "@headitem ")))
4680 (orgtbl-to-generic table (org-combine-plists params2 params))))
4682 (defun orgtbl-to-orgtbl (table params)
4683 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4684 Useful when slicing one table into many. The :hline, :sep,
4685 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4686 and :tend suppress strings without splicing; they can be set to
4687 provide ORGTBL directives for the generated table."
4691 :tstart nil :tend nil
4696 (params (org-combine-plists params2 params)))
4697 (orgtbl-to-generic table params)))
4699 (defun org-table-get-remote-range (name-or-id form)
4700 "Get a field value or a list of values in a range from table at ID.
4702 NAME-OR-ID may be the name of a table in the current file as set by
4703 a \"#+TBLNAME:\" directive. The first table following this line
4704 will then be used. Alternatively, it may be an ID referring to
4705 any entry, also in a different file. In this case, the first table
4706 in that entry will be referenced.
4707 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
4708 \"@I$2..@II$2\". All the references must be absolute, not relative.
4710 The return value is either a single string for a single field, or a
4711 list of the fields in the rectangle ."
4714 ;; Protect a bunch of variables from being overwritten
4715 ;; by the context of the remote table
4716 org-table-column-names org-table-column-name-regexp
4717 org-table-local-parameters org-table-named-field-locations
4718 org-table-current-line-types org-table-current-begin-line
4719 org-table-current-begin-pos org-table-dlines
4720 org-table-current-ncol
4721 org-table-hlines org-table-last-alignment
4722 org-table-last-column-widths org-table-last-alignment
4723 org-table-last-column-widths tbeg
4725 (setq form (org-table-convert-refs-to-rc form))
4730 (goto-char (point-min))
4731 (if (re-search-forward
4732 (concat "^[ \t]*#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4734 (setq buffer (current-buffer) loc (match-beginning 0))
4735 (setq id-loc (org-id-find name-or-id 'marker))
4736 (unless (and id-loc (markerp id-loc))
4737 (error "Can't find remote table \"%s\"" name-or-id))
4738 (setq buffer (marker-buffer id-loc)
4739 loc (marker-position id-loc))
4740 (move-marker id-loc nil)))
4741 (with-current-buffer buffer
4747 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4748 (not (match-beginning 1)))
4749 (error "Cannot find a table at NAME or ID %s" name-or-id))
4750 (setq tbeg (point-at-bol))
4751 (org-table-get-specials)
4752 (setq form (org-table-formula-substitute-names
4753 (org-table-formula-handle-first/last-rc form)))
4754 (if (and (string-match org-table-range-regexp form)
4755 (> (length (match-string 0 form)) 1))
4757 (org-table-get-range (match-string 0 form) tbeg 1))
4760 (provide 'org-table)
4762 ;;; org-table.el ends here