1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004-2012 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, otherwise, if table is not sent, the functions
56 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
57 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
58 In the optimized version, the table editor takes over all simple keys that
59 normally just insert a character. In tables, the characters are inserted
60 in a way to minimize disturbing the table structure (i.e. in overwrite mode
61 for empty fields). Outside tables, the correct binding of the keys is
64 The default for this option is t if the optimized version is also used in
65 Org-mode. See the variable `org-enable-table-editor' for details. Changing
66 this variable requires a restart of Emacs to become effective."
70 (defcustom orgtbl-radio-table-templates
71 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
72 % END RECEIVE ORGTBL %n
74 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
77 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
78 @c END RECEIVE ORGTBL %n
80 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
83 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
84 <!-- END RECEIVE ORGTBL %n -->
86 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
89 "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 matching dline (most likely te reference 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 (delq nil
(mapcar (lambda (x) (when (listp x
) x
))
1751 (org-table-to-lisp))))))
1752 (delete-region (org-table-begin) (org-table-end))
1753 (insert (mapconcat (lambda(x) (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1757 (defun org-table-wrap-region (arg)
1758 "Wrap several fields in a column like a paragraph.
1759 This is useful if you'd like to spread the contents of a field over several
1760 lines, in order to keep the table compact.
1762 If there is an active region, and both point and mark are in the same column,
1763 the text in the column is wrapped to minimum width for the given number of
1764 lines. Generally, this makes the table more compact. A prefix ARG may be
1765 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1766 formats the selected text to two lines. If the region was longer than two
1767 lines, the remaining lines remain empty. A negative prefix argument reduces
1768 the current number of lines by that amount. The wrapped text is pasted back
1769 into the table. If you formatted it to more lines than it was before, fields
1770 further down in the table get overwritten - so you might need to make space in
1773 If there is no region, the current field is split at the cursor position and
1774 the text fragment to the right of the cursor is prepended to the field one
1777 If there is no region, but you specify a prefix ARG, the current field gets
1778 blank, and the content is appended to the field above."
1780 (org-table-check-inside-data-field)
1781 (if (org-region-active-p)
1782 ;; There is a region: fill as a paragraph
1783 (let* ((beg (region-beginning))
1784 (cline (save-excursion (goto-char beg
) (org-current-line)))
1785 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1787 (org-table-cut-region (region-beginning) (region-end))
1788 (if (> (length (car org-table-clip
)) 1)
1789 (error "Region must be limited to single column"))
1790 (setq nlines
(if arg
1792 (+ (length org-table-clip
) arg
)
1794 (length org-table-clip
)))
1795 (setq org-table-clip
1796 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1798 (org-goto-line cline
)
1799 (org-table-goto-column ccol
)
1800 (org-table-paste-rectangle))
1801 ;; No region, split the current field at point
1802 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1803 (skip-chars-forward "^\r\n|"))
1805 ;; combine with field above
1806 (let ((s (org-table-blank-field))
1807 (col (org-table-current-column)))
1808 (beginning-of-line 0)
1809 (while (org-at-table-hline-p) (beginning-of-line 0))
1810 (org-table-goto-column col
)
1811 (skip-chars-forward "^|")
1812 (skip-chars-backward " ")
1813 (insert " " (org-trim s
))
1816 (if (looking-at "\\([^|]+\\)+|")
1817 (let ((s (match-string 1)))
1818 (replace-match " |")
1819 (goto-char (match-beginning 0))
1820 (org-table-next-row)
1821 (insert (org-trim s
) " ")
1823 (org-table-next-row)))))
1825 (defvar org-field-marker nil
)
1827 (defun org-table-edit-field (arg)
1828 "Edit table field in a different window.
1829 This is mainly useful for fields that contain hidden parts.
1830 When called with a \\[universal-argument] prefix, just make the full field visible so that
1831 it can be edited in place."
1835 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
1837 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1838 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1839 (remove-text-properties b e
'(org-cwidth t invisible t
1840 display t intangible t
))
1841 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1842 (font-lock-fontify-block))))
1844 (let ((pos (move-marker (make-marker) (point)))
1846 (if (eq org-table-use-standard-references t
)
1847 (concat (org-number-to-letters (org-table-current-column))
1848 (int-to-string (org-table-current-dline)))
1849 (concat "@" (int-to-string (org-table-current-dline))
1850 "$" (int-to-string (org-table-current-column)))))
1851 (field (org-table-get-field))
1852 (cw (current-window-configuration))
1855 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
1856 (when (and (local-variable-p 'org-field-marker
)
1857 (markerp org-field-marker
))
1858 (move-marker org-field-marker nil
))
1860 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
1861 (let ((org-inhibit-startup t
)) (org-mode))
1863 (setq truncate-lines nil
)
1865 (goto-char (setq p
(point-max)))
1866 (insert (org-trim field
))
1867 (remove-text-properties p
(point-max)
1868 '(invisible t org-cwidth t display t
1871 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1872 (org-set-local 'org-window-configuration cw
)
1873 (org-set-local 'org-field-marker pos
)
1874 (message "Edit and finish with C-c C-c")))))
1876 (defun org-table-finish-edit-field ()
1877 "Finish editing a table data field.
1878 Remove all newline characters, insert the result into the table, realign
1879 the table and kill the editing buffer."
1880 (let ((pos org-field-marker
)
1881 (cw org-window-configuration
)
1882 (cb (current-buffer))
1884 (goto-char (point-min))
1885 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1886 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1887 (replace-match " "))
1888 (setq text
(org-trim (buffer-string)))
1889 (set-window-configuration cw
)
1891 (select-window (get-buffer-window (marker-buffer pos
)))
1893 (move-marker pos nil
)
1894 (org-table-check-inside-data-field)
1895 (org-table-get-field nil text
)
1897 (message "New field value inserted")))
1899 (define-minor-mode org-table-follow-field-mode
1900 "Minor mode to make the table field editor window follow the cursor.
1901 When this mode is active, the field editor window will always show the
1902 current field. The mode exits automatically when the cursor leaves the
1903 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
1904 nil
" TblFollow" nil
1905 (if org-table-follow-field-mode
1906 (org-add-hook 'post-command-hook
'org-table-follow-fields-with-editor
1908 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
1909 (let* ((buf (get-buffer "*Org Table Edit Field*"))
1910 (win (and buf
(get-buffer-window buf
))))
1911 (when win
(delete-window win
))
1913 (with-current-buffer buf
1914 (move-marker org-field-marker nil
))
1915 (kill-buffer buf
)))))
1917 (defun org-table-follow-fields-with-editor ()
1918 (if (and org-table-exit-follow-field-mode-when-leaving-table
1919 (not (org-at-table-p)))
1920 ;; We have left the table, exit the follow mode
1921 (org-table-follow-field-mode -
1)
1922 (when (org-table-check-inside-data-field 'noerror
)
1923 (let ((win (selected-window)))
1924 (org-table-edit-field nil
)
1925 (org-fit-window-to-buffer)
1926 (select-window win
)))))
1928 (defvar org-timecnt
) ; dynamically scoped parameter
1930 (defun org-table-sum (&optional beg end nlast
)
1931 "Sum numbers in region of current table column.
1932 The result will be displayed in the echo area, and will be available
1933 as kill to be inserted with \\[yank].
1935 If there is an active region, it is interpreted as a rectangle and all
1936 numbers in that rectangle will be summed. If there is no active
1937 region and point is located in a table column, sum all numbers in that
1940 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1941 numbers are assumed to be times as well (in decimal hours) and the
1942 numbers are added as such.
1944 If NLAST is a number, only the NLAST fields will actually be summed."
1947 (let (col (org-timecnt 0) diff h m s org-table-clip
)
1949 ((and beg end
)) ; beg and end given explicitly
1950 ((org-region-active-p)
1951 (setq beg
(region-beginning) end
(region-end)))
1953 (setq col
(org-table-current-column))
1954 (goto-char (org-table-begin))
1955 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
1956 (error "No table data"))
1957 (org-table-goto-column col
)
1959 (goto-char (org-table-end))
1960 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
1961 (error "No table data"))
1962 (org-table-goto-column col
)
1963 (setq end
(point))))
1964 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
1965 (items1 (cond ((not nlast
) items
)
1966 ((>= nlast
(length items
)) items
)
1967 (t (setq items
(reverse items
))
1968 (setcdr (nthcdr (1- nlast
) items
) nil
)
1970 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
1972 (res (apply '+ numbers
))
1973 (sres (if (= org-timecnt
0)
1974 (number-to-string res
)
1975 (setq diff
(* 3600 res
)
1976 h
(floor (/ diff
3600)) diff
(mod diff
3600)
1977 m
(floor (/ diff
60)) diff
(mod diff
60)
1979 (format "%d:%02d:%02d" h m s
))))
1981 (if (org-called-interactively-p 'interactive
)
1983 (substitute-command-keys
1984 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
1985 (length numbers
) sres
))))
1988 (defun org-table-get-number-for-summing (s)
1990 (if (string-match "^ *|? *" s
)
1991 (setq s
(replace-match "" nil nil s
)))
1992 (if (string-match " *|? *$" s
)
1993 (setq s
(replace-match "" nil nil s
)))
1994 (setq n
(string-to-number s
))
1996 ((and (string-match "0" s
)
1997 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
1998 ((string-match "\\`[ \t]+\\'" s
) nil
)
1999 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2000 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2001 (m (string-to-number (or (match-string 2 s
) "0")))
2002 (s (string-to-number (or (match-string 4 s
) "0"))))
2003 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2004 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2008 (defun org-table-current-field-formula (&optional key noerror
)
2009 "Return the formula active for the current field.
2010 Assumes that specials are in place.
2011 If KEY is given, return the key to this formula.
2012 Otherwise return the formula preceded with \"=\" or \":=\"."
2013 (let* ((name (car (rassoc (list (org-current-line)
2014 (org-table-current-column))
2015 org-table-named-field-locations
)))
2016 (col (org-table-current-column))
2017 (scol (int-to-string col
))
2018 (ref (format "@%d$%d" (org-table-current-dline) col
))
2019 (stored-list (org-table-get-stored-formulas noerror
))
2020 (ass (or (assoc name stored-list
)
2021 (assoc ref stored-list
)
2022 (assoc scol stored-list
))))
2025 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
2028 (defun org-table-get-formula (&optional equation named
)
2029 "Read a formula from the minibuffer, offer stored formula as default.
2030 When NAMED is non-nil, look for a named equation."
2031 (let* ((stored-list (org-table-get-stored-formulas))
2032 (name (car (rassoc (list (org-current-line)
2033 (org-table-current-column))
2034 org-table-named-field-locations
)))
2035 (ref (format "@%d$%d" (org-table-current-dline)
2036 (org-table-current-column)))
2037 (refass (assoc ref stored-list
))
2038 (nameass (assoc name stored-list
))
2040 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
2043 (int-to-string (org-table-current-column))))
2044 (dummy (and (or nameass refass
) (not named
)
2045 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2047 (name (or name ref
))
2048 (org-table-may-need-update nil
)
2049 (stored (cdr (assoc scol stored-list
)))
2051 ((and stored equation
(string-match "^ *=? *$" equation
))
2055 (t (org-table-formula-from-user
2057 (org-table-formula-to-user
2058 (format "%s formula %s%s="
2059 (if named
"Field" "Column")
2060 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
2062 (if stored
(org-table-formula-to-user stored
) "")
2063 'org-table-formula-history
2066 (when (not (string-match "\\S-" eq
))
2068 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2069 (org-table-store-formulas stored-list
)
2070 (error "Formula removed"))
2071 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2072 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2073 (if (and name
(not named
))
2074 ;; We set the column equation, delete the named one.
2075 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2078 (setcdr (assoc scol stored-list
) eq
)
2079 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2080 (if (or mustsave
(not (equal stored eq
)))
2081 (org-table-store-formulas stored-list
))
2084 (defun org-table-store-formulas (alist)
2085 "Store the list of formulas below the current table."
2086 (setq alist
(sort alist
'org-table-formula-less-p
))
2088 (goto-char (org-table-end))
2089 (if (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM:\\(.*\n?\\)")
2091 ;; don't overwrite TBLFM, we might use text properties to store stuff
2092 (goto-char (match-beginning 2))
2093 (delete-region (match-beginning 2) (match-end 0)))
2094 (org-indent-line-function)
2095 (insert "#+TBLFM:"))
2097 (mapconcat (lambda (x)
2099 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2100 (car x
) "=" (cdr x
)))
2104 (defsubst org-table-formula-make-cmp-string
(a)
2105 (when (string-match "\\`$[<>]" a
)
2106 (let ((arrow (string-to-char (substring a
1))))
2107 ;; Fake a high number to make sure this is sorted at the end.
2108 (setq a
(org-table-formula-handle-first/last-rc a
))
2109 (setq a
(format "$%d" (+ 10000
2110 (if (= arrow ?
<) -
1000 0)
2111 (string-to-number (substring a
1)))))))
2113 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2117 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2119 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2121 (concat "@@" (match-string 5 a
))))))
2123 (defun org-table-formula-less-p (a b
)
2124 "Compare two formulas for sorting."
2125 (let ((as (org-table-formula-make-cmp-string (car a
)))
2126 (bs (org-table-formula-make-cmp-string (car b
))))
2127 (and as bs
(string< as bs
))))
2129 (defun org-table-get-stored-formulas (&optional noerror
)
2130 "Return an alist with the stored formulas directly after current table."
2132 (let (scol eq eq-alist strings string seen
)
2134 (goto-char (org-table-end))
2135 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
2136 (setq strings
(org-split-string (org-match-string-no-properties 2)
2138 (while (setq string
(pop strings
))
2139 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2140 (setq scol
(if (match-end 2)
2141 (match-string 2 string
)
2142 (match-string 1 string
))
2143 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2144 (concat "$" scol
) scol
)
2145 eq
(match-string 3 string
)
2146 eq-alist
(cons (cons scol eq
) eq-alist
))
2147 (if (member scol seen
)
2150 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2153 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2154 (push scol seen
))))))
2155 (nreverse eq-alist
)))
2157 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2158 "Modify the equations after the table structure has been edited.
2159 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2160 For all numbers larger than LIMIT, shift them by DELTA."
2162 (goto-char (org-table-end))
2163 (when (looking-at "[ \t]*#\\+TBLFM:")
2164 (let ((re (concat key
"\\([0-9]+\\)"))
2167 (if (or (equal key
"$") (equal key
"$LR"))
2168 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2169 (regexp-quote key
) remove
)
2170 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2173 (while (re-search-forward re2
(point-at-eol) t
)
2174 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2175 (if (equal (char-before (match-beginning 0)) ?.
)
2176 (error "Change makes TBLFM term %s invalid. Use undo to recover."
2178 (replace-match "")))))
2179 (while (re-search-forward re
(point-at-eol) t
)
2180 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2181 (setq s
(match-string 1) n
(string-to-number s
))
2183 ((setq a
(assoc s replace
))
2184 (replace-match (concat key
(cdr a
)) t t
))
2185 ((and limit
(> n limit
))
2186 (replace-match (concat key
(int-to-string (+ n delta
)))
2189 (defun org-table-get-specials ()
2190 "Get the column names and local parameters for this table."
2192 (let ((beg (org-table-begin)) (end (org-table-end))
2193 names name fields fields1 field cnt
2194 c v l line col types dlines hlines last-dline
)
2195 (setq org-table-column-names nil
2196 org-table-local-parameters nil
2197 org-table-named-field-locations nil
2198 org-table-current-begin-line nil
2199 org-table-current-begin-pos nil
2200 org-table-current-line-types nil
2201 org-table-current-ncol
0)
2203 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2204 (setq names
(org-split-string (match-string 1) " *| *")
2206 (while (setq name
(pop names
))
2208 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name
)
2209 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2210 (setq org-table-column-names
(nreverse org-table-column-names
))
2211 (setq org-table-column-name-regexp
2212 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2214 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2215 (setq fields
(org-split-string (match-string 1) " *| *"))
2216 (while (setq field
(pop fields
))
2217 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2218 (push (cons (match-string 1 field
) (match-string 2 field
))
2219 org-table-local-parameters
))))
2221 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2222 (setq c
(match-string 1)
2223 fields
(org-split-string (match-string 2) " *| *"))
2225 (beginning-of-line (if (equal c
"_") 2 0))
2226 (setq line
(org-current-line) col
1)
2227 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2228 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2229 (while (and fields1
(setq field
(pop fields
)))
2230 (setq v
(pop fields1
) col
(1+ col
))
2231 (when (and (stringp field
) (stringp v
)
2232 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field
))
2233 (push (cons field v
) org-table-local-parameters
)
2234 (push (list field line col
) org-table-named-field-locations
))))
2235 ;; Analyse the line types
2237 (setq org-table-current-begin-line
(org-current-line)
2238 org-table-current-begin-pos
(point)
2239 l org-table-current-begin-line
)
2240 (while (looking-at "[ \t]*|\\(-\\)?")
2241 (push (if (match-end 1) 'hline
'dline
) types
)
2242 (if (match-end 1) (push l hlines
) (push l dlines
))
2243 (beginning-of-line 2)
2245 (push 'hline types
) ;; add an imaginary extra hline to the end
2246 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2247 last-dline
(car dlines
)
2248 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2249 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2250 (org-goto-line last-dline
)
2251 (let* ((l last-dline
)
2252 (fields (org-split-string
2253 (buffer-substring (point-at-bol) (point-at-eol))
2255 (nfields (length fields
))
2257 (setq org-table-current-ncol nfields
)
2258 (loop for i from
1 to nfields do
2259 (push (list (format "LR%d" i
) l i
) al
)
2260 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2261 (setq org-table-named-field-locations
2262 (append org-table-named-field-locations al
))
2263 (setq org-table-local-parameters
2264 (append org-table-local-parameters al2
))))))
2266 (defun org-table-maybe-eval-formula ()
2267 "Check if the current field starts with \"=\" or \":=\".
2268 If yes, store the formula and apply it."
2269 ;; We already know we are in a table. Get field will only return a formula
2270 ;; when appropriate. It might return a separator line, but no problem.
2271 (when org-table-formula-evaluate-inline
2272 (let* ((field (org-trim (or (org-table-get-field) "")))
2274 (when (string-match "^:?=\\(.*\\)" field
)
2275 (setq named
(equal (string-to-char field
) ?
:)
2276 eq
(match-string 1 field
))
2277 (if (or (fboundp 'calc-eval
)
2278 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2279 (org-table-eval-formula (if named
'(4) nil
)
2280 (org-table-formula-from-user eq
))
2281 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2283 (defvar org-recalc-commands nil
2284 "List of commands triggering the recalculation of a line.
2285 Will be filled automatically during use.")
2287 (defvar org-recalc-marks
2288 '((" " .
"Unmarked: no special line, no automatic recalculation")
2289 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2290 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2291 ("!" .
"Column name definition line. Reference in formula as $name.")
2292 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2293 ("_" .
"Names for values in row below this one.")
2294 ("^" .
"Names for values in row above this one.")))
2296 (defun org-table-rotate-recalc-marks (&optional newchar
)
2297 "Rotate the recalculation mark in the first column.
2298 If in any row, the first field is not consistent with a mark,
2299 insert a new column for the markers.
2300 When there is an active region, change all the lines in the region,
2301 after prompting for the marking character.
2302 After each change, a message will be displayed indicating the meaning
2305 (unless (org-at-table-p) (error "Not at a table"))
2306 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2307 (beg (org-table-begin))
2308 (end (org-table-end))
2309 (l (org-current-line))
2310 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2311 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2315 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2316 (col (org-table-current-column))
2317 (forcenew (car (assoc newchar org-recalc-marks
)))
2320 (message "Change region to what mark? Type # * ! $ or SPC: ")
2321 (setq newchar
(char-to-string (read-char-exclusive))
2322 forcenew
(car (assoc newchar org-recalc-marks
))))
2323 (if (and newchar
(not forcenew
))
2324 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2326 (if l1
(org-goto-line l1
))
2328 (beginning-of-line 1)
2329 (unless (looking-at org-table-dataline-regexp
)
2330 (error "Not at a table data line")))
2332 (org-table-goto-column 1)
2333 (org-table-insert-column)
2334 (org-table-goto-column (1+ col
)))
2335 (setq epos
(point-at-eol))
2337 (beginning-of-line 1)
2338 (org-table-get-field
2339 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2341 (setq new
(or forcenew
2342 (cadr (member (match-string 1) marks
))))
2348 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2349 (and (looking-at org-table-dataline-regexp
)
2350 (org-table-get-field 1 (concat " " new
" "))))
2351 (org-goto-line l1
)))
2352 (if (not (= epos
(point-at-eol))) (org-table-align))
2354 (and (org-called-interactively-p 'interactive
)
2355 (message "%s" (cdr (assoc new org-recalc-marks
))))))
2357 (defun org-table-maybe-recalculate-line ()
2358 "Recompute the current line if marked for it, and if we haven't just done it."
2360 (and org-table-allow-automatic-line-recalculation
2361 (not (and (memq last-command org-recalc-commands
)
2362 (equal org-last-recalc-line
(org-current-line))))
2363 (save-excursion (beginning-of-line 1)
2364 (looking-at org-table-auto-recalculate-regexp
))
2365 (org-table-recalculate) t
))
2368 (defsubst org-set-calc-mode
(var &optional value
)
2370 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2371 ("R" calc-angle-mode rad
)
2372 ("F" calc-prefer-frac t
)
2373 ("S" calc-symbolic-mode t
)))
2374 value
(nth 2 var
) var
(nth 1 var
)))
2375 (if (memq var modes
)
2376 (setcar (cdr (memq var modes
)) value
)
2377 (cons var
(cons value modes
)))
2380 (defun org-table-eval-formula (&optional arg equation
2381 suppress-align suppress-const
2382 suppress-store suppress-analysis
)
2383 "Replace the table field value at the cursor by the result of a calculation.
2385 This function makes use of Dave Gillespie's Calc package, in my view the
2386 most exciting program ever written for GNU Emacs. So you need to have Calc
2387 installed in order to use this function.
2389 In a table, this command replaces the value in the current field with the
2390 result of a formula. It also installs the formula as the \"current\" column
2391 formula, by storing it in a special line below the table. When called
2392 with a `C-u' prefix, the current field must be a named field, and the
2393 formula is installed as valid in only this specific field.
2395 When called with two `C-u' prefixes, insert the active equation
2396 for the field back into the current field, so that it can be
2397 edited there. This is useful in order to use \\[org-table-show-reference]
2398 to check the referenced fields.
2400 When called, the command first prompts for a formula, which is read in
2401 the minibuffer. Previously entered formulas are available through the
2402 history list, and the last used formula is offered as a default.
2403 These stored formulas are adapted correctly when moving, inserting, or
2404 deleting columns with the corresponding commands.
2406 The formula can be any algebraic expression understood by the Calc package.
2407 For details, see the Org-mode manual.
2409 This function can also be called from Lisp programs and offers
2410 additional arguments: EQUATION can be the formula to apply. If this
2411 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2412 used to speed-up recursive calls by by-passing unnecessary aligns.
2413 SUPPRESS-CONST suppresses the interpretation of constants in the
2414 formula, assuming that this has been done already outside the function.
2415 SUPPRESS-STORE means the formula should not be stored, either because
2416 it is already stored, or because it is a modified equation that should
2417 not overwrite the stored one."
2419 (org-table-check-inside-data-field)
2420 (or suppress-analysis
(org-table-get-specials))
2421 (if (equal arg
'(16))
2422 (let ((eq (org-table-current-field-formula)))
2423 (or eq
(error "No equation active for current field"))
2424 (org-table-get-field nil eq
)
2426 (setq org-table-may-need-update t
))
2428 (ndown (if (integerp arg
) arg
1))
2429 (org-table-automatic-realign nil
)
2430 (case-fold-search nil
)
2432 (formula (if (and equation suppress-store
)
2434 (org-table-get-formula equation
(equal arg
'(4)))))
2435 (n0 (org-table-current-column))
2436 (modes (copy-sequence org-calc-default-modes
))
2437 (numbers nil
) ; was a variable, now fixed default
2439 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2440 duration duration-output-format
)
2441 ;; Parse the format string. Since we have a lot of modes, this is
2442 ;; a lot of work. However, I think calc still uses most of the time.
2443 (if (string-match ";" formula
)
2444 (let ((tmp (org-split-string formula
";")))
2445 (setq formula
(car tmp
)
2446 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2448 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2449 (setq c
(string-to-char (match-string 1 fmt
))
2450 n
(string-to-number (match-string 2 fmt
)))
2452 (setq modes
(org-set-calc-mode 'calc-internal-prec n
))
2453 (setq modes
(org-set-calc-mode
2455 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2456 (?s . sci
) (?e . eng
))))
2458 (setq fmt
(replace-match "" t t fmt
)))
2459 (if (string-match "T" fmt
)
2460 (setq duration t numbers t
2461 duration-output-format nil
2462 fmt
(replace-match "" t t fmt
)))
2463 (if (string-match "t" fmt
)
2465 duration-output-format org-table-duration-custom-format
2467 fmt
(replace-match "" t t fmt
)))
2468 (if (string-match "N" fmt
)
2470 fmt
(replace-match "" t t fmt
)))
2471 (if (string-match "L" fmt
)
2473 fmt
(replace-match "" t t fmt
)))
2474 (if (string-match "E" fmt
)
2476 fmt
(replace-match "" t t fmt
)))
2477 (while (string-match "[DRFS]" fmt
)
2478 (setq modes
(org-set-calc-mode (match-string 0 fmt
)))
2479 (setq fmt
(replace-match "" t t fmt
)))
2480 (unless (string-match "\\S-" fmt
)
2482 (if (and (not suppress-const
) org-table-formula-use-constants
)
2483 (setq formula
(org-table-formula-substitute-names formula
)))
2484 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2486 (setq fields
(org-split-string
2488 (buffer-substring (point-at-bol) (point-at-eol)))
2490 ;; replace fields with duration values if relevant
2493 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2496 (setq fields
(mapcar
2497 (lambda (x) (number-to-string (string-to-number x
)))
2499 (setq ndown
(1- ndown
))
2500 (setq form
(copy-sequence formula
)
2501 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2502 (if (and lispp literal
) (setq lispp
'literal
))
2504 ;; Insert row and column number of formula result field
2505 (while (string-match "[@$]#" form
)
2510 (if (equal (substring form
(match-beginning 0)
2511 (1+ (match-beginning 0)))
2513 (org-table-current-dline)
2514 (org-table-current-column))))
2517 ;; Check for old vertical references
2518 (setq form
(org-table-rewrite-old-row-references form
))
2519 ;; Insert remote references
2520 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2524 (org-table-make-reference
2525 (org-table-get-remote-range
2526 (match-string 1 form
) (match-string 2 form
))
2527 keep-empty numbers lispp
))
2529 ;; Insert complex ranges
2530 (while (and (string-match org-table-range-regexp form
)
2531 (> (length (match-string 0 form
)) 1))
2532 (setq formrg
(save-match-data
2533 (org-table-get-range (match-string 0 form
) nil n0
)))
2536 (org-table-make-reference
2537 ;; possibly handle durations
2540 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2541 (org-table-time-string-to-seconds formrg
))
2543 keep-empty numbers lispp
)))
2544 (if (not (save-match-data
2545 (string-match (regexp-quote form
) formrpl
)))
2546 (setq form
(replace-match formrpl t t form
))
2547 (error "Spreadsheet error: invalid reference \"%s\"" form
)))
2548 ;; Insert simple ranges
2549 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2553 (org-table-make-reference
2555 fields
(string-to-number (match-string 1 form
))
2556 (string-to-number (match-string 2 form
)))
2557 keep-empty numbers lispp
))
2560 ;; Insert the references to fields in same row
2561 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2562 (setq n
(+ (string-to-number (match-string 1 form
))
2563 (if (match-end 2) n0
0))
2564 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
))
2565 (unless x
(error "Invalid field specifier \"%s\""
2566 (match-string 0 form
)))
2567 (setq form
(replace-match
2569 (org-table-make-reference x nil numbers lispp
))
2573 (setq ev
(condition-case nil
2574 (eval (eval (read form
)))
2576 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2577 ev
(if duration
(org-table-time-seconds-to-string
2578 (string-to-number ev
)
2579 duration-output-format
) ev
))
2580 (or (fboundp 'calc-eval
)
2581 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2582 (setq ev
(calc-eval (cons form modes
) (if numbers
'num
))
2583 ev
(if duration
(org-table-time-seconds-to-string
2584 (string-to-number ev
)
2585 duration-output-format
) ev
)))
2587 (when org-table-formula-debug
2588 (with-output-to-temp-buffer "*Substitution History*"
2589 (princ (format "Substitution history of formula
2593 $1-> %s\n" orig formula form0 form
))
2595 (princ (format " %s^\nError: %s"
2596 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2597 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2599 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2600 (setq bw
(get-buffer-window "*Substitution History*"))
2601 (org-fit-window-to-buffer bw
)
2602 (unless (and (org-called-interactively-p 'any
) (not ndown
))
2603 (unless (let (inhibit-redisplay)
2604 (y-or-n-p "Debugging Formula. Continue to next? "))
2609 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2610 (org-table-justify-field-maybe
2611 (format org-table-formula-field-format
2612 (if fmt
(format fmt
(string-to-number ev
)) ev
)))
2613 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2614 (call-interactively 'org-return
)
2616 (and down
(org-table-maybe-recalculate-line))
2617 (or suppress-align
(and org-table-may-need-update
2618 (org-table-align))))))
2620 (defun org-table-put-field-property (prop value
)
2622 (put-text-property (progn (skip-chars-backward "^|") (point))
2623 (progn (skip-chars-forward "^|") (point))
2626 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2627 "Get a calc vector from a column, according to descriptor DESC.
2628 Optional arguments TBEG and COL can give the beginning of the table and
2629 the current column, to avoid unnecessary parsing.
2631 HIGHLIGHT means just highlight the range.
2633 When CORNERS-ONLY is set, only return the corners of the range as
2634 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2635 in the buffer and column1 and column2 are table column numbers."
2636 (if (not (equal (string-to-char desc
) ?
@))
2637 (setq desc
(concat "@" desc
)))
2639 (or tbeg
(setq tbeg
(org-table-begin)))
2640 (or col
(setq col
(org-table-current-column)))
2641 (let ((thisline (org-current-line))
2642 beg end c1 c2 r1 r2 rangep tmp
)
2643 (unless (string-match org-table-range-regexp desc
)
2644 (error "Invalid table range specifier `%s'" desc
))
2645 (setq rangep
(match-end 3)
2646 r1
(and (match-end 1) (match-string 1 desc
))
2647 r2
(and (match-end 4) (match-string 4 desc
))
2648 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2649 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2651 (and c1
(setq c1
(+ (string-to-number c1
)
2652 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2653 (and c2
(setq c2
(+ (string-to-number c2
)
2654 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2655 (if (equal r1
"") (setq r1 nil
))
2656 (if (equal r2
"") (setq r2 nil
))
2657 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2658 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2659 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2660 (if (not r1
) (setq r1 thisline
))
2661 (if (not r2
) (setq r2 thisline
))
2662 (if (not c1
) (setq c1 col
))
2663 (if (not c2
) (setq c2 col
))
2664 (if (and (not corners-only
)
2665 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2669 (while (not (looking-at org-table-dataline-regexp
))
2670 (beginning-of-line 2))
2671 (prog1 (org-trim (org-table-get-field c1
))
2672 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2673 ;; A range, return a vector
2674 ;; First sort the numbers to get a regular rectangle
2675 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2676 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2678 ;; Only return the corners of the range
2680 ;; Copy the range values into a list
2682 (while (not (looking-at org-table-dataline-regexp
))
2683 (beginning-of-line 2))
2684 (org-table-goto-column c1
)
2687 (while (not (looking-at org-table-dataline-regexp
))
2688 (beginning-of-line 0))
2689 (org-table-goto-column c2
)
2692 (org-table-highlight-rectangle
2693 beg
(progn (skip-chars-forward "^|\n") (point))))
2694 ;; return string representation of calc vector
2696 (apply 'append
(org-table-copy-region beg end
))))))))
2698 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2699 "Analyze descriptor DESC and retrieve the corresponding line number.
2700 The cursor is currently in line CLINE, the table begins in line BLINE,
2701 and TABLE is a vector with line types."
2702 (if (string-match "^[0-9]+$" desc
)
2703 (aref org-table-dlines
(string-to-number desc
))
2704 (setq cline
(or cline
(org-current-line))
2705 bline
(or bline org-table-current-begin-line
)
2706 table
(or table org-table-current-line-types
))
2708 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2710 (and (not (match-end 3)) (not (match-end 6)))
2711 (and (match-end 3) (match-end 6) (not (match-end 5))))
2712 (error "Invalid row descriptor `%s'" desc
))
2713 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2714 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2715 (odir (and (match-end 5) (match-string 5 desc
)))
2716 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2718 (rel (and (match-end 6)
2719 (or (and (match-end 1) (not (match-end 3)))
2721 (if (and hn
(not hdir
))
2724 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2725 (if (and (not hn
) on
(not odir
))
2726 (error "Should never happen");;(aref org-table-dlines on)
2727 (if (and hn
(> hn
0))
2728 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2729 nil hn cline desc
)))
2731 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2732 rel on cline desc
)))
2735 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2736 "FIXME: Needs more documentation."
2737 (let ((l (length table
)))
2739 (while (and (setq i
(+ i
(if backwards -
1 1)))
2741 (not (eq (aref table i
) type
))
2742 (if (and relative
(eq (aref table i
) 'hline
))
2744 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2745 ((eq org-table-relative-ref-may-cross-hline
'error
)
2746 (error "Row descriptor %s used in line %d crosses hline" desc cline
))
2747 (t (setq i
(- i
(if backwards -
1 1))
2752 (if (or (< i
0) (>= i l
))
2753 (error "Row descriptor %s used in line %d leads outside table"
2757 (defun org-table-rewrite-old-row-references (s)
2758 (if (string-match "&[-+0-9I]" s
)
2759 (error "Formula contains old &row reference, please rewrite using @-syntax")
2762 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2763 "Convert list ELEMENTS to something appropriate to insert into formula.
2764 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2765 NUMBERS indicates that everything should be converted to numbers.
2766 LISPP means to return something appropriate for a Lisp list."
2767 (if (stringp elements
) ; just a single val
2769 (if (eq lispp
'literal
)
2771 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2772 (if (equal elements
"") (setq elements
"0"))
2773 (if numbers
(setq elements
(number-to-string (string-to-number elements
))))
2774 (concat "(" elements
")"))
2778 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2780 (setq elements
(or elements
'("0")))
2784 (if (eq lispp
'literal
)
2786 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2788 (concat "[" (mapconcat
2790 (if numbers
(number-to-string (string-to-number x
)) x
))
2794 (defun org-table-recalculate (&optional all noalign
)
2795 "Recalculate the current table line by applying all stored formulas.
2796 With prefix arg ALL, do this for all lines in the table.
2797 With the prefix argument ALL is `(16)' \
2798 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2799 it is the symbol `iterate', recompute the table until it no longer changes.
2800 If NOALIGN is not nil, do not re-align the table after the computations
2801 are done. This is typically used internally to save time, if it is
2802 known that the table will be realigned a little later anyway."
2804 (or (memq this-command org-recalc-commands
)
2805 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2806 (unless (org-at-table-p) (error "Not at a table"))
2807 (if (or (eq all
'iterate
) (equal all
'(16)))
2809 (org-table-get-specials)
2810 (let* ((eqlist (sort (org-table-get-stored-formulas)
2811 (lambda (a b
) (string< (car a
) (car b
)))))
2812 (eqlist1 (copy-sequence eqlist
))
2813 (inhibit-redisplay (not debug-on-error
))
2814 (line-re org-table-dataline-regexp
)
2815 (thisline (org-current-line))
2816 (thiscol (org-table-current-column))
2818 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
2819 ;; Insert constants in all formulas
2822 (when (string-match "\\`$[<>]" (car x
))
2824 (setq x
(cons (substring
2825 (org-table-formula-handle-first/last-rc
2828 (if (assoc (car x
) eqlist1
)
2829 (error "\"%s=\" formula tries to overwrite existing formula for column %s"
2832 (org-table-formula-handle-first/last-rc
(car x
))
2833 (org-table-formula-substitute-names
2834 (org-table-formula-handle-first/last-rc
(cdr x
)))))
2836 ;; Split the equation list
2837 (while (setq eq
(pop eqlist
))
2838 (if (<= (string-to-char (car eq
)) ?
9)
2841 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
2842 ;; Expand ranges in lhs of formulas
2843 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
2845 ;; Get the correct line range to process
2848 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
2849 (goto-char (setq beg
(org-table-begin)))
2850 (if (re-search-forward org-table-calculate-mark-regexp end t
)
2851 ;; This is a table with marked lines, compute selected lines
2852 (setq line-re org-table-recalculate-regexp
)
2853 ;; Move forward to the first non-header line
2854 (if (and (re-search-forward org-table-dataline-regexp end t
)
2855 (re-search-forward org-table-hline-regexp end t
)
2856 (re-search-forward org-table-dataline-regexp end t
))
2857 (setq beg
(match-beginning 0))
2858 nil
))) ;; just leave beg where it is
2859 (setq beg
(point-at-bol)
2860 end
(move-marker (make-marker) (1+ (point-at-eol)))))
2862 (and all
(message "Re-applying formulas to full table..."))
2864 ;; First find the named fields, and mark them untouchable.
2865 ;; Also check if several field/range formulas try to set the same field.
2866 (remove-text-properties beg end
'(org-untouchable t
))
2867 (while (setq eq
(pop eqlname
))
2869 a
(assoc name org-table-named-field-locations
))
2871 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
2873 (when (member name1 seen-fields
)
2874 (error "Several field/range formulas try to set %s" name1
))
2875 (push name1 seen-fields
)
2878 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
2881 (aref org-table-dlines
2882 (string-to-number (match-string 1 name
)))
2883 (error (error "Invalid row number in %s"
2885 (string-to-number (match-string 2 name
)))))
2886 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
2887 (message "Re-applying formula to field: %s" name
)
2888 (org-goto-line (nth 1 a
))
2889 (org-table-goto-column (nth 2 a
))
2890 (push (append a
(list (cdr eq
))) eqlname1
)
2891 (org-table-put-field-property :org-untouchable t
)))
2892 (setq eqlname1
(nreverse eqlname1
))
2894 ;; Now evaluate the column formulas, but skip fields covered by
2897 (while (re-search-forward line-re end t
)
2898 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2899 ;; Unprotected line, recalculate
2900 (and all
(message "Re-applying formulas to full table...(line %d)"
2901 (setq cnt
(1+ cnt
))))
2902 (setq org-last-recalc-line
(org-current-line))
2904 (while (setq entry
(pop eql
))
2905 (org-goto-line org-last-recalc-line
)
2906 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
2907 (unless (get-text-property (point) :org-untouchable
)
2908 (org-table-eval-formula nil
(cdr entry
)
2909 'noalign
'nocst
'nostore
'noanalysis
)))))
2911 ;; Now evaluate the field formulas
2912 (while (setq eq
(pop eqlname1
))
2913 (message "Re-applying formula to field: %s" (car eq
))
2914 (org-goto-line (nth 1 eq
))
2915 (org-table-goto-column (nth 2 eq
))
2916 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
2917 'nostore
'noanalysis
))
2919 (org-goto-line thisline
)
2920 (org-table-goto-column thiscol
)
2921 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
2922 (or noalign
(and org-table-may-need-update
(org-table-align))
2923 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
2925 ;; back to initial position
2926 (message "Re-applying formulas...done")
2927 (org-goto-line thisline
)
2928 (org-table-goto-column thiscol
)
2929 (or noalign
(and org-table-may-need-update
(org-table-align))
2930 (and all
(message "Re-applying formulas...done"))))))
2932 (defun org-table-iterate (&optional arg
)
2933 "Recalculate the table until it does not change anymore.
2934 The maximun number of iterations is 10, but you can choose a different value
2935 with the prefix ARG."
2937 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
2939 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2944 (org-table-recalculate 'all
)
2945 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
2946 (if (not (string= lasttbl thistbl
))
2947 (setq lasttbl thistbl
)
2949 (message "Convergence after %d iterations" i
)
2950 (message "Table was already stable"))
2952 (error "No convergence after %d iterations" i
))))
2954 (defun org-table-recalculate-buffer-tables ()
2955 "Recalculate all tables in the current buffer."
2960 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
2962 (defun org-table-iterate-buffer-tables ()
2963 "Iterate all tables in the buffer, to converge inter-table dependencies."
2966 (checksum (md5 (buffer-string)))
2976 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
2977 (if (equal checksum
(setq c1
(md5 (buffer-string))))
2979 (message "Convergence after %d iterations" (- imax i
))
2981 (setq checksum c1
)))
2982 (error "No convergence after %d iterations" imax
))))))
2984 (defun org-table-expand-lhs-ranges (equations)
2985 "Expand list of formulas.
2986 If some of the RHS in the formulas are ranges or a row reference, expand
2987 them to individual field equations for each field."
2988 (let (e res lhs rhs range r1 r2 c1 c2
)
2989 (while (setq e
(pop equations
))
2990 (setq lhs
(car e
) rhs
(cdr e
))
2992 ((string-match "^@-?[-+I0-9]+\\$-?[0-9]+$" lhs
)
2993 ;; This just refers to one fixed field
2995 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs
)
2996 ;; This just refers to one fixed named field
2998 ((string-match "^@[0-9]+$" lhs
)
2999 (loop for ic from
1 to org-table-current-ncol do
3000 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
3001 (put-text-property 0 (length (caar res
))
3002 :orig-eqn e
(caar res
))))
3004 (setq range
(org-table-get-range lhs org-table-current-begin-pos
3006 (setq r1
(nth 0 range
) c1
(nth 1 range
)
3007 r2
(nth 2 range
) c2
(nth 3 range
))
3008 (setq r1
(org-table-line-to-dline r1
))
3009 (setq r2
(org-table-line-to-dline r2
'above
))
3010 (loop for ir from r1 to r2 do
3011 (loop for ic from c1 to c2 do
3012 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
3013 (put-text-property 0 (length (caar res
))
3014 :orig-eqn e
(caar res
)))))))
3017 (defun org-table-formula-handle-first/last-rc
(s)
3018 "Replace @<, @>, $<, $> with first/last row/column of the table.
3019 So @< and $< will always be replaced with @1 and $1, respectively.
3020 The advantage of these special markers are that structure editing of
3021 the table will not change them, while @1 and $1 will be modified
3022 when a line/row is swapped out of that privileged position. So for
3023 formulas that use a range of rows or columns, it may often be better
3024 to anchor the formula with \"I\" row markers, or to offset from the
3025 borders of the table using the @< @> $< $> makers."
3026 (let (n nmax len char
(start 0))
3027 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3030 (setq start
(match-end 3))
3031 (setq nmax
(if (equal (match-string 1 s
) "@")
3032 (1- (length org-table-dlines
))
3033 org-table-current-ncol
)
3034 len
(- (match-end 2) (match-beginning 2))
3035 char
(string-to-char (match-string 2 s
))
3039 (if (or (< n
1) (> n nmax
))
3040 (error "Reference \"%s\" in expression \"%s\" points outside table"
3041 (match-string 0 s
) s
))
3042 (setq start
(match-beginning 0))
3043 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3046 (defun org-table-formula-substitute-names (f)
3047 "Replace $const with values in string F."
3048 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
3049 ;; First, check for column names
3050 (while (setq start
(string-match org-table-column-name-regexp f start
))
3051 (setq start
(1+ start
))
3052 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
3053 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
3054 ;; Parameters and constants
3056 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
3058 (setq start
(match-end 2))
3059 (setq start
(1+ start
))
3060 (if (setq a
(save-match-data
3061 (org-table-get-constant (match-string 1 f
))))
3062 (setq f
(replace-match
3063 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
3064 (if org-table-formula-debug
3065 (put-text-property 0 (length f
) :orig-formula f1 f
))
3068 (defun org-table-get-constant (const)
3069 "Find the value for a parameter or constant in a formula.
3070 Parameters get priority."
3071 (or (cdr (assoc const org-table-local-parameters
))
3072 (cdr (assoc const org-table-formula-constants-local
))
3073 (cdr (assoc const org-table-formula-constants
))
3074 (and (fboundp 'constants-get
) (constants-get const
))
3075 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3076 (org-entry-get nil
(substring const
5) 'inherit
))
3079 (defvar org-table-fedit-map
3080 (let ((map (make-sparse-keymap)))
3081 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3082 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3083 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3084 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3085 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3086 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3087 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3088 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3089 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3090 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3091 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3092 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3093 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3094 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3095 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3096 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3097 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3098 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3099 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3100 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3103 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3105 ["Finish and Install" org-table-fedit-finish t
]
3106 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3107 ["Abort" org-table-fedit-abort t
]
3109 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3110 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3112 "Shift Reference at Point"
3113 ["Up" org-table-fedit-ref-up t
]
3114 ["Down" org-table-fedit-ref-down t
]
3115 ["Left" org-table-fedit-ref-left t
]
3116 ["Right" org-table-fedit-ref-right t
]
3118 "Change Test Row for Column Formulas"
3119 ["Up" org-table-fedit-line-up t
]
3120 ["Down" org-table-fedit-line-down t
]
3122 ["Scroll Table Window" org-table-fedit-scroll t
]
3123 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3124 ["Show Table Grid" org-table-fedit-toggle-coordinates
3125 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3126 org-table-overlay-coordinates
)]
3128 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3129 :style toggle
:selected org-table-buffer-is-an
]))
3133 (defun org-table-edit-formulas ()
3134 "Edit the formulas of the current table in a separate buffer."
3136 (when (save-excursion (beginning-of-line 1) (looking-at "[ \t]*#\\+TBLFM"))
3137 (beginning-of-line 0))
3138 (unless (org-at-table-p) (error "Not at a table"))
3139 (org-table-get-specials)
3140 (let ((key (org-table-current-field-formula 'key
'noerror
))
3141 (eql (sort (org-table-get-stored-formulas 'noerror
)
3142 'org-table-formula-less-p
))
3143 (pos (move-marker (make-marker) (point)))
3145 (wc (current-window-configuration))
3146 (sel-win (selected-window))
3147 (titles '((column .
"# Column Formulas\n")
3148 (field .
"# Field and Range Formulas\n")
3149 (named .
"# Named Field Formulas\n")))
3151 (org-switch-to-buffer-other-window "*Edit Formulas*")
3153 ;; Keep global-font-lock-mode from turning on font-lock-mode
3154 (let ((font-lock-global-modes '(not fundamental-mode
)))
3156 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
3157 (org-set-local 'org-pos pos
)
3158 (org-set-local 'org-window-configuration wc
)
3159 (org-set-local 'org-selected-window sel-win
)
3160 (use-local-map org-table-fedit-map
)
3161 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3162 (easy-menu-add org-table-fedit-menu
)
3163 (setq startline
(org-current-line))
3164 (while (setq entry
(pop eql
))
3166 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3167 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3168 ((string-match "^[0-9]" (car entry
)) 'column
)
3170 (when (setq title
(assq type titles
))
3171 (or (bobp) (insert "\n"))
3172 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3173 (setq titles
(remove title titles
)))
3174 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3175 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3176 (car entry
) " = " (cdr entry
) "\n"))
3177 (remove-text-properties 0 (length s
) '(face nil
) s
)
3179 (if (eq org-table-use-standard-references t
)
3180 (org-table-fedit-toggle-ref-type))
3181 (org-goto-line startline
)
3182 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3184 (defun org-table-fedit-post-command ()
3185 (when (not (memq this-command
'(lisp-complete-symbol)))
3186 (let ((win (selected-window)))
3189 (org-table-show-reference)
3191 (select-window win
)))))
3193 (defun org-table-formula-to-user (s)
3194 "Convert a formula from internal to user representation."
3195 (if (eq org-table-use-standard-references t
)
3196 (org-table-convert-refs-to-an s
)
3199 (defun org-table-formula-from-user (s)
3200 "Convert a formula from user to internal representation."
3201 (if org-table-use-standard-references
3202 (org-table-convert-refs-to-rc s
)
3205 (defun org-table-convert-refs-to-rc (s)
3206 "Convert spreadsheet references from A7 to @7$28.
3207 Works for single references, but also for entire formulas and even the
3210 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^)]*)\\)" s start
)
3213 ;; format match, just advance
3214 (setq start
(match-end 0)))
3215 ((and (> (match-beginning 0) 0)
3216 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3217 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3218 ;; 3.e5 or something like this.
3219 (setq start
(match-end 0)))
3220 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3221 ;; (member (match-string 1 s)
3222 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3224 ;; function name, just advance
3225 (setq start
(match-end 0)))
3227 (setq start
(match-beginning 0)
3229 (if (equal (match-string 2 s
) "&")
3230 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3232 (string-to-number (match-string 2 s
))
3233 (org-letters-to-number (match-string 1 s
))))
3237 (defun org-table-convert-refs-to-an (s)
3238 "Convert spreadsheet references from to @7$28 to AB7.
3239 Works for single references, but also for entire formulas and even the
3241 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3242 (setq s
(replace-match
3244 (org-number-to-letters
3245 (string-to-number (match-string 2 s
)))
3246 (string-to-number (match-string 1 s
)))
3248 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3249 (setq s
(replace-match (concat "\\1"
3250 (org-number-to-letters
3251 (string-to-number (match-string 2 s
))) "&")
3255 (defun org-letters-to-number (s)
3256 "Convert a base 26 number represented by letters into an integer.
3257 For example: AB -> 28."
3260 (while (> (length s
) 0)
3261 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3265 (defun org-number-to-letters (n)
3266 "Convert an integer into a base 26 number represented by letters.
3267 For example: 28 -> AB."
3270 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3274 (defun org-table-time-string-to-seconds (s)
3275 "Convert a time string into numerical duration in seconds.
3276 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3277 If S is a string representing a number, keep this number."
3278 (let (hour minus min sec res
)
3280 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3281 (setq minus
(< 0 (length (match-string 1 s
)))
3282 hour
(string-to-number (match-string 2 s
))
3283 min
(string-to-number (match-string 3 s
))
3284 sec
(string-to-number (match-string 4 s
)))
3286 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3287 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3288 ((and (not (string-match org-ts-regexp-both s
))
3289 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3290 (setq minus
(< 0 (length (match-string 1 s
)))
3291 hour
(string-to-number (match-string 2 s
))
3292 min
(string-to-number (match-string 3 s
)))
3294 (setq res
(- (+ (* hour
3600) (* min
60))))
3295 (setq res
(+ (* hour
3600) (* min
60)))))
3296 (t (setq res
(string-to-number s
))))
3297 (number-to-string res
)))
3299 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3300 "Convert a number of seconds to a time string.
3301 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3302 minutes or seconds."
3303 (cond ((eq output-format
'days
)
3304 (format "%.3f" (/ (float secs
) 86400)))
3305 ((eq output-format
'hours
)
3306 (format "%.2f" (/ (float secs
) 3600)))
3307 ((eq output-format
'minutes
)
3308 (format "%.1f" (/ (float secs
) 60)))
3309 ((eq output-format
'seconds
)
3311 (t (org-format-seconds "%.2h:%.2m:%.2s" secs
))))
3313 (defun org-table-fedit-convert-buffer (function)
3314 "Convert all references in this buffer, using FUNCTION."
3315 (let ((line (org-current-line)))
3316 (goto-char (point-min))
3318 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3319 (delete-region (point) (point-at-eol))
3320 (or (eobp) (forward-char 1)))
3321 (org-goto-line line
)))
3323 (defun org-table-fedit-toggle-ref-type ()
3324 "Convert all references in the buffer from B3 to @3$2 and back."
3326 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3327 (org-table-fedit-convert-buffer
3328 (if org-table-buffer-is-an
3329 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3330 (message "Reference type switched to %s"
3331 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3333 (defun org-table-fedit-ref-up ()
3334 "Shift the reference at point one row/hline up."
3336 (org-table-fedit-shift-reference 'up
))
3337 (defun org-table-fedit-ref-down ()
3338 "Shift the reference at point one row/hline down."
3340 (org-table-fedit-shift-reference 'down
))
3341 (defun org-table-fedit-ref-left ()
3342 "Shift the reference at point one field to the left."
3344 (org-table-fedit-shift-reference 'left
))
3345 (defun org-table-fedit-ref-right ()
3346 "Shift the reference at point one field to the right."
3348 (org-table-fedit-shift-reference 'right
))
3350 (defun org-table-fedit-shift-reference (dir)
3352 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3353 (if (memq dir
'(left right
))
3354 (org-rematch-and-replace 1 (eq dir
'left
))
3355 (error "Cannot shift reference in this direction")))
3356 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3357 ;; A B3-like reference
3358 (if (memq dir
'(up down
))
3359 (org-rematch-and-replace 2 (eq dir
'up
))
3360 (org-rematch-and-replace 1 (eq dir
'left
))))
3362 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3363 ;; An internal reference
3364 (if (memq dir
'(up down
))
3365 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3366 (org-rematch-and-replace 5 (eq dir
'left
))))))
3368 (defun org-rematch-and-replace (n &optional decr hline
)
3369 "Re-match the group N, and replace it with the shifted reference."
3370 (or (match-end n
) (error "Cannot shift reference in this direction"))
3371 (goto-char (match-beginning n
))
3372 (and (looking-at (regexp-quote (match-string n
)))
3373 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3376 (defun org-table-shift-refpart (ref &optional decr hline
)
3377 "Shift a reference part REF.
3378 If DECR is set, decrease the references row/column, else increase.
3379 If HLINE is set, this may be a hline reference, it certainly is not
3380 a translation reference."
3382 (let* ((sign (string-match "^[-+]" ref
)) n
)
3384 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3386 ((and hline
(string-match "^I+" ref
))
3387 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3388 (setq n
(+ n
(if decr -
1 1)))
3389 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3391 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3393 (concat sign
(make-string n ?I
)))
3395 ((string-match "^[0-9]+" ref
)
3396 (setq n
(string-to-number (concat sign ref
)))
3397 (setq n
(+ n
(if decr -
1 1)))
3399 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3400 (number-to-string (max 1 n
))))
3402 ((string-match "^[a-zA-Z]+" ref
)
3403 (org-number-to-letters
3404 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3406 (t (error "Cannot shift reference"))))))
3408 (defun org-table-fedit-toggle-coordinates ()
3409 "Toggle the display of coordinates in the referenced table."
3411 (let ((pos (marker-position org-pos
)))
3412 (with-current-buffer (marker-buffer org-pos
)
3415 (org-table-toggle-coordinate-overlays)))))
3417 (defun org-table-fedit-finish (&optional arg
)
3418 "Parse the buffer for formula definitions and install them.
3419 With prefix ARG, apply the new formulas to the table."
3421 (org-table-remove-rectangle-highlight)
3422 (if org-table-use-standard-references
3424 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3425 (setq org-table-buffer-is-an nil
)))
3426 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3427 (goto-char (point-min))
3428 (while (re-search-forward
3429 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3431 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3432 form
(match-string 3))
3433 (setq form
(org-trim form
))
3434 (when (not (equal form
""))
3435 (while (string-match "[ \t]*\n[ \t]*" form
)
3436 (setq form
(replace-match " " t t form
)))
3437 (when (assoc var eql
)
3438 (error "Double formulas for %s" var
))
3439 (push (cons var form
) eql
)))
3441 (set-window-configuration org-window-configuration
)
3442 (select-window sel-win
)
3444 (unless (org-at-table-p)
3445 (error "Lost table position - cannot install formulas"))
3446 (org-table-store-formulas eql
)
3447 (move-marker pos nil
)
3448 (kill-buffer "*Edit Formulas*")
3450 (org-table-recalculate 'all
)
3451 (message "New formulas installed - press C-u C-c C-c to apply."))))
3453 (defun org-table-fedit-abort ()
3454 "Abort editing formulas, without installing the changes."
3456 (org-table-remove-rectangle-highlight)
3457 (let ((pos org-pos
) (sel-win org-selected-window
))
3458 (set-window-configuration org-window-configuration
)
3459 (select-window sel-win
)
3461 (move-marker pos nil
)
3462 (message "Formula editing aborted without installing changes")))
3464 (defun org-table-fedit-lisp-indent ()
3465 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3467 (let ((pos (point)) beg end ind
)
3468 (beginning-of-line 1)
3470 ((looking-at "[ \t]")
3472 (call-interactively 'lisp-indent-line
))
3473 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3474 ((not (fboundp 'pp-buffer
))
3475 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3476 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3477 (goto-char (- (match-end 0) 2))
3479 (setq ind
(make-string (current-column) ?\
))
3480 (condition-case nil
(forward-sexp 1)
3482 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3485 (narrow-to-region beg end
)
3486 (if (eq last-command this-command
)
3488 (goto-char (point-min))
3489 (setq this-command nil
)
3490 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3491 (replace-match " ")))
3493 (untabify (point-min) (point-max))
3494 (goto-char (1+ (point-min)))
3495 (while (re-search-forward "^." nil t
)
3496 (beginning-of-line 1)
3498 (goto-char (point-max))
3499 (backward-delete-char 1)))
3503 (defvar org-show-positions nil
)
3505 (defun org-table-show-reference (&optional local
)
3506 "Show the location/value of the $ expression at point."
3508 (org-table-remove-rectangle-highlight)
3510 (let ((pos (if local
(point) org-pos
))
3512 (org-inhibit-highlight-removal t
)
3513 (win (selected-window))
3514 (org-show-positions nil
)
3515 var name e what match dest
)
3516 (if local
(org-table-get-specials))
3518 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3519 (setq match
(concat (substring (match-string 0) 0 -
1)
3521 (substring (match-string 0) 0 -
1)
3524 ((or (org-at-regexp-p org-table-range-regexp2
)
3525 (org-at-regexp-p org-table-translate-regexp
)
3526 (org-at-regexp-p org-table-range-regexp
))
3529 (org-table-convert-refs-to-rc (match-string 0))))
3531 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3532 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3534 (t (error "No reference at point")))
3535 match
(and what
(or match
(match-string 0))))
3536 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3537 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3538 'secondary-selection
))
3539 (org-add-hook 'before-change-functions
3540 'org-table-remove-rectangle-highlight
)
3541 (if (eq what
'name
) (setq var
(substring match
1)))
3542 (when (eq what
'range
)
3543 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3544 (setq match
(org-table-formula-substitute-names match
)))
3548 (re-search-backward "^\\S-" nil t
)
3549 (beginning-of-line 1)
3550 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3553 (org-table-convert-refs-to-rc (match-string 1))))
3554 (org-table-add-rectangle-overlay
3555 (match-beginning 1) (match-end 1) face2
))))
3556 (if (and (markerp pos
) (marker-buffer pos
))
3557 (if (get-buffer-window (marker-buffer pos
))
3558 (select-window (get-buffer-window (marker-buffer pos
)))
3559 (org-switch-to-buffer-other-window (get-buffer-window
3560 (marker-buffer pos
)))))
3562 (org-table-force-dataline)
3564 (setq name
(substring dest
1))
3566 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3567 (setq e
(assoc name org-table-named-field-locations
))
3568 (org-goto-line (nth 1 e
))
3569 (org-table-goto-column (nth 2 e
)))
3570 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3571 (let ((l (string-to-number (match-string 1 dest
)))
3572 (c (string-to-number (match-string 2 dest
))))
3573 (org-goto-line (aref org-table-dlines l
))
3574 (org-table-goto-column c
)))
3575 (t (org-table-goto-column (string-to-number name
))))
3576 (move-marker pos
(point))
3577 (org-table-highlight-rectangle nil nil face2
))
3579 ((equal dest match
))
3584 (org-table-get-range match nil nil
'highlight
))
3586 ((setq e
(assoc var org-table-named-field-locations
))
3587 (org-goto-line (nth 1 e
))
3588 (org-table-goto-column (nth 2 e
))
3589 (org-table-highlight-rectangle (point) (point))
3590 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3591 ((setq e
(assoc var org-table-column-names
))
3592 (org-table-goto-column (string-to-number (cdr e
)))
3593 (org-table-highlight-rectangle (point) (point))
3594 (goto-char (org-table-begin))
3595 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3598 (goto-char (match-beginning 1))
3599 (org-table-highlight-rectangle)
3600 (message "Named column (column %s)" (cdr e
)))
3601 (error "Column name not found")))
3604 (org-table-goto-column (string-to-number (substring match
1)))
3605 (org-table-highlight-rectangle (point) (point))
3606 (message "Column %s" (substring match
1)))
3607 ((setq e
(assoc var org-table-local-parameters
))
3608 (goto-char (org-table-begin))
3609 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3611 (goto-char (match-beginning 1))
3612 (org-table-highlight-rectangle)
3613 (message "Local parameter."))
3614 (error "Parameter not found")))
3617 ((not var
) (error "No reference at point"))
3618 ((setq e
(assoc var org-table-formula-constants-local
))
3619 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3621 ((setq e
(assoc var org-table-formula-constants
))
3622 (message "Constant: $%s=%s in `org-table-formula-constants'."
3624 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3625 (message "Constant: $%s=%s, from `constants.el'%s."
3626 var e
(format " (%s units)" constants-unit-system
)))
3627 (t (error "Undefined name $%s" var
)))))
3629 (when (and org-show-positions
3630 (not (memq this-command
'(org-table-fedit-scroll
3631 org-table-fedit-scroll-down
))))
3632 (push pos org-show-positions
)
3633 (push org-table-current-begin-pos org-show-positions
)
3634 (let ((min (apply 'min org-show-positions
))
3635 (max (apply 'max org-show-positions
)))
3636 (goto-char min
) (recenter 0)
3638 (or (pos-visible-in-window-p max
) (recenter -
1))))
3639 (select-window win
))))
3641 (defun org-table-force-dataline ()
3642 "Make sure the cursor is in a dataline in a table."
3643 (unless (save-excursion
3644 (beginning-of-line 1)
3645 (looking-at org-table-dataline-regexp
))
3646 (let* ((re org-table-dataline-regexp
)
3647 (p1 (save-excursion (re-search-forward re nil
'move
)))
3648 (p2 (save-excursion (re-search-backward re nil
'move
))))
3650 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3652 ((or p1 p2
) (goto-char (or p1 p2
)))
3653 (t (error "No table dataline around here"))))))
3655 (defun org-table-fedit-line-up ()
3656 "Move cursor one line up in the window showing the table."
3658 (org-table-fedit-move 'previous-line
))
3660 (defun org-table-fedit-line-down ()
3661 "Move cursor one line down in the window showing the table."
3663 (org-table-fedit-move 'next-line
))
3665 (defun org-table-fedit-move (command)
3666 "Move the cursor in the window showing the table.
3667 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3668 (let ((org-table-allow-automatic-line-recalculation nil
)
3669 (pos org-pos
) (win (selected-window)) p
)
3670 (select-window (get-buffer-window (marker-buffer org-pos
)))
3672 (call-interactively command
)
3673 (while (and (org-at-table-p)
3674 (org-at-table-hline-p))
3675 (call-interactively command
))
3676 (or (org-at-table-p) (goto-char p
))
3677 (move-marker pos
(point))
3678 (select-window win
)))
3680 (defun org-table-fedit-scroll (N)
3682 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3683 (scroll-other-window N
)))
3685 (defun org-table-fedit-scroll-down (N)
3687 (org-table-fedit-scroll (- N
)))
3689 (defvar org-table-rectangle-overlays nil
)
3691 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3692 "Add a new overlay."
3693 (let ((ov (make-overlay beg end
)))
3694 (overlay-put ov
'face
(or face
'secondary-selection
))
3695 (push ov org-table-rectangle-overlays
)))
3697 (defun org-table-highlight-rectangle (&optional beg end face
)
3698 "Highlight rectangular region in a table."
3699 (setq beg
(or beg
(point)) end
(or end
(point)))
3700 (let ((b (min beg end
))
3703 (and (boundp 'org-show-positions
)
3704 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3705 (goto-char (min beg end
))
3706 (setq l1
(org-current-line)
3707 c1
(org-table-current-column))
3708 (goto-char (max beg end
))
3709 (setq l2
(org-current-line)
3710 c2
(org-table-current-column))
3711 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3713 (beginning-of-line 1)
3714 (loop for line from l1 to l2 do
3715 (when (looking-at org-table-dataline-regexp
)
3716 (org-table-goto-column c1
)
3717 (skip-chars-backward "^|\n") (setq beg
(point))
3718 (org-table-goto-column c2
)
3719 (skip-chars-forward "^|\n") (setq end
(point))
3720 (org-table-add-rectangle-overlay beg end face
))
3721 (beginning-of-line 2))
3723 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3725 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3726 "Remove the rectangle overlays."
3727 (unless org-inhibit-highlight-removal
3728 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3729 (mapc 'delete-overlay org-table-rectangle-overlays
)
3730 (setq org-table-rectangle-overlays nil
)))
3732 (defvar org-table-coordinate-overlays nil
3733 "Collects the coordinate grid overlays, so that they can be removed.")
3734 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3736 (defun org-table-overlay-coordinates ()
3737 "Add overlays to the table at point, to show row/column coordinates."
3739 (mapc 'delete-overlay org-table-coordinate-overlays
)
3740 (setq org-table-coordinate-overlays nil
)
3742 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3743 (goto-char (org-table-begin))
3744 (while (org-at-table-p)
3745 (setq eol
(point-at-eol))
3746 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
3747 (push ov org-table-coordinate-overlays
)
3748 (setq hline
(looking-at org-table-hline-regexp
))
3749 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3750 (format "%4d" (setq id
(1+ id
)))))
3751 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3754 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3755 (setq beg
(1+ (match-beginning 0))
3757 s1
(concat "$" (int-to-string ic
))
3758 s2
(org-number-to-letters ic
)
3759 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3760 (setq ov
(make-overlay beg
(+ beg
(length str
))))
3761 (push ov org-table-coordinate-overlays
)
3762 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3763 (beginning-of-line 2)))))
3765 (defun org-table-toggle-coordinate-overlays ()
3766 "Toggle the display of Row/Column numbers in tables."
3768 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3769 (message "Row/Column number display turned %s"
3770 (if org-table-overlay-coordinates
"on" "off"))
3771 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3773 (unless org-table-overlay-coordinates
3774 (mapc 'delete-overlay org-table-coordinate-overlays
)
3775 (setq org-table-coordinate-overlays nil
)))
3777 (defun org-table-toggle-formula-debugger ()
3778 "Toggle the formula debugger in tables."
3780 (setq org-table-formula-debug
(not org-table-formula-debug
))
3781 (message "Formula debugging has been turned %s"
3782 (if org-table-formula-debug
"on" "off")))
3784 ;;; The orgtbl minor mode
3786 ;; Define a minor mode which can be used in other modes in order to
3787 ;; integrate the org-mode table editor.
3789 ;; This is really a hack, because the org-mode table editor uses several
3790 ;; keys which normally belong to the major mode, for example the TAB and
3791 ;; RET keys. Here is how it works: The minor mode defines all the keys
3792 ;; necessary to operate the table editor, but wraps the commands into a
3793 ;; function which tests if the cursor is currently inside a table. If that
3794 ;; is the case, the table editor command is executed. However, when any of
3795 ;; those keys is used outside a table, the function uses `key-binding' to
3796 ;; look up if the key has an associated command in another currently active
3797 ;; keymap (minor modes, major mode, global), and executes that command.
3798 ;; There might be problems if any of the keys used by the table editor is
3799 ;; otherwise used as a prefix key.
3801 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3802 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3803 ;; addresses this by checking explicitly for both bindings.
3805 ;; The optimized version (see variable `orgtbl-optimized') takes over
3806 ;; all keys which are bound to `self-insert-command' in the *global map*.
3807 ;; Some modes bind other commands to simple characters, for example
3808 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3809 ;; active, this binding is ignored inside tables and replaced with a
3810 ;; modified self-insert.
3813 (defvar orgtbl-mode-map
(make-keymap)
3814 "Keymap for `orgtbl-mode'.")
3817 (defun turn-on-orgtbl ()
3818 "Unconditionally turn on `orgtbl-mode'."
3821 (defvar org-old-auto-fill-inhibit-regexp nil
3822 "Local variable used by `orgtbl-mode'.")
3824 (defconst orgtbl-line-start-regexp
3825 "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\|TBLNAME\\):\\)"
3826 "Matches a line belonging to an orgtbl.")
3828 (defconst orgtbl-extra-font-lock-keywords
3829 (list (list (concat "^" orgtbl-line-start-regexp
".*")
3830 0 (quote 'org-table
) 'prepend
))
3831 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
3833 ;; Install it as a minor mode.
3834 (put 'orgtbl-mode
:included t
)
3835 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
3838 (define-minor-mode orgtbl-mode
3839 "The `org-mode' table editor as a minor mode for use in other modes."
3840 :lighter
" OrgTbl" :keymap orgtbl-mode-map
3841 (org-load-modules-maybe)
3843 ((eq major-mode
'org-mode
)
3844 ;; Exit without error, in case some hook functions calls this
3845 ;; by accident in org-mode.
3846 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
3848 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
3849 ;; Make sure we are first in minor-mode-map-alist
3850 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
3851 ;; FIXME: maybe it should use emulation-mode-map-alists?
3852 (and c
(setq minor-mode-map-alist
3853 (cons c
(delq c minor-mode-map-alist
)))))
3854 (org-set-local (quote org-table-may-need-update
) t
)
3855 (org-add-hook 'before-change-functions
'org-before-change-function
3857 (org-set-local 'org-old-auto-fill-inhibit-regexp
3858 auto-fill-inhibit-regexp
)
3859 (org-set-local 'auto-fill-inhibit-regexp
3860 (if auto-fill-inhibit-regexp
3861 (concat orgtbl-line-start-regexp
"\\|"
3862 auto-fill-inhibit-regexp
)
3863 orgtbl-line-start-regexp
))
3864 (add-to-invisibility-spec '(org-cwidth))
3865 (when (fboundp 'font-lock-add-keywords
)
3866 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
3867 (org-restart-font-lock))
3868 (easy-menu-add orgtbl-mode-menu
))
3870 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
3871 (org-table-cleanup-narrow-column-properties)
3872 (org-remove-from-invisibility-spec '(org-cwidth))
3873 (remove-hook 'before-change-functions
'org-before-change-function t
)
3874 (when (fboundp 'font-lock-remove-keywords
)
3875 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
3876 (org-restart-font-lock))
3877 (easy-menu-remove orgtbl-mode-menu
)
3878 (force-mode-line-update 'all
))))
3880 (defun org-table-cleanup-narrow-column-properties ()
3881 "Remove all properties related to narrow-column invisibility."
3882 (let ((s (point-min)))
3883 (while (setq s
(text-property-any s
(point-max)
3884 'display org-narrow-column-arrow
))
3885 (remove-text-properties s
(1+ s
) '(display t
)))
3886 (setq s
(point-min))
3887 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
3888 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
3889 (setq s
(point-min))
3890 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
3891 (remove-text-properties s
(1+ s
) '(invisible t
)))))
3893 (defun orgtbl-make-binding (fun n
&rest keys
)
3894 "Create a function for binding in the table minor mode.
3895 FUN is the command to call inside a table. N is used to create a unique
3896 command name. KEYS are keys that should be checked in for a command
3897 to execute outside of tables."
3900 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
3902 (concat "In tables, run `" (symbol-name fun
) "'.\n"
3903 "Outside of tables, run the binding of `"
3904 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
3909 (list 'call-interactively
(list 'quote fun
))
3910 (list 'let
'(orgtbl-mode)
3911 (list 'call-interactively
3914 (list 'key-binding k
))
3916 '('orgtbl-error
))))))))
3918 (defun orgtbl-error ()
3919 "Error when there is no default binding for a table key."
3921 (error "This key has no function outside tables"))
3923 (defun orgtbl-setup ()
3924 "Setup orgtbl keymaps."
3927 '(([(meta shift left
)] org-table-delete-column
)
3928 ([(meta left
)] org-table-move-column-left
)
3929 ([(meta right
)] org-table-move-column-right
)
3930 ([(meta shift right
)] org-table-insert-column
)
3931 ([(meta shift up
)] org-table-kill-row
)
3932 ([(meta shift down
)] org-table-insert-row
)
3933 ([(meta up
)] org-table-move-row-up
)
3934 ([(meta down
)] org-table-move-row-down
)
3935 ("\C-c\C-w" org-table-cut-region
)
3936 ("\C-c\M-w" org-table-copy-region
)
3937 ("\C-c\C-y" org-table-paste-rectangle
)
3938 ("\C-c\C-w" org-table-wrap-region
)
3939 ("\C-c-" org-table-insert-hline
)
3940 ("\C-c}" org-table-toggle-coordinate-overlays
)
3941 ("\C-c{" org-table-toggle-formula-debugger
)
3942 ("\C-m" org-table-next-row
)
3943 ([(shift return
)] org-table-copy-down
)
3944 ("\C-c?" org-table-field-info
)
3945 ("\C-c " org-table-blank-field
)
3946 ("\C-c+" org-table-sum
)
3947 ("\C-c=" org-table-eval-formula
)
3948 ("\C-c'" org-table-edit-formulas
)
3949 ("\C-c`" org-table-edit-field
)
3950 ("\C-c*" org-table-recalculate
)
3951 ("\C-c^" org-table-sort-lines
)
3952 ("\M-a" org-table-beginning-of-field
)
3953 ("\M-e" org-table-end-of-field
)
3954 ([(control ?
#)] org-table-rotate-recalc-marks
)))
3956 (while (setq elt
(pop bindings
))
3957 (setq nfunc
(1+ nfunc
))
3958 (setq key
(org-key (car elt
))
3960 cmd
(orgtbl-make-binding fun nfunc key
))
3961 (org-defkey orgtbl-mode-map key cmd
))
3963 ;; Special treatment needed for TAB and RET
3964 (org-defkey orgtbl-mode-map
[(return)]
3965 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
3966 (org-defkey orgtbl-mode-map
"\C-m"
3967 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
3969 (org-defkey orgtbl-mode-map
[(tab)]
3970 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
3971 (org-defkey orgtbl-mode-map
"\C-i"
3972 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
3974 (org-defkey orgtbl-mode-map
[(shift tab
)]
3975 (orgtbl-make-binding 'org-table-previous-field
104
3976 [(shift tab
)] [(tab)] "\C-i"))
3979 (unless (featurep 'xemacs
)
3980 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
3981 (orgtbl-make-binding 'org-table-previous-field
107
3982 [S-iso-lefttab
] [backtab] [(shift tab)]
3985 (org-defkey orgtbl-mode-map [backtab]
3986 (orgtbl-make-binding 'org-table-previous-field
108
3987 [backtab] [S-iso-lefttab] [(shift tab)]
3990 (org-defkey orgtbl-mode-map "\M-\C-m"
3991 (orgtbl-make-binding 'org-table-wrap-region 105
3992 "\M-\C-m" [(meta return)]))
3993 (org-defkey orgtbl-mode-map [(meta return)]
3994 (orgtbl-make-binding 'org-table-wrap-region 106
3995 [(meta return)] "\M-\C-m"))
3997 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
3998 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4000 (when orgtbl-optimized
4001 ;; If the user wants maximum table support, we need to hijack
4002 ;; some standard editing functions
4003 (org-remap orgtbl-mode-map
4004 'self-insert-command 'orgtbl-self-insert-command
4005 'delete-char 'org-delete-char
4006 'delete-backward-char 'org-delete-backward-char)
4007 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4008 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4010 ["Create or convert" org-table-create-or-convert-from-region
4011 :active (not (org-at-table-p)) :keys "C-c |" ]
4013 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4014 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4015 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4016 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4018 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4019 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4020 ["Copy Field from Above"
4021 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4024 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4025 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4026 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4027 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4029 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4030 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4031 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4032 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4033 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4035 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4037 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4038 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4039 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4040 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4043 ["Insert table template" orgtbl-insert-radio-table
4044 (assq major-mode orgtbl-radio-table-templates)]
4045 ["Comment/uncomment table" orgtbl-toggle-comment t])
4047 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4048 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4049 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4050 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4051 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4052 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4053 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4054 ["Sum Column/Rectangle" org-table-sum
4055 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4056 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4058 org-table-toggle-formula-debugger :active (org-at-table-p)
4060 :style toggle :selected org-table-formula-debug]
4061 ["Show Col/Row Numbers"
4062 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4064 :style toggle :selected org-table-overlay-coordinates]
4068 (defun orgtbl-ctrl-c-ctrl-c (arg)
4069 "If the cursor is inside a table, realign the table.
4070 If it is a table to be sent away to a receiver, do it.
4071 With prefix arg, also recompute table."
4073 (let ((pos (point)) action consts-str consts cst const-str)
4075 (beginning-of-line 1)
4077 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4078 ((looking-at "[ \t]*|") pos)
4079 ((looking-at "[ \t]*#\\+TBLFM:") 'recalc))))
4083 (org-table-maybe-eval-formula)
4085 (call-interactively 'org-table-recalculate)
4086 (org-table-maybe-recalculate-line))
4087 (call-interactively 'org-table-align)
4088 (when (orgtbl-send-table 'maybe)
4089 (run-hooks 'orgtbl-after-send-table-hook)))
4090 ((eq action 'recalc)
4092 (goto-char (point-min))
4093 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t)
4094 (setq const-str (substring-no-properties (match-string 1)))
4095 (setq consts (append consts (org-split-string const-str "[ \t]+")))
4098 (while (setq e (pop consts))
4099 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4100 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4101 (setq org-table-formula-constants-local cst)))))
4103 (beginning-of-line 1)
4104 (skip-chars-backward " \r\n\t")
4105 (if (org-at-table-p)
4106 (org-call-with-arg 'org-table-recalculate t))))
4107 (t (let (orgtbl-mode)
4108 (call-interactively (key-binding "\C-c\C-c")))))))
4110 (defun orgtbl-create-or-convert-from-region (arg)
4111 "Create table or convert region to table, if no conflicting binding.
4112 This installs the table binding `C-c |', but only if there is no
4113 conflicting binding to this key outside orgtbl-mode."
4115 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4117 (call-interactively cmd)
4118 (call-interactively 'org-table-create-or-convert-from-region))))
4120 (defun orgtbl-tab (arg)
4121 "Justification and field motion for `orgtbl-mode'."
4123 (if arg (org-table-edit-field t)
4124 (org-table-justify-field-maybe)
4125 (org-table-next-field)))
4127 (defun orgtbl-ret ()
4128 "Justification and field motion for `orgtbl-mode'."
4132 (org-table-justify-field-maybe)
4133 (org-table-next-row)))
4135 (defun orgtbl-self-insert-command (N)
4136 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4137 If the cursor is in a table looking at whitespace, the whitespace is
4138 overwritten, and the table is not marked as requiring realignment."
4140 (if (and (org-at-table-p)
4142 (and org-table-auto-blank-field
4143 (member last-command
4144 '(orgtbl-hijacker-command-100
4145 orgtbl-hijacker-command-101
4146 orgtbl-hijacker-command-102
4147 orgtbl-hijacker-command-103
4148 orgtbl-hijacker-command-104
4149 orgtbl-hijacker-command-105
4151 (org-table-blank-field))
4154 (looking-at "[^|\n]* +|"))
4155 (let (org-table-may-need-update)
4156 (goto-char (1- (match-end 0)))
4158 (goto-char (match-beginning 0))
4159 (self-insert-command N))
4160 (setq org-table-may-need-update t)
4163 (cmd (or (key-binding
4164 (or (and (listp function-key-map)
4165 (setq a (assoc last-input-event function-key-map))
4167 (vector last-input-event)))
4168 'self-insert-command)))
4169 (call-interactively cmd)
4170 (if (and org-self-insert-cluster-for-undo
4171 (eq cmd 'self-insert-command))
4172 (if (not (eq last-command 'orgtbl-self-insert-command))
4173 (setq org-self-insert-command-undo-counter 1)
4174 (if (>= org-self-insert-command-undo-counter 20)
4175 (setq org-self-insert-command-undo-counter 1)
4176 (and (> org-self-insert-command-undo-counter 0)
4178 (not (cadr buffer-undo-list)) ; remove nil entry
4179 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4180 (setq org-self-insert-command-undo-counter
4181 (1+ org-self-insert-command-undo-counter))))))))
4183 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4184 "Regular expression matching exponentials as produced by calc.")
4186 (defun orgtbl-export (table target)
4188 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
4189 (lines (org-split-string table "[ \t]*\n[ \t]*"))
4190 org-table-last-alignment org-table-last-column-widths
4192 (if (not (fboundp func))
4193 (error "Cannot export orgtbl table to %s" target))
4194 (setq lines (org-table-clean-before-export lines))
4198 (if (string-match org-table-hline-regexp x)
4200 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4202 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
4204 (loop for i from (1- maxcol) downto 0 do
4205 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
4206 (setq column (delq nil column))
4207 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
4208 (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))
4209 (funcall func table nil)))
4211 (defun orgtbl-gather-send-defs ()
4212 "Gather a plist of :name, :transform, :params for each destination before
4215 (goto-char (org-table-begin))
4217 (beginning-of-line 0)
4218 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4219 (let ((name (org-no-properties (match-string 1)))
4220 (transform (intern (match-string 2)))
4221 (params (if (match-end 3)
4222 (read (concat "(" (match-string 3) ")")))))
4223 (push (list :name name :transform transform :params params)
4225 (beginning-of-line 0)))
4228 (defun orgtbl-send-replace-tbl (name txt)
4229 "Find and replace table NAME with TXT."
4231 (goto-char (point-min))
4232 (unless (re-search-forward
4233 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4234 (error "Don't know where to insert translated table"))
4235 (goto-char (match-beginning 0))
4236 (beginning-of-line 2)
4238 (let ((beg (point)))
4239 (unless (re-search-forward
4240 (concat "END RECEIVE ORGTBL +" name) nil t)
4241 (error "Cannot find end of insertion region"))
4242 (beginning-of-line 1)
4243 (delete-region beg (point))))
4247 (defun org-table-to-lisp (&optional txt)
4248 "Convert the table at point to a Lisp structure.
4249 The structure will be a list. Each item is either the symbol `hline'
4250 for a horizontal separator line, or a list of field values as strings.
4251 The table is taken from the parameter TXT, or from the buffer at point."
4253 (unless (org-at-table-p)
4254 (error "No table at point")))
4256 (buffer-substring-no-properties (org-table-begin)
4258 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4262 (if (string-match org-table-hline-regexp x)
4264 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4267 (defun orgtbl-send-table (&optional maybe)
4268 "Send a transformed version of this table to the receiver position.
4269 With argument MAYBE, fail quietly if no transformation is defined for
4273 (unless (org-at-table-p) (error "Not at a table"))
4274 ;; when non-interactive, we assume align has just happened.
4275 (when (org-called-interactively-p 'any) (org-table-align))
4276 (let ((dests (orgtbl-gather-send-defs))
4277 (txt (buffer-substring-no-properties (org-table-begin)
4280 (unless dests (if maybe (throw 'exit nil)
4281 (error "Don't know how to transform this table")))
4282 (dolist (dest dests)
4283 (let* ((name (plist-get dest :name))
4284 (transform (plist-get dest :transform))
4285 (params (plist-get dest :params))
4286 (skip (plist-get params :skip))
4287 (skipcols (plist-get params :skipcols))
4289 (lines (org-table-clean-before-export
4291 (org-split-string txt "[ \t]*\n[ \t]*"))))
4292 (i0 (if org-table-clean-did-remove-column 2 1))
4295 (if (string-match org-table-hline-regexp x)
4297 (org-remove-by-index
4298 (org-split-string (org-trim x) "\\s-*|\\s-*")
4301 (fun (if (= i0 2) 'cdr 'identity))
4302 (org-table-last-alignment
4303 (org-remove-by-index (funcall fun org-table-last-alignment)
4305 (org-table-last-column-widths
4306 (org-remove-by-index (funcall fun org-table-last-column-widths)
4308 (txt (if (fboundp transform)
4309 (funcall transform table params)
4310 (error "No such transformation function %s" transform))))
4311 (orgtbl-send-replace-tbl name txt))
4312 (setq ntbl (1+ ntbl)))
4313 (message "Table converted and installed at %d receiver location%s"
4314 ntbl (if (> ntbl 1) "s" ""))
4319 (defun org-remove-by-index (list indices &optional i0)
4320 "Remove the elements in LIST with indices in INDICES.
4321 First element has index 0, or I0 if given."
4324 (if (integerp indices) (setq indices (list indices)))
4325 (setq i0 (1- (or i0 0)))
4326 (delq :rm (mapcar (lambda (x)
4328 (if (memq i0 indices) :rm x))
4331 (defun orgtbl-toggle-comment ()
4332 "Comment or uncomment the orgtbl at point."
4334 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4335 (re2 (concat "^" orgtbl-line-start-regexp))
4336 (commented (save-excursion (beginning-of-line 1)
4337 (cond ((looking-at re1) t)
4338 ((looking-at re2) nil)
4339 (t (error "Not at an org table")))))
4340 (re (if commented re1 re2))
4343 (beginning-of-line 1)
4344 (while (looking-at re) (beginning-of-line 0))
4345 (beginning-of-line 2)
4347 (while (looking-at re) (beginning-of-line 2))
4349 (comment-region beg end (if commented '(4) nil))))
4351 (defun orgtbl-insert-radio-table ()
4352 "Insert a radio table template appropriate for this major mode."
4354 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4357 (unless e (error "No radio table setup defined for %s" major-mode))
4358 (setq name (read-string "Table name: "))
4359 (while (string-match "%n" txt)
4360 (setq txt (replace-match name t t txt)))
4361 (or (bolp) (insert "\n"))
4366 ;; Dynamically bound input and output for table formatting.
4367 (defvar *orgtbl-table* nil
4368 "Carries the current table through formatting routines.")
4369 (defvar *orgtbl-rtn* nil
4370 "Formatting routines push the output lines here.")
4371 ;; Formatting parameters for the current table section.
4372 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4373 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4374 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4375 (defvar *orgtbl-fmt* nil "Format for each entry.")
4376 (defvar *orgtbl-efmt* nil "Format for numbers.")
4377 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4378 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4379 (defvar *orgtbl-lstart* nil "Text starting a row.")
4380 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4381 (defvar *orgtbl-lend* nil "Text ending a row.")
4382 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4384 (defsubst orgtbl-get-fmt (fmt i)
4385 "Retrieve the format from FMT corresponding to the Ith column."
4386 (if (and (not (functionp fmt)) (consp fmt))
4390 (defsubst orgtbl-apply-fmt (fmt &rest args)
4391 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4392 (cond ((functionp fmt) (apply fmt args))
4393 (fmt (apply 'format fmt args))
4397 (defsubst orgtbl-eval-str (str)
4398 "If STR is a function, evaluate it with no arguments."
4403 (defun orgtbl-format-line (line)
4404 "Format LINE as a table row."
4405 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4411 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4412 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4413 (orgtbl-apply-fmt efmt (match-string 1 f)
4416 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4417 *orgtbl-default-fmt*)
4420 (push (if *orgtbl-lfmt*
4421 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4422 (concat (orgtbl-eval-str *orgtbl-lstart*)
4423 (mapconcat 'identity line *orgtbl-sep*)
4424 (orgtbl-eval-str *orgtbl-lend*)))
4427 (defun orgtbl-format-section (section-stopper)
4428 "Format lines until the first occurrence of SECTION-STOPPER."
4431 (while (not (eq (car *orgtbl-table*) section-stopper))
4432 (if prevline (orgtbl-format-line prevline))
4433 (setq prevline (pop *orgtbl-table*)))
4434 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4435 (*orgtbl-lend* *orgtbl-llend*)
4436 (*orgtbl-lfmt* *orgtbl-llfmt*))
4437 (orgtbl-format-line prevline))))))
4439 (defun orgtbl-to-generic (table params)
4440 "Convert the orgtbl-mode TABLE to some other format.
4441 This generic routine can be used for many standard cases.
4442 TABLE is a list, each entry either the symbol `hline' for a horizontal
4443 separator line, or a list of fields for that line.
4444 PARAMS is a property list of parameters that can influence the conversion.
4445 For the generic converter, some parameters are obligatory: you need to
4446 specify either :lfmt, or all of (:lstart :lend :sep).
4448 Valid parameters are
4450 :splice When set to t, return only table body lines, don't wrap
4451 them into :tstart and :tend. Default is nil. When :splice
4452 is non-nil, this also means that the exporter should not look
4453 for and interpret header and footer sections.
4455 :hline String to be inserted on horizontal separation lines.
4456 May be nil to ignore hlines.
4458 :sep Separator between two fields
4459 :remove-nil-lines Do not include lines that evaluate to nil.
4462 Each in the following group may be either a string or a function
4463 of no arguments returning a string:
4464 :tstart String to start the table. Ignored when :splice is t.
4465 :tend String to end the table. Ignored when :splice is t.
4466 :lstart String to start a new table line.
4467 :llstart String to start the last table line, defaults to :lstart.
4468 :lend String to end a table line
4469 :llend String to end the last table line, defaults to :lend.
4471 Each in the following group may be a string, a function of one
4472 argument (the field or line) returning a string, or a plist
4473 mapping columns to either of the above:
4474 :lfmt Format for entire line, with enough %s to capture all fields.
4475 If this is present, :lstart, :lend, and :sep are ignored.
4476 :llfmt Format for the entire last line, defaults to :lfmt.
4477 :fmt A format to be used to wrap the field, should contain
4478 %s for the original field value. For example, to wrap
4479 everything in dollars, you could use :fmt \"$%s$\".
4480 This may also be a property list with column numbers and
4481 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4483 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4484 Same as above, specific for the header lines in the table.
4485 All lines before the first hline are treated as header.
4486 If any of these is not present, the data line value is used.
4488 This may be either a string or a function of two arguments:
4489 :efmt Use this format to print numbers with exponentials.
4490 The format should have %s twice for inserting mantissa
4491 and exponent, for example \"%s\\\\times10^{%s}\". This
4492 may also be a property list with column numbers and
4493 formats. :fmt will still be applied after :efmt.
4495 In addition to this, the parameters :skip and :skipcols are always handled
4496 directly by `orgtbl-send-table'. See manual."
4499 (let* ((splicep (plist-get params :splice))
4500 (hline (plist-get params :hline))
4501 (remove-nil-linesp (plist-get params :remove-nil-lines))
4502 (remove-newlines (plist-get params :remove-newlines))
4503 (*orgtbl-hline* hline)
4504 (*orgtbl-table* table)
4505 (*orgtbl-sep* (plist-get params :sep))
4506 (*orgtbl-efmt* (plist-get params :efmt))
4507 (*orgtbl-lstart* (plist-get params :lstart))
4508 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4509 (*orgtbl-lend* (plist-get params :lend))
4510 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4511 (*orgtbl-lfmt* (plist-get params :lfmt))
4512 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4513 (*orgtbl-fmt* (plist-get params :fmt))
4518 (when (plist-member params :tstart)
4519 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4520 (if tstart (push tstart *orgtbl-rtn*)))))
4522 ;; Do we have a heading section? If so, format it and handle the
4524 (if (and (not splicep)
4525 (or (consp (car *orgtbl-table*))
4526 (consp (nth 1 *orgtbl-table*)))
4527 (memq 'hline (cdr *orgtbl-table*)))
4529 (when (eq 'hline (car *orgtbl-table*))
4530 ;; there is a hline before the first data line
4531 (and hline (push hline *orgtbl-rtn*))
4532 (pop *orgtbl-table*))
4533 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4535 (*orgtbl-llstart* (or (plist-get params :hllstart)
4537 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4538 (*orgtbl-llend* (or (plist-get params :hllend)
4539 (plist-get params :hlend) *orgtbl-llend*))
4540 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4541 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4542 (plist-get params :hlfmt) *orgtbl-llfmt*))
4543 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4544 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4545 (orgtbl-format-section 'hline))
4546 (if hline (push hline *orgtbl-rtn*))
4547 (pop *orgtbl-table*)))
4549 ;; Now format the main section.
4550 (orgtbl-format-section nil)
4553 (when (plist-member params :tend)
4554 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4555 (if tend (push tend *orgtbl-rtn*)))))
4557 (mapconcat (if remove-newlines
4559 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4561 (nreverse (if remove-nil-linesp
4562 (remq nil *orgtbl-rtn*)
4563 *orgtbl-rtn*)) "\n")))
4565 (defun orgtbl-to-tsv (table params)
4566 "Convert the orgtbl-mode table to TAB separated material."
4567 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4568 (defun orgtbl-to-csv (table params)
4569 "Convert the orgtbl-mode table to CSV material.
4570 This does take care of the proper quoting of fields with comma or quotes."
4571 (orgtbl-to-generic table (org-combine-plists
4572 '(:sep "," :fmt org-quote-csv-field)
4575 (defun orgtbl-to-latex (table params)
4576 "Convert the orgtbl-mode TABLE to LaTeX.
4577 TABLE is a list, each entry either the symbol `hline' for a horizontal
4578 separator line, or a list of fields for that line.
4579 PARAMS is a property list of parameters that can influence the conversion.
4580 Supports all parameters from `orgtbl-to-generic'. Most important for
4583 :splice When set to t, return only table body lines, don't wrap
4584 them into a tabular environment. Default is nil.
4586 :fmt A format to be used to wrap the field, should contain %s for the
4587 original field value. For example, to wrap everything in dollars,
4588 use :fmt \"$%s$\". This may also be a property list with column
4589 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4590 The format may also be a function that formats its one argument.
4592 :efmt Format for transforming numbers with exponentials. The format
4593 should have %s twice for inserting mantissa and exponent, for
4594 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4595 This may also be a property list with column numbers and formats.
4596 The format may also be a function that formats its two arguments.
4598 :llend If you find too much space below the last line of a table,
4599 pass a value of \"\" for :llend to suppress the final \\\\.
4601 The general parameters :skip and :skipcols have already been applied when
4602 this function is called."
4603 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4604 org-table-last-alignment ""))
4607 :tstart (concat "\\begin{tabular}{" alignment "}")
4608 :tend "\\end{tabular}"
4609 :lstart "" :lend " \\\\" :sep " & "
4610 :efmt "%s\\,(%s)" :hline "\\hline")))
4611 (orgtbl-to-generic table (org-combine-plists params2 params))))
4613 (defun orgtbl-to-html (table params)
4614 "Convert the orgtbl-mode TABLE to HTML.
4615 TABLE is a list, each entry either the symbol `hline' for a horizontal
4616 separator line, or a list of fields for that line.
4617 PARAMS is a property list of parameters that can influence the conversion.
4618 Currently this function recognizes the following parameters:
4620 :splice When set to t, return only table body lines, don't wrap
4621 them into a <table> environment. Default is nil.
4623 The general parameters :skip and :skipcols have already been applied when
4624 this function is called. The function does *not* use `orgtbl-to-generic',
4625 so you cannot specify parameters for it."
4626 (let* ((splicep (plist-get params :splice))
4627 (html-table-tag org-export-html-table-tag)
4629 ;; Just call the formatter we already have
4630 ;; We need to make text lines for it, so put the fields back together.
4631 (setq html (org-format-org-table-html
4636 (concat "| " (mapconcat 'org-html-expand x " | ") " |")))
4639 (if (string-match "\n+\\'" html)
4640 (setq html (replace-match "" t t html)))
4643 (defun orgtbl-to-texinfo (table params)
4644 "Convert the orgtbl-mode TABLE to TeXInfo.
4645 TABLE is a list, each entry either the symbol `hline' for a horizontal
4646 separator line, or a list of fields for that line.
4647 PARAMS is a property list of parameters that can influence the conversion.
4648 Supports all parameters from `orgtbl-to-generic'. Most important for
4651 :splice nil/t When set to t, return only table body lines, don't wrap
4652 them into a multitable environment. Default is nil.
4654 :fmt fmt A format to be used to wrap the field, should contain
4655 %s for the original field value. For example, to wrap
4656 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4657 This may also be a property list with column numbers and
4658 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4659 Each format also may be a function that formats its one
4662 :cf \"f1 f2..\" The column fractions for the table. By default these
4663 are computed automatically from the width of the columns
4666 The general parameters :skip and :skipcols have already been applied when
4667 this function is called."
4668 (let* ((total (float (apply '+ org-table-last-column-widths)))
4669 (colfrac (or (plist-get params :cf)
4671 (lambda (x) (format "%.3f" (/ (float x) total)))
4672 org-table-last-column-widths " ")))
4675 :tstart (concat "@multitable @columnfractions " colfrac)
4676 :tend "@end multitable"
4677 :lstart "@item " :lend "" :sep " @tab "
4678 :hlstart "@headitem ")))
4679 (orgtbl-to-generic table (org-combine-plists params2 params))))
4681 (defun orgtbl-to-orgtbl (table params)
4682 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4683 Useful when slicing one table into many. The :hline, :sep,
4684 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4685 and :tend suppress strings without splicing; they can be set to
4686 provide ORGTBL directives for the generated table."
4690 :tstart nil :tend nil
4695 (params (org-combine-plists params2 params)))
4696 (orgtbl-to-generic table params)))
4698 (defun org-table-get-remote-range (name-or-id form)
4699 "Get a field value or a list of values in a range from table at ID.
4701 NAME-OR-ID may be the name of a table in the current file as set by
4702 a \"#+TBLNAME:\" directive. The first table following this line
4703 will then be used. Alternatively, it may be an ID referring to
4704 any entry, also in a different file. In this case, the first table
4705 in that entry will be referenced.
4706 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
4707 \"@I$2..@II$2\". All the references must be absolute, not relative.
4709 The return value is either a single string for a single field, or a
4710 list of the fields in the rectangle ."
4713 ;; Protect a bunch of variables from being overwritten
4714 ;; by the context of the remote table
4715 org-table-column-names org-table-column-name-regexp
4716 org-table-local-parameters org-table-named-field-locations
4717 org-table-current-line-types org-table-current-begin-line
4718 org-table-current-begin-pos org-table-dlines
4719 org-table-current-ncol
4720 org-table-hlines org-table-last-alignment
4721 org-table-last-column-widths org-table-last-alignment
4722 org-table-last-column-widths tbeg
4724 (setq form (org-table-convert-refs-to-rc form))
4729 (goto-char (point-min))
4730 (if (re-search-forward
4731 (concat "^[ \t]*#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4733 (setq buffer (current-buffer) loc (match-beginning 0))
4734 (setq id-loc (org-id-find name-or-id 'marker))
4735 (unless (and id-loc (markerp id-loc))
4736 (error "Can't find remote table \"%s\"" name-or-id))
4737 (setq buffer (marker-buffer id-loc)
4738 loc (marker-position id-loc))
4739 (move-marker id-loc nil)))
4740 (with-current-buffer buffer
4746 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4747 (not (match-beginning 1)))
4748 (error "Cannot find a table at NAME or ID %s" name-or-id))
4749 (setq tbeg (point-at-bol))
4750 (org-table-get-specials)
4751 (setq form (org-table-formula-substitute-names
4752 (org-table-formula-handle-first/last-rc form)))
4753 (if (and (string-match org-table-range-regexp form)
4754 (> (length (match-string 0 form)) 1))
4756 (org-table-get-range (match-string 0 form) tbeg 1))
4759 (provide 'org-table)
4761 ;;; org-table.el ends here