1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
29 ;; This file contains the table editor and spreadsheet for Org-mode.
31 ;; Watch out: Here we are talking about two different kind of tables.
32 ;; Most of the code is for the tables created with the Org-mode table editor.
33 ;; Sometimes, we talk about tables created and edited with the table.el
34 ;; Emacs package. We call the former org-type tables, and the latter
35 ;; table.el-type tables.
43 (declare-function org-table-clean-before-export
"org-exp"
44 (lines &optional maybe-quoted
))
45 (declare-function org-format-org-table-html
"org-html" (lines &optional splice
))
46 (defvar orgtbl-mode
) ; defined below
47 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
48 (defvar org-export-html-table-tag
) ; defined in org-exp.el
49 (defvar constants-unit-system
)
50 (defvar org-table-follow-field-mode
)
52 (defvar orgtbl-after-send-table-hook nil
53 "Hook for functions attaching to `C-c C-c', if the table is sent.
54 This can be used to add additional functionality after the table is sent
55 to the receiver position, othewise, if table is not sent, the functions
58 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
59 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
60 In the optimized version, the table editor takes over all simple keys that
61 normally just insert a character. In tables, the characters are inserted
62 in a way to minimize disturbing the table structure (i.e. in overwrite mode
63 for empty fields). Outside tables, the correct binding of the keys is
66 The default for this option is t if the optimized version is also used in
67 Org-mode. See the variable `org-enable-table-editor' for details. Changing
68 this variable requires a restart of Emacs to become effective."
72 (defcustom orgtbl-radio-table-templates
73 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
74 % END RECEIVE ORGTBL %n
76 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
79 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
80 @c END RECEIVE ORGTBL %n
82 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
85 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
86 <!-- END RECEIVE ORGTBL %n -->
88 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
91 "Templates for radio tables in different major modes.
92 All occurrences of %n in a template will be replaced with the name of the
93 table, obtained by prompting the user."
96 (list (symbol :tag
"Major mode")
97 (string :tag
"Format"))))
99 (defgroup org-table-settings nil
100 "Settings for tables in Org-mode."
101 :tag
"Org Table Settings"
104 (defcustom org-table-default-size
"5x2"
105 "The default size for newly created tables, Columns x Rows."
106 :group
'org-table-settings
109 (defcustom org-table-number-regexp
110 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
111 "Regular expression for recognizing numbers in table columns.
112 If a table column contains mostly numbers, it will be aligned to the
113 right. If not, it will be aligned to the left.
115 The default value of this option is a regular expression which allows
116 anything which looks remotely like a number as used in scientific
117 context. For example, all of the following will be considered a
119 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
121 Other options offered by the customize interface are more restrictive."
122 :group
'org-table-settings
124 (const :tag
"Positive Integers"
126 (const :tag
"Integers"
128 (const :tag
"Floating Point Numbers"
129 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
130 (const :tag
"Floating Point Number or Integer"
131 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
132 (const :tag
"Exponential, Floating point, Integer"
133 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
134 (const :tag
"Very General Number-Like, including hex"
135 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
136 (string :tag
"Regexp:")))
138 (defcustom org-table-number-fraction
0.5
139 "Fraction of numbers in a column required to make the column align right.
140 In a column all non-white fields are considered. If at least this
141 fraction of fields is matched by `org-table-number-fraction',
142 alignment to the right border applies."
143 :group
'org-table-settings
146 (defgroup org-table-editing nil
147 "Behavior of tables during editing in Org-mode."
148 :tag
"Org Table Editing"
151 (defcustom org-table-automatic-realign t
152 "Non-nil means automatically re-align table when pressing TAB or RETURN.
153 When nil, aligning is only done with \\[org-table-align], or after column
155 :group
'org-table-editing
158 (defcustom org-table-auto-blank-field t
159 "Non-nil means automatically blank table field when starting to type into it.
160 This only happens when typing immediately after a field motion
161 command (TAB, S-TAB or RET).
162 Only relevant when `org-enable-table-editor' is equal to `optimized'."
163 :group
'org-table-editing
166 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
167 "Non-nil means automatically exit the follow mode.
168 When nil, the follow mode will stay on and be active in any table
169 the cursor enters. Since the table follow filed mode messes with the
170 window configuration, it is not recommended to set this variable to nil,
171 except maybe locally in a special file that has mostly tables with long
176 (defcustom org-table-fix-formulas-confirm nil
177 "Whether the user should confirm when Org fixes formulas."
178 :group
'org-table-editing
180 (const :tag
"with yes-or-no" yes-or-no-p
)
181 (const :tag
"with y-or-n" y-or-n-p
)
182 (const :tag
"no confirmation" nil
)))
183 (put 'org-table-fix-formulas-confirm
185 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
187 (defcustom org-table-tab-jumps-over-hlines t
188 "Non-nil means tab in the last column of a table with jump over a hline.
189 If a horizontal separator line is following the current line,
190 `org-table-next-field' can either create a new row before that line, or jump
191 over the line. When this option is nil, a new line will be created before
193 :group
'org-table-editing
196 (defgroup org-table-calculation nil
197 "Options concerning tables in Org-mode."
198 :tag
"Org Table Calculation"
201 (defcustom org-table-use-standard-references
'from
202 "Should org-mode work with table references like B3 instead of @3$2?
205 from accept as input, do not present for editing
206 t accept as input and present for editing"
207 :group
'org-table-calculation
209 (const :tag
"Never, don't even check user input for them" nil
)
210 (const :tag
"Always, both as user input, and when editing" t
)
211 (const :tag
"Convert user input, don't offer during editing" from
)))
213 (defcustom org-table-copy-increment t
214 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
215 :group
'org-table-calculation
218 (defcustom org-calc-default-modes
219 '(calc-internal-prec 12
220 calc-float-format
(float 8)
223 calc-symbolic-mode nil
224 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
225 calc-display-working-message t
227 "List with Calc mode settings for use in `calc-eval' for table formulas.
228 The list must contain alternating symbols (Calc modes variables and values).
229 Don't remove any of the default settings, just change the values. Org-mode
230 relies on the variables to be present in the list."
231 :group
'org-table-calculation
234 (defcustom org-table-duration-custom-format
'hours
235 "Format for the output of calc computations like $1+$2;t.
236 The default value is 'hours, and will output the results as a
237 number of hours. Other allowed values are 'seconds, 'minutes and
238 'days, and the output will be a fraction of seconds, minutes or
240 :group
'org-table-calculation
241 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
242 (symbol :tag
"Minutes" 'minutes
)
243 (symbol :tag
"Hours " 'hours
)
244 (symbol :tag
"Days " 'days
)))
246 (defcustom org-table-formula-evaluate-inline t
247 "Non-nil means TAB and RET evaluate a formula in current table field.
248 If the current field starts with an equal sign, it is assumed to be a formula
249 which should be evaluated as described in the manual and in the documentation
250 string of the command `org-table-eval-formula'. This feature requires the
252 When this variable is nil, formula calculation is only available through
253 the command \\[org-table-eval-formula]."
254 :group
'org-table-calculation
257 (defcustom org-table-formula-use-constants t
258 "Non-nil means interpret constants in formulas in tables.
259 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
260 by the value given in `org-table-formula-constants', or by a value obtained
261 from the `constants.el' package."
262 :group
'org-table-calculation
265 (defcustom org-table-formula-constants nil
266 "Alist with constant names and values, for use in table formulas.
267 The car of each element is a name of a constant, without the `$' before it.
268 The cdr is the value as a string. For example, if you'd like to use the
269 speed of light in a formula, you would configure
271 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
273 and then use it in an equation like `$1*$c'.
275 Constants can also be defined on a per-file basis using a line like
277 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
278 :group
'org-table-calculation
280 (cons (string :tag
"name")
281 (string :tag
"value"))))
283 (defcustom org-table-allow-automatic-line-recalculation t
284 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
285 Automatically means when TAB or RET or C-c C-c are pressed in the line."
286 :group
'org-table-calculation
289 (defcustom org-table-error-on-row-ref-crossing-hline t
290 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
294 (defcustom org-table-relative-ref-may-cross-hline t
295 "Non-nil means relative formula references may cross hlines.
296 Here are the allowed values:
298 nil Relative references may not cross hlines. They will reference the
299 field next to the hline instead. Coming from below, the reference
300 will be to the field below the hline. Coming from above, it will be
302 t Relative references may cross hlines.
303 error An attempt to cross a hline will throw an error.
305 It is probably good to never set this variable to nil, for the sake of
306 portability of tables."
307 :group
'org-table-calculation
309 (const :tag
"Allow to cross" t
)
310 (const :tag
"Stick to hline" nil
)
311 (const :tag
"Error on attempt to cross" error
)))
313 (defgroup org-table-import-export nil
314 "Options concerning table import and export in Org-mode."
315 :tag
"Org Table Import Export"
318 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
319 "Default export parameters for `org-table-export'.
320 These can be overridden for a specific table by setting the
321 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
322 radio tables for the different export transformations and
323 available parameters."
324 :group
'org-table-import-export
327 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
328 "Detects a table line marked for automatic recalculation.")
329 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
330 "Detects a table line marked for automatic recalculation.")
331 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
332 "Detects a table line marked for automatic recalculation.")
333 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
334 "Searching from within a table (any type) this finds the first line outside the table.")
335 (defvar org-table-last-highlighted-reference nil
)
336 (defvar org-table-formula-history nil
)
338 (defvar org-table-column-names nil
339 "Alist with column names, derived from the `!' line.")
340 (defvar org-table-column-name-regexp nil
341 "Regular expression matching the current column names.")
342 (defvar org-table-local-parameters nil
343 "Alist with parameter names, derived from the `$' line.")
344 (defvar org-table-named-field-locations nil
345 "Alist with locations of named fields.")
347 (defvar org-table-current-line-types nil
348 "Table row types, non-nil only for the duration of a command.")
349 (defvar org-table-current-begin-line nil
350 "Table begin line, non-nil only for the duration of a command.")
351 (defvar org-table-current-begin-pos nil
352 "Table begin position, non-nil only for the duration of a command.")
353 (defvar org-table-current-ncol nil
354 "Number of columns in table, non-nil only for the duration of a command.")
355 (defvar org-table-dlines nil
356 "Vector of data line line numbers in the current table.")
357 (defvar org-table-hlines nil
358 "Vector of hline line numbers in the current table.")
360 (defconst org-table-range-regexp
361 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
363 "Regular expression for matching ranges in formulas.")
365 (defconst org-table-range-regexp2
367 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
369 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
370 "Match a range for reference display.")
372 (defun org-table-colgroup-line-p (line)
373 "Is this a table line colgroup information?"
375 (and (string-match "[<>]\\|&[lg]t;" line
)
376 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
382 (not (member s
'("" "<" ">" "<>" "<" ">" "<>"))))
383 (org-split-string (match-string 1 line
) "[ \t]*|[ \t]*")))))))
385 (defun org-table-cookie-line-p (line)
386 "Is this a table line with only alignment/width cookies?"
388 (and (string-match "[<>]\\|&[lg]t;" line
)
390 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line
)
391 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line
))
392 (not (delq nil
(mapcar
394 (not (or (equal s
"")
396 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s
)
398 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'"
400 (org-split-string (match-string 1 line
)
401 "[ \t]*|[ \t]*")))))))
403 (defconst org-table-translate-regexp
404 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
405 "Match a reference that needs translation, for reference display.")
407 (defun org-table-create-with-table.el
()
408 "Use the table.el package to insert a new table.
409 If there is already a table at point, convert between Org-mode tables
410 and table.el tables."
415 (if (y-or-n-p "Convert table to Org-mode table? ")
416 (org-table-convert)))
418 (when (y-or-n-p "Convert table to table.el table? ")
420 (org-table-convert)))
421 (t (call-interactively 'table-insert
))))
423 (defun org-table-create-or-convert-from-region (arg)
424 "Convert region to table, or create an empty table.
425 If there is an active region, convert it to a table, using the function
426 `org-table-convert-region'. See the documentation of that function
427 to learn how the prefix argument is interpreted to determine the field
429 If there is no such region, create an empty table with `org-table-create'."
431 (if (org-region-active-p)
432 (org-table-convert-region (region-beginning) (region-end) arg
)
433 (org-table-create arg
)))
435 (defun org-table-create (&optional size
)
436 "Query for a size and insert a table skeleton.
437 SIZE is a string Columns x Rows like for example \"3x2\"."
440 (setq size
(read-string
441 (concat "Table size Columns x Rows [e.g. "
442 org-table-default-size
"]: ")
443 "" nil org-table-default-size
)))
446 (indent (make-string (current-column) ?\
))
447 (split (org-split-string size
" *x *"))
448 (rows (string-to-number (nth 1 split
)))
449 (columns (string-to-number (car split
)))
450 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
452 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
453 (point-at-bol) (point)))
454 (beginning-of-line 1)
456 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
457 (dotimes (i rows
) (insert line
))
460 ;; Insert a hline after the first row.
467 (defun org-table-convert-region (beg0 end0
&optional separator
)
468 "Convert region to a table.
469 The region goes from BEG0 to END0, but these borders will be moved
470 slightly, to make sure a beginning of line in the first line is included.
472 SEPARATOR specifies the field separator in the lines. It can have the
475 '(4) Use the comma as a field separator
476 '(16) Use a TAB as field separator
477 integer When a number, use that many spaces as field separator
478 nil When nil, the command tries to be smart and figure out the
479 separator in the following way:
480 - when each line contains a TAB, assume TAB-separated material
481 - when each line contains a comma, assume CSV material
482 - else, assume one or more SPACE characters as separator."
484 (let* ((beg (min beg0 end0
))
485 (end (max beg0 end0
))
488 (beginning-of-line 1)
489 (setq beg
(move-marker (make-marker) (point)))
491 (if (bolp) (backward-char 1) (end-of-line 1))
492 (setq end
(move-marker (make-marker) (point)))
493 ;; Get the right field separator
498 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
499 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
502 (if (equal separator
'(4))
503 (while (< (point) end
)
504 ;; parse the csv stuff
506 ((looking-at "^") (insert "| "))
507 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
508 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
509 (replace-match "\\1")
510 (if (looking-at "\"") (insert "\"")))
511 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
512 ((looking-at "[ \t]*,") (replace-match " | "))
513 (t (beginning-of-line 2))))
515 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
516 ((equal separator
'(16)) "^\\|\t")
517 ((integerp separator
)
519 (error "Number of spaces in separator must be >= 1")
520 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
521 (t (error "This should not happen"))))
522 (while (re-search-forward re end t
)
523 (replace-match "| " t t
)))
527 (defun org-table-import (file arg
)
528 "Import FILE as a table.
529 The file is assumed to be tab-separated. Such files can be produced by most
530 spreadsheet and database applications. If no tabs (at least one per line)
531 are found, lines will be split on whitespace into fields."
533 (or (bolp) (newline))
536 (insert-file-contents file
)
537 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
540 (defvar org-table-last-alignment
)
541 (defvar org-table-last-column-widths
)
542 (defun org-table-export (&optional file format
)
543 "Export table to a file, with configurable format.
544 Such a file can be imported into a spreadsheet program like Excel.
545 FILE can be the output file name. If not given, it will be taken from
546 a TABLE_EXPORT_FILE property in the current entry or higher up in the
547 hierarchy, or the user will be prompted for a file name.
548 FORMAT can be an export format, of the same kind as it used when
549 `orgtbl-mode' sends a table in a different format. The default format can
550 be found in the variable `org-table-export-default-format', but the function
551 first checks if there is an export format specified in a TABLE_EXPORT_FORMAT
552 property, locally or anywhere up in the hierarchy."
554 (unless (org-at-table-p)
555 (error "No table at point"))
557 (org-table-align) ;; make sure we have everything we need
558 (let* ((beg (org-table-begin))
559 (end (org-table-end))
560 (txt (buffer-substring-no-properties beg end
))
561 (file (or file
(org-entry-get beg
"TABLE_EXPORT_FILE" t
)))
563 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)))
566 (setq file
(read-file-name "Export table to: "))
567 (unless (or (not (file-exists-p file
))
568 (y-or-n-p (format "Overwrite file %s? " file
)))
570 (if (file-directory-p file
)
571 (error "This is a directory path, not a file"))
572 (if (and (buffer-file-name)
573 (equal (file-truename file
)
574 (file-truename (buffer-file-name))))
575 (error "Please specify a file name that is different from current"))
577 (setq deffmt-readable org-table-export-default-format
)
578 (while (string-match "\t" deffmt-readable
)
579 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
580 (while (string-match "\n" deffmt-readable
)
581 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
582 (setq format
(org-completing-read
584 '("orgtbl-to-tsv" "orgtbl-to-csv"
585 "orgtbl-to-latex" "orgtbl-to-html"
586 "orgtbl-to-generic" "orgtbl-to-texinfo"
587 "orgtbl-to-orgtbl") nil nil
589 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
590 (let* ((transform (intern (match-string 1 format
)))
591 (params (if (match-end 2)
592 (read (concat "(" (match-string 2 format
) ")"))))
593 (skip (plist-get params
:skip
))
594 (skipcols (plist-get params
:skipcols
))
595 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
596 (lines (org-table-clean-before-export lines
))
597 (i0 (if org-table-clean-did-remove-column
2 1))
600 (if (string-match org-table-hline-regexp x
)
603 (org-split-string (org-trim x
) "\\s-*|\\s-*")
606 (fun (if (= i0
2) 'cdr
'identity
))
607 (org-table-last-alignment
608 (org-remove-by-index (funcall fun org-table-last-alignment
)
610 (org-table-last-column-widths
611 (org-remove-by-index (funcall fun org-table-last-column-widths
)
614 (unless (fboundp transform
)
615 (error "No such transformation function %s" transform
))
616 (setq txt
(funcall transform table params
))
618 (with-current-buffer (find-file-noselect file
)
619 (setq buf
(current-buffer))
625 (message "Export done."))
626 (error "TABLE_EXPORT_FORMAT invalid"))))
628 (defvar org-table-aligned-begin-marker
(make-marker)
629 "Marker at the beginning of the table last aligned.
630 Used to check if cursor still is in that table, to minimize realignment.")
631 (defvar org-table-aligned-end-marker
(make-marker)
632 "Marker at the end of the table last aligned.
633 Used to check if cursor still is in that table, to minimize realignment.")
634 (defvar org-table-last-alignment nil
635 "List of flags for flushright alignment, from the last re-alignment.
636 This is being used to correctly align a single field after TAB or RET.")
637 (defvar org-table-last-column-widths nil
638 "List of max width of fields in each column.
639 This is being used to correctly align a single field after TAB or RET.")
640 (defvar org-table-formula-debug nil
641 "Non-nil means debug table formulas.
642 When nil, simply write \"#ERROR\" in corrupted fields.")
643 (make-variable-buffer-local 'org-table-formula-debug
)
644 (defvar org-table-overlay-coordinates nil
645 "Overlay coordinates after each align of a table.")
646 (make-variable-buffer-local 'org-table-overlay-coordinates
)
648 (defvar org-last-recalc-line nil
)
649 (defvar org-table-do-narrow t
) ; for dynamic scoping
650 (defconst org-narrow-column-arrow
"=>"
651 "Used as display property in narrowed table columns.")
653 (defun org-table-align ()
654 "Align the table at point by aligning all vertical bars."
658 (beg (org-table-begin))
659 (end (org-table-end))
660 ;; Current cursor position
661 (linepos (org-current-line))
662 (colpos (org-table-current-column))
663 (winstart (window-start))
664 (winstartline (org-current-line (min winstart
(1- (point-max)))))
665 lines
(new "") lengths l typenums ty fields maxfields i
673 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
675 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
676 emptystrings links dates emph raise narrow
677 falign falign1 fmax f1 len c e space
)
679 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
680 ;; Check if we have links or dates
682 (setq links
(re-search-forward org-bracket-link-regexp end t
))
684 (setq emph
(and org-hide-emphasis-markers
685 (re-search-forward org-emph-re end t
)))
687 (setq raise
(and org-use-sub-superscripts
688 (re-search-forward org-match-substring-regexp end t
)))
690 (setq dates
(and org-display-custom-times
691 (re-search-forward org-ts-regexp-both end t
)))
692 ;; Make sure the link properties are right
693 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
694 ;; Make sure the date properties are right
695 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
696 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
697 (when raise
(goto-char beg
) (while (org-raise-scripts end
)))
699 ;; Check if we are narrowing any columns
701 (setq narrow
(and org-table-do-narrow
702 org-format-transports-properties-p
703 (re-search-forward "<[lrc]?[0-9]+>" end t
)))
705 (setq falign
(re-search-forward "<[lrc][0-9]*>" end t
))
708 (setq lines
(org-split-string
709 (buffer-substring beg end
) "\n"))
710 ;; Store the indentation of the first line
711 (if (string-match "^ *" (car lines
))
712 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
713 ;; Mark the hlines by setting the corresponding element to nil
714 ;; At the same time, we remove trailing space.
715 (setq lines
(mapcar (lambda (l)
716 (if (string-match "^ *|-" l
)
718 (if (string-match "[ \t]+$" l
)
719 (substring l
0 (match-beginning 0))
722 ;; Get the data fields by splitting the lines.
725 (org-split-string l
" *| *"))
726 (delq nil
(copy-sequence lines
))))
727 ;; How many fields in the longest line?
729 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
731 (kill-region beg end
)
732 (org-table-create org-table-default-size
)
733 (error "Empty table - created default table")))
734 ;; A list of empty strings to fill any short rows on output
735 (setq emptystrings
(make-list maxfields
""))
736 ;; Check for special formatting.
738 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
739 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
740 ;; Check if there is an explicit width specified
742 (when (or narrow falign
)
743 (setq c column fmax nil falign1 nil
)
746 (when (and (stringp e
) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e
))
747 (if (match-end 1) (setq falign1
(match-string 1 e
)))
748 (if (and org-table-do-narrow
(match-end 2))
749 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
750 ;; Find fields that are wider than fmax, and shorten them
752 (loop for xx in column do
753 (when (and (stringp xx
)
754 (> (org-string-width xx
) fmax
))
755 (org-add-props xx nil
757 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
758 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
760 (error "Cannot narrow field starting with wide link \"%s\""
761 (match-string 0 xx
)))
762 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
763 (add-text-properties (- f1
2) f1
764 (list 'display org-narrow-column-arrow
)
766 ;; Get the maximum width for each column
767 (push (apply 'max
(or fmax
1) 1 (mapcar 'org-string-width column
))
769 ;; Get the fraction of numbers, to decide about alignment of the column
771 (push (equal (downcase falign1
) "r") typenums
)
772 (setq cnt
0 frac
0.0)
773 (loop for x in column do
776 (setq frac
( / (+ (* frac cnt
)
777 (if (string-match org-table-number-regexp x
) 1 0))
778 (setq cnt
(1+ cnt
))))))
779 (push (>= frac org-table-number-fraction
) typenums
)))
780 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
782 ;; Store the alignment of this table, for later editing of single fields
783 (setq org-table-last-alignment typenums
784 org-table-last-column-widths lengths
)
786 ;; With invisible characters, `format' does not get the field width right
787 ;; So we need to make these fields wide by hand.
788 (when (or links emph raise
)
789 (loop for i from
0 upto
(1- maxfields
) do
790 (setq len
(nth i lengths
))
791 (loop for j from
0 upto
(1- (length fields
)) do
792 (setq c
(nthcdr i
(car (nthcdr j fields
))))
793 (if (and (stringp (car c
))
794 (or (text-property-any 0 (length (car c
))
795 'invisible
'org-link
(car c
))
796 (text-property-any 0 (length (car c
))
797 'org-dwidth t
(car c
)))
798 (< (org-string-width (car c
)) len
))
800 (setq space
(make-string (- len
(org-string-width (car c
))) ?\
))
801 (setcar c
(if (nth i typenums
)
802 (concat space
(car c
))
803 (concat (car c
) space
))))))))
805 ;; Compute the formats needed for output of the table
806 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
807 (while (setq l
(pop lengths
))
808 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
809 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
810 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
811 (setq rfmt
(concat rfmt
"\n")
812 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
816 (if l
(apply 'format rfmt
817 (append (pop fields
) emptystrings
))
820 (if (equal (char-before) ?
\n)
821 ;; This hack is for org-indent, to force redisplay of the
822 ;; line prefix of the first line. Apparently the redisplay
823 ;; is tied to the newline, which is, I think, a bug.
824 ;; To force this redisplay, we remove and re-insert the
825 ;; newline, so that the redisplay engine thinks it belongs
826 ;; to the changed text.
828 (backward-delete-char 1)
830 (move-marker org-table-aligned-begin-marker
(point))
832 ;; Replace the old one
833 (delete-region (point) end
)
834 (move-marker end nil
)
835 (move-marker org-table-aligned-end-marker
(point))
836 (when (and orgtbl-mode
(not (org-mode-p)))
837 (goto-char org-table-aligned-begin-marker
)
838 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
839 ;; Try to move to the old location
840 (org-goto-line winstartline
)
841 (setq winstart
(point-at-bol))
842 (org-goto-line linepos
)
843 (set-window-start (selected-window) winstart
'noforce
)
844 (org-table-goto-column colpos
)
845 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
846 (setq org-table-may-need-update nil
)
849 (defun org-table-begin (&optional table-type
)
850 "Find the beginning of the table and return its position.
851 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
853 (if (not (re-search-backward
854 (if table-type org-table-any-border-regexp
855 org-table-border-regexp
)
857 (progn (goto-char (point-min)) (point))
858 (goto-char (match-beginning 0))
859 (beginning-of-line 2)
862 (defun org-table-end (&optional table-type
)
863 "Find the end of the table and return its position.
864 With argument TABLE-TYPE, go to the end of a table.el-type table."
866 (if (not (re-search-forward
867 (if table-type org-table-any-border-regexp
868 org-table-border-regexp
)
870 (goto-char (point-max))
871 (goto-char (match-beginning 0)))
874 (defun org-table-justify-field-maybe (&optional new
)
875 "Justify the current field, text to left, number to right.
876 Optional argument NEW may specify text to replace the current field content."
878 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
879 ((org-at-table-hline-p))
881 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
883 (< (point) org-table-aligned-begin-marker
)
884 (>= (point) org-table-aligned-end-marker
)))
885 ;; This is not the same table, force a full re-align
886 (setq org-table-may-need-update t
))
887 (t ;; realign the current field, based on previous full realign
888 (let* ((pos (point)) s
889 (col (org-table-current-column))
890 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
893 (skip-chars-backward "^|\n")
894 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
896 (setq s
(match-string 1)
898 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
899 e
(not (= (match-beginning 2) (match-end 2))))
900 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
901 l
(if e
"|" (setq org-table-may-need-update t
) ""))
904 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
905 (setq n
(format f new
))
906 (setq n
(concat new
"|") org-table-may-need-update t
)))
907 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
909 (let (org-table-may-need-update)
910 (replace-match n t t
))))
911 (setq org-table-may-need-update t
))
914 (defun org-table-next-field ()
915 "Go to the next field in the current table, creating new lines as needed.
916 Before doing so, re-align the table if necessary."
918 (org-table-maybe-eval-formula)
919 (org-table-maybe-recalculate-line)
920 (if (and org-table-automatic-realign
921 org-table-may-need-update
)
923 (let ((end (org-table-end)))
924 (if (org-at-table-hline-p)
928 (re-search-forward "|" end
)
929 (if (looking-at "[ \t]*$")
930 (re-search-forward "|" end
))
931 (if (and (looking-at "-")
932 org-table-tab-jumps-over-hlines
933 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
934 (goto-char (match-beginning 1)))
937 (beginning-of-line 0)
938 (org-table-insert-row 'below
))
939 (if (looking-at " ") (forward-char 1))))
941 (org-table-insert-row 'below
)))))
943 (defun org-table-previous-field ()
944 "Go to the previous field in the table.
945 Before doing so, re-align the table if necessary."
947 (org-table-justify-field-maybe)
948 (org-table-maybe-recalculate-line)
949 (if (and org-table-automatic-realign
950 org-table-may-need-update
)
952 (if (org-at-table-hline-p)
956 (re-search-backward "|" (org-table-begin))
957 (re-search-backward "|" (org-table-begin)))
958 (error (error "Cannot move to previous table field")))
959 (while (looking-at "|\\(-\\|[ \t]*$\\)")
960 (re-search-backward "|" (org-table-begin)))
961 (if (looking-at "| ?")
962 (goto-char (match-end 0))))
964 (defun org-table-beginning-of-field (&optional n
)
965 "Move to the end of the current table field.
966 If already at or after the end, move to the end of the next table field.
967 With numeric argument N, move N-1 fields forward first."
972 (org-table-previous-field))
973 (if (not (re-search-backward "|" (point-at-bol 0) t
))
974 (error "No more table fields before the current")
975 (goto-char (match-end 0))
976 (and (looking-at " ") (forward-char 1)))
977 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
979 (defun org-table-end-of-field (&optional n
)
980 "Move to the beginning of the current table field.
981 If already at or before the beginning, move to the beginning of the
983 With numeric argument N, move N-1 fields backward first."
988 (org-table-next-field))
989 (when (re-search-forward "|" (point-at-eol 1) t
)
991 (skip-chars-backward " ")
992 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
994 (if (<= (point) pos
) (org-table-end-of-field 2))))
996 (defun org-table-next-row ()
997 "Go to the next row (same column) in the current table.
998 Before doing so, re-align the table if necessary."
1000 (org-table-maybe-eval-formula)
1001 (org-table-maybe-recalculate-line)
1002 (if (or (looking-at "[ \t]*$")
1003 (save-excursion (skip-chars-backward " \t") (bolp)))
1005 (if (and org-table-automatic-realign
1006 org-table-may-need-update
)
1008 (let ((col (org-table-current-column)))
1009 (beginning-of-line 2)
1010 (if (or (not (org-at-table-p))
1011 (org-at-table-hline-p))
1013 (beginning-of-line 0)
1014 (org-table-insert-row 'below
)))
1015 (org-table-goto-column col
)
1016 (skip-chars-backward "^|\n\r")
1017 (if (looking-at " ") (forward-char 1)))))
1019 (defun org-table-copy-down (n)
1020 "Copy a field down in the current column.
1021 If the field at the cursor is empty, copy into it the content of
1022 the nearest non-empty field above. With argument N, use the Nth
1023 non-empty field. If the current field is not empty, it is copied
1024 down to the next row, and the cursor is moved with it.
1025 Therefore, repeating this command causes the column to be filled
1027 If the variable `org-table-copy-increment' is non-nil and the
1028 field is an integer or a timestamp, it will be incremented while
1029 copying. In the case of a timestamp, increment by one day."
1031 (let* ((colpos (org-table-current-column))
1032 (col (current-column))
1033 (field (org-table-get-field))
1034 (non-empty (string-match "[^ \t]" field
))
1035 (beg (org-table-begin))
1038 (org-table-check-inside-data-field)
1041 (setq txt
(org-trim field
))
1042 (org-table-next-row)
1043 (org-table-blank-field))
1047 (while (progn (beginning-of-line 1)
1048 (re-search-backward org-table-dataline-regexp
1050 (org-table-goto-column colpos t
)
1051 (if (and (looking-at
1052 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1053 (<= (setq n
(1- n
)) 0))
1054 (throw 'exit
(match-string 1))))))))
1057 (if (and org-table-copy-increment
1058 (not (equal orig-n
0))
1059 (string-match "^[0-9]+$" txt
)
1060 (< (string-to-number txt
) 100000000))
1061 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
1063 (org-move-to-column col
)
1064 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1065 (org-timestamp-up-day)
1066 (org-table-maybe-recalculate-line))
1068 (org-move-to-column col
))
1069 (error "No non-empty field found"))))
1071 (defun org-table-check-inside-data-field (&optional noerror
)
1072 "Is point inside a table data field?
1073 I.e. not on a hline or before the first or after the last column?
1074 This actually throws an error, so it aborts the current command."
1075 (if (or (not (org-at-table-p))
1076 (= (org-table-current-column) 0)
1077 (org-at-table-hline-p)
1078 (looking-at "[ \t]*$"))
1081 (error "Not in table data field"))
1084 (defvar org-table-clip nil
1085 "Clipboard for table regions.")
1087 (defun org-table-get (line column
)
1088 "Get the field in table line LINE, column COLUMN.
1089 If LINE is larger than the number of data lines in the table, the function
1090 returns nil. However, if COLUMN is too large, we will simply return an
1092 If LINE is nil, use the current line.
1093 If column is nil, use the current column."
1094 (setq column
(or column
(org-table-current-column)))
1096 (and (or (not line
) (org-table-goto-line line
))
1097 (org-trim (org-table-get-field column
)))))
1099 (defun org-table-put (line column value
&optional align
)
1100 "Put VALUE into line LINE, column COLUMN.
1101 When ALIGN is set, also realign the table."
1102 (setq column
(or column
(org-table-current-column)))
1103 (prog1 (save-excursion
1104 (and (or (not line
) (org-table-goto-line line
))
1105 (progn (org-table-goto-column column nil
'force
) t
)
1106 (org-table-get-field column value
)))
1107 (and align
(org-table-align))))
1109 (defun org-table-current-line ()
1110 "Return the index of the current data line."
1111 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1113 (goto-char (org-table-begin))
1114 (while (and (re-search-forward org-table-dataline-regexp end t
)
1116 (< (point-at-eol) pos
))))
1119 (defun org-table-goto-line (N)
1120 "Go to the Nth data line in the current table.
1121 Return t when the line exists, nil if it does not exist."
1122 (goto-char (org-table-begin))
1123 (let ((end (org-table-end)) (cnt 0))
1124 (while (and (re-search-forward org-table-dataline-regexp end t
)
1125 (< (setq cnt
(1+ cnt
)) N
)))
1128 (defun org-table-blank-field ()
1129 "Blank the current table field or active region."
1131 (org-table-check-inside-data-field)
1132 (if (and (org-called-interactively-p 'any
) (org-region-active-p))
1133 (let (org-table-clip)
1134 (org-table-cut-region (region-beginning) (region-end)))
1135 (skip-chars-backward "^|")
1137 (if (looking-at "|[^|\n]+")
1138 (let* ((pos (match-beginning 0))
1139 (match (match-string 0))
1140 (len (org-string-width match
)))
1141 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1142 (goto-char (+ 2 pos
))
1143 (substring match
1)))))
1145 (defun org-table-get-field (&optional n replace
)
1146 "Return the value of the field in column N of current row.
1147 N defaults to current field.
1148 If REPLACE is a string, replace field with this value. The return value
1149 is always the old value."
1150 (and n
(org-table-goto-column n
))
1151 (skip-chars-backward "^|\n")
1153 (if (looking-at "|[^|\r\n]*")
1154 (let* ((pos (match-beginning 0))
1155 (val (buffer-substring (1+ pos
) (match-end 0))))
1157 (replace-match (concat "|" (if (equal replace
"") " " replace
))
1159 (goto-char (min (point-at-eol) (+ 2 pos
)))
1161 (forward-char 1) ""))
1163 (defun org-table-field-info (arg)
1164 "Show info about the current field, and highlight any reference at point."
1166 (org-table-get-specials)
1168 (let* ((pos (point))
1169 (col (org-table-current-column))
1170 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1171 (name (car (rassoc (list (org-current-line) col
)
1172 org-table-named-field-locations
)))
1173 (eql (org-table-expand-lhs-ranges
1176 (cons (org-table-formula-handle-first/last-rc
1178 (org-table-get-stored-formulas))))
1179 (dline (org-table-current-dline))
1180 (ref (format "@%d$%d" dline col
))
1181 (ref1 (org-table-convert-refs-to-an ref
))
1182 (fequation (or (assoc name eql
) (assoc ref eql
)))
1183 (cequation (assoc (int-to-string col
) eql
))
1184 (eqn (or fequation cequation
)))
1185 (if (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))
1186 (setq eqn
(get-text-property 0 :orig-eqn
(car eqn
))))
1189 (org-table-show-reference 'local
)
1191 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1193 (if cname
(concat " or $" cname
) "")
1195 (if name
(concat " or $" name
) "")
1196 ;; FIXME: formula info not correct if special table line
1198 (concat ", formula: "
1199 (org-table-formula-to-user
1201 (if (string-match "^[$@]"(car eqn
)) "" "$")
1202 (car eqn
) "=" (cdr eqn
))))
1205 (defun org-table-current-column ()
1206 "Find out which column we are in."
1208 (if (org-called-interactively-p 'any
) (org-table-check-inside-data-field))
1210 (let ((cnt 0) (pos (point)))
1211 (beginning-of-line 1)
1212 (while (search-forward "|" pos t
)
1213 (setq cnt
(1+ cnt
)))
1214 (when (org-called-interactively-p 'interactive
)
1215 (message "In table column %d" cnt
))
1218 (defun org-table-current-dline ()
1219 "Find out what table data line we are in.
1220 Only data lines count for this."
1222 (when (org-called-interactively-p 'any
)
1223 (org-table-check-inside-data-field))
1225 (let ((cnt 0) (pos (point)))
1226 (goto-char (org-table-begin))
1227 (while (<= (point) pos
)
1228 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1229 (beginning-of-line 2))
1230 (when (org-called-interactively-p 'any
)
1231 (message "This is table line %d" cnt
))
1234 (defun org-table-goto-column (n &optional on-delim force
)
1235 "Move the cursor to the Nth column in the current table line.
1236 With optional argument ON-DELIM, stop with point before the left delimiter
1238 If there are less than N fields, just go to after the last delimiter.
1239 However, when FORCE is non-nil, create new columns if necessary."
1241 (beginning-of-line 1)
1243 (while (and (> (setq n
(1- n
)) -
1)
1244 (or (search-forward "|" (point-at-eol) t
)
1246 (progn (end-of-line 1)
1247 (skip-chars-backward "^|")
1250 (when (and force
(not (looking-at ".*|")))
1251 (save-excursion (end-of-line 1) (insert " | ")))
1254 (if (looking-at " ") (forward-char 1)))))
1256 (defun org-table-insert-column ()
1257 "Insert a new column into the table."
1259 (if (not (org-at-table-p))
1260 (error "Not at a table"))
1261 (org-table-find-dataline)
1262 (let* ((col (max 1 (org-table-current-column)))
1263 (beg (org-table-begin))
1264 (end (org-table-end))
1265 ;; Current cursor position
1266 (linepos (org-current-line))
1269 (while (< (point) end
)
1270 (if (org-at-table-hline-p)
1272 (org-table-goto-column col t
)
1274 (beginning-of-line 2))
1275 (move-marker end nil
)
1276 (org-goto-line linepos
)
1277 (org-table-goto-column colpos
)
1279 (when (or (not org-table-fix-formulas-confirm
)
1280 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1281 (org-table-fix-formulas "$" nil
(1- col
) 1)
1282 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1284 (defun org-table-find-dataline ()
1285 "Find a data line in the current table, which is needed for column commands."
1286 (if (and (org-at-table-p)
1287 (not (org-at-table-hline-p)))
1289 (let ((col (current-column))
1290 (end (org-table-end)))
1291 (org-move-to-column col
)
1292 (while (and (< (point) end
)
1293 (or (not (= (current-column) col
))
1294 (org-at-table-hline-p)))
1295 (beginning-of-line 2)
1296 (org-move-to-column col
))
1297 (if (and (org-at-table-p)
1298 (not (org-at-table-hline-p)))
1301 "Please position cursor in a data line for column operations")))))
1303 (defun org-table-line-to-dline (line &optional above
)
1304 "Turn a buffer line number into a data line number.
1305 If there is no data line in this line, return nil.
1306 If there is no matchin dline (most likely te refrence was a hline), the
1307 first dline below it is used. When ABOVE is non-nil, the one above is used."
1309 (let ((ll (length org-table-dlines
))
1315 (if (<= (aref org-table-dlines i
) line
)
1320 (if (>= (aref org-table-dlines i
) line
)
1325 (defun org-table-delete-column ()
1326 "Delete a column from the table."
1328 (if (not (org-at-table-p))
1329 (error "Not at a table"))
1330 (org-table-find-dataline)
1331 (org-table-check-inside-data-field)
1332 (let* ((col (org-table-current-column))
1333 (beg (org-table-begin))
1334 (end (org-table-end))
1335 ;; Current cursor position
1336 (linepos (org-current-line))
1339 (while (< (point) end
)
1340 (if (org-at-table-hline-p)
1342 (org-table-goto-column col t
)
1343 (and (looking-at "|[^|\n]+|")
1344 (replace-match "|")))
1345 (beginning-of-line 2))
1346 (move-marker end nil
)
1347 (org-goto-line linepos
)
1348 (org-table-goto-column colpos
)
1350 (when (or (not org-table-fix-formulas-confirm
)
1351 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1352 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1354 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1357 (defun org-table-move-column-right ()
1358 "Move column to the right."
1360 (org-table-move-column nil
))
1361 (defun org-table-move-column-left ()
1362 "Move column to the left."
1364 (org-table-move-column 'left
))
1366 (defun org-table-move-column (&optional left
)
1367 "Move the current column to the right. With arg LEFT, move to the left."
1369 (if (not (org-at-table-p))
1370 (error "Not at a table"))
1371 (org-table-find-dataline)
1372 (org-table-check-inside-data-field)
1373 (let* ((col (org-table-current-column))
1374 (col1 (if left
(1- col
) col
))
1375 (beg (org-table-begin))
1376 (end (org-table-end))
1377 ;; Current cursor position
1378 (linepos (org-current-line))
1379 (colpos (if left
(1- col
) (1+ col
))))
1380 (if (and left
(= col
1))
1381 (error "Cannot move column further left"))
1382 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1383 (error "Cannot move column further right"))
1385 (while (< (point) end
)
1386 (if (org-at-table-hline-p)
1388 (org-table-goto-column col1 t
)
1389 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1390 (replace-match "|\\2|\\1|")))
1391 (beginning-of-line 2))
1392 (move-marker end nil
)
1393 (org-goto-line linepos
)
1394 (org-table-goto-column colpos
)
1396 (when (or (not org-table-fix-formulas-confirm
)
1397 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1398 (org-table-fix-formulas
1399 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1400 (cons (number-to-string colpos
) (number-to-string col
))))
1401 (org-table-fix-formulas
1402 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1403 (cons (number-to-string colpos
) (number-to-string col
)))))))
1405 (defun org-table-move-row-down ()
1406 "Move table row down."
1408 (org-table-move-row nil
))
1409 (defun org-table-move-row-up ()
1410 "Move table row up."
1412 (org-table-move-row 'up
))
1414 (defun org-table-move-row (&optional up
)
1415 "Move the current table line down. With arg UP, move it up."
1417 (let* ((col (current-column))
1419 (hline1p (save-excursion (beginning-of-line 1)
1420 (looking-at org-table-hline-regexp
)))
1421 (dline1 (org-table-current-dline))
1422 (dline2 (+ dline1
(if up -
1 1)))
1425 (beginning-of-line tonew
)
1426 (unless (org-at-table-p)
1428 (error "Cannot move row further"))
1429 (setq hline2p
(looking-at org-table-hline-regexp
))
1431 (beginning-of-line 1)
1433 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1434 (delete-region (point) (1+ (point-at-eol)))
1435 (beginning-of-line tonew
)
1437 (beginning-of-line 0)
1438 (org-move-to-column col
)
1439 (unless (or hline1p hline2p
1440 (not (or (not org-table-fix-formulas-confirm
)
1441 (funcall org-table-fix-formulas-confirm
1442 "Fix formulas? "))))
1443 (org-table-fix-formulas
1444 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1445 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1447 (defun org-table-insert-row (&optional arg
)
1448 "Insert a new row above the current line into the table.
1449 With prefix ARG, insert below the current line."
1451 (if (not (org-at-table-p))
1452 (error "Not at a table"))
1453 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1454 (new (org-table-clean-line line
)))
1455 ;; Fix the first field if necessary
1456 (if (string-match "^[ \t]*| *[#$] *|" line
)
1457 (setq new
(replace-match (match-string 0 line
) t t new
)))
1458 (beginning-of-line (if arg
2 1))
1459 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1460 (beginning-of-line 0)
1461 (re-search-forward "| ?" (point-at-eol) t
)
1462 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1464 (when (or (not org-table-fix-formulas-confirm
)
1465 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1466 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1468 (defun org-table-insert-hline (&optional above
)
1469 "Insert a horizontal-line below the current line into the table.
1470 With prefix ABOVE, insert above the current line."
1472 (if (not (org-at-table-p))
1473 (error "Not at a table"))
1474 (when (eobp) (insert "\n") (backward-char 1))
1475 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1477 (let ((line (org-table-clean-line
1478 (buffer-substring (point-at-bol) (point-at-eol))))
1479 (col (current-column)))
1480 (while (string-match "|\\( +\\)|" line
)
1481 (setq line
(replace-match
1482 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1483 ?-
) "|") t t line
)))
1484 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1485 (beginning-of-line (if above
1 2))
1487 (beginning-of-line (if above
1 -
1))
1488 (org-move-to-column col
)
1489 (and org-table-overlay-coordinates
(org-table-align))))
1491 (defun org-table-hline-and-move (&optional same-column
)
1492 "Insert a hline and move to the row below that line."
1494 (let ((col (org-table-current-column)))
1495 (org-table-maybe-eval-formula)
1496 (org-table-maybe-recalculate-line)
1497 (org-table-insert-hline)
1499 (if (looking-at "\n[ \t]*|-")
1500 (progn (insert "\n|") (org-table-align))
1501 (org-table-next-field))
1502 (if same-column
(org-table-goto-column col
))))
1504 (defun org-table-clean-line (s)
1505 "Convert a table line S into a string with only \"|\" and space.
1506 In particular, this does handle wide and invisible characters."
1507 (if (string-match "^[ \t]*|-" s
)
1508 ;; It's a hline, just map the characters
1509 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1510 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1511 (setq s
(replace-match
1512 (concat "|" (make-string (org-string-width (match-string 1 s
))
1517 (defun org-table-kill-row ()
1518 "Delete the current row or horizontal line from the table."
1520 (if (not (org-at-table-p))
1521 (error "Not at a table"))
1522 (let ((col (current-column))
1523 (dline (org-table-current-dline)))
1524 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1525 (if (not (org-at-table-p)) (beginning-of-line 0))
1526 (org-move-to-column col
)
1527 (when (or (not org-table-fix-formulas-confirm
)
1528 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1529 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1532 (defun org-table-sort-lines (with-case &optional sorting-type
)
1533 "Sort table lines according to the column at point.
1535 The position of point indicates the column to be used for
1536 sorting, and the range of lines is the range between the nearest
1537 horizontal separator lines, or the entire table of no such lines
1538 exist. If point is before the first column, you will be prompted
1539 for the sorting column. If there is an active region, the mark
1540 specifies the first line and the sorting column, while point
1541 should be in the last line to be included into the sorting.
1543 The command then prompts for the sorting type which can be
1544 alphabetically, numerically, or by time (as given in a time stamp
1545 in the field). Sorting in reverse order is also possible.
1547 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1549 If SORTING-TYPE is specified when this function is called from a Lisp
1550 program, no prompting will take place. SORTING-TYPE must be a character,
1551 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1552 should be done in reverse order."
1554 (let* ((thisline (org-current-line))
1555 (thiscol (org-table-current-column))
1556 beg end bcol ecol tend tbeg column lns pos
)
1557 (when (equal thiscol
0)
1558 (if (org-called-interactively-p 'any
)
1561 (read-string "Use column N for sorting: ")))
1563 (org-table-goto-column thiscol
))
1564 (org-table-check-inside-data-field)
1565 (if (org-region-active-p)
1567 (setq beg
(region-beginning) end
(region-end))
1569 (setq column
(org-table-current-column)
1572 (setq end
(point-at-bol 2)))
1573 (setq column
(org-table-current-column)
1575 tbeg
(org-table-begin)
1576 tend
(org-table-end))
1577 (if (re-search-backward org-table-hline-regexp tbeg t
)
1578 (setq beg
(point-at-bol 2))
1580 (setq beg
(point-at-bol 1)))
1582 (if (re-search-forward org-table-hline-regexp tend t
)
1583 (setq end
(point-at-bol 1))
1585 (setq end
(point-at-bol))))
1586 (setq beg
(move-marker (make-marker) beg
)
1587 end
(move-marker (make-marker) end
))
1590 (org-table-goto-column column
)
1591 (skip-chars-backward "^|")
1592 (setq bcol
(current-column))
1593 (org-table-goto-column (1+ column
))
1594 (skip-chars-backward "^|")
1595 (setq ecol
(1- (current-column)))
1596 (org-table-goto-column column
)
1597 (setq lns
(mapcar (lambda(x) (cons
1598 (org-sort-remove-invisible
1600 (org-split-string x
"[ \t]*|[ \t]*")))
1602 (org-split-string (buffer-substring beg end
) "\n")))
1603 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1604 (delete-region beg end
)
1605 (move-marker beg nil
)
1606 (move-marker end nil
)
1607 (insert (mapconcat 'cdr lns
"\n") "\n")
1608 (org-goto-line thisline
)
1609 (org-table-goto-column thiscol
)
1610 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1613 (defun org-table-cut-region (beg end
)
1614 "Copy region in table to the clipboard and blank all relevant fields.
1615 If there is no active region, use just the field at point."
1617 (if (org-region-active-p) (region-beginning) (point))
1618 (if (org-region-active-p) (region-end) (point))))
1619 (org-table-copy-region beg end
'cut
))
1621 (defun org-table-copy-region (beg end
&optional cut
)
1622 "Copy rectangular region in table to clipboard.
1623 A special clipboard is used which can only be accessed
1624 with `org-table-paste-rectangle'."
1626 (if (org-region-active-p) (region-beginning) (point))
1627 (if (org-region-active-p) (region-end) (point))
1628 current-prefix-arg
))
1629 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1631 (rpl (if cut
" " nil
)))
1633 (org-table-check-inside-data-field)
1634 (setq l01
(org-current-line)
1635 c01
(org-table-current-column))
1637 (org-table-check-inside-data-field)
1638 (setq l02
(org-current-line)
1639 c02
(org-table-current-column))
1640 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1641 c1
(min c01 c02
) c2
(max c01 c02
))
1645 (if (> l1 l2
) (throw 'exit t
))
1647 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1648 (setq cols nil ic1 c1 ic2 c2
)
1649 (while (< ic1
(1+ ic2
))
1650 (push (org-table-get-field ic1 rpl
) cols
)
1651 (setq ic1
(1+ ic1
)))
1652 (push (nreverse cols
) region
)
1653 (setq l1
(1+ l1
)))))
1654 (setq org-table-clip
(nreverse region
))
1655 (if cut
(org-table-align))
1658 (defun org-table-paste-rectangle ()
1659 "Paste a rectangular region into a table.
1660 The upper right corner ends up in the current field. All involved fields
1661 will be overwritten. If the rectangle does not fit into the present table,
1662 the table is enlarged as needed. The process ignores horizontal separator
1665 (unless (and org-table-clip
(listp org-table-clip
))
1666 (error "First cut/copy a region to paste!"))
1667 (org-table-check-inside-data-field)
1668 (let* ((clip org-table-clip
)
1669 (line (org-current-line))
1670 (col (org-table-current-column))
1671 (org-enable-table-editor t
)
1672 (org-table-automatic-realign nil
)
1674 (while (setq cols
(pop clip
))
1675 (while (org-at-table-hline-p) (beginning-of-line 2))
1676 (if (not (org-at-table-p))
1677 (progn (end-of-line 0) (org-table-next-field)))
1679 (while (setq field
(pop cols
))
1680 (org-table-goto-column c nil
'force
)
1681 (org-table-get-field nil field
)
1683 (beginning-of-line 2))
1684 (org-goto-line line
)
1685 (org-table-goto-column col
)
1688 (defun org-table-convert ()
1689 "Convert from `org-mode' table to table.el and back.
1690 Obviously, this only works within limits. When an Org-mode table is
1691 converted to table.el, all horizontal separator lines get lost, because
1692 table.el uses these as cell boundaries and has no notion of horizontal lines.
1693 A table.el table can be converted to an Org-mode table only if it does not
1694 do row or column spanning. Multiline cells will become multiple cells.
1695 Beware, Org-mode does not test if the table can be successfully converted - it
1696 blindly applies a recipe that works for simple tables."
1699 (if (org-at-table.el-p
)
1700 ;; convert to Org-mode table
1701 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1702 (end (move-marker (make-marker) (org-table-end t
))))
1703 (table-unrecognize-region beg end
)
1705 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1708 (if (org-at-table-p)
1709 ;; convert to table.el table
1710 (let ((beg (move-marker (make-marker) (org-table-begin)))
1711 (end (move-marker (make-marker) (org-table-end))))
1712 ;; first, get rid of all horizontal lines
1714 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1716 ;; insert a hline before first
1718 (org-table-insert-hline 'above
)
1719 (beginning-of-line -
1)
1720 ;; insert a hline after each line
1721 (while (progn (beginning-of-line 3) (< (point) end
))
1722 (org-table-insert-hline))
1724 (setq end
(move-marker end
(org-table-end)))
1725 ;; replace "+" at beginning and ending of hlines
1726 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1727 (replace-match "\\1+-"))
1729 (while (re-search-forward "-|[ \t]*$" end t
)
1730 (replace-match "-+"))
1733 (defun org-table-wrap-region (arg)
1734 "Wrap several fields in a column like a paragraph.
1735 This is useful if you'd like to spread the contents of a field over several
1736 lines, in order to keep the table compact.
1738 If there is an active region, and both point and mark are in the same column,
1739 the text in the column is wrapped to minimum width for the given number of
1740 lines. Generally, this makes the table more compact. A prefix ARG may be
1741 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1742 formats the selected text to two lines. If the region was longer than two
1743 lines, the remaining lines remain empty. A negative prefix argument reduces
1744 the current number of lines by that amount. The wrapped text is pasted back
1745 into the table. If you formatted it to more lines than it was before, fields
1746 further down in the table get overwritten - so you might need to make space in
1749 If there is no region, the current field is split at the cursor position and
1750 the text fragment to the right of the cursor is prepended to the field one
1753 If there is no region, but you specify a prefix ARG, the current field gets
1754 blank, and the content is appended to the field above."
1756 (org-table-check-inside-data-field)
1757 (if (org-region-active-p)
1758 ;; There is a region: fill as a paragraph
1759 (let* ((beg (region-beginning))
1760 (cline (save-excursion (goto-char beg
) (org-current-line)))
1761 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1763 (org-table-cut-region (region-beginning) (region-end))
1764 (if (> (length (car org-table-clip
)) 1)
1765 (error "Region must be limited to single column"))
1766 (setq nlines
(if arg
1768 (+ (length org-table-clip
) arg
)
1770 (length org-table-clip
)))
1771 (setq org-table-clip
1772 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1774 (org-goto-line cline
)
1775 (org-table-goto-column ccol
)
1776 (org-table-paste-rectangle))
1777 ;; No region, split the current field at point
1778 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1779 (skip-chars-forward "^\r\n|"))
1781 ;; combine with field above
1782 (let ((s (org-table-blank-field))
1783 (col (org-table-current-column)))
1784 (beginning-of-line 0)
1785 (while (org-at-table-hline-p) (beginning-of-line 0))
1786 (org-table-goto-column col
)
1787 (skip-chars-forward "^|")
1788 (skip-chars-backward " ")
1789 (insert " " (org-trim s
))
1792 (if (looking-at "\\([^|]+\\)+|")
1793 (let ((s (match-string 1)))
1794 (replace-match " |")
1795 (goto-char (match-beginning 0))
1796 (org-table-next-row)
1797 (insert (org-trim s
) " ")
1799 (org-table-next-row)))))
1801 (defvar org-field-marker nil
)
1803 (defun org-table-edit-field (arg)
1804 "Edit table field in a different window.
1805 This is mainly useful for fields that contain hidden parts.
1806 When called with a \\[universal-argument] prefix, just make the full field visible so that
1807 it can be edited in place."
1811 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
1813 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1814 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1815 (remove-text-properties b e
'(org-cwidth t invisible t
1816 display t intangible t
))
1817 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1818 (font-lock-fontify-block))))
1820 (let ((pos (move-marker (make-marker) (point)))
1822 (if (eq org-table-use-standard-references t
)
1823 (concat (org-number-to-letters (org-table-current-column))
1824 (int-to-string (org-table-current-dline)))
1825 (concat "@" (int-to-string (org-table-current-dline))
1826 "$" (int-to-string (org-table-current-column)))))
1827 (field (org-table-get-field))
1828 (cw (current-window-configuration))
1831 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
1832 (when (and (local-variable-p 'org-field-marker
)
1833 (markerp org-field-marker
))
1834 (move-marker org-field-marker nil
))
1836 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
1837 (let ((org-inhibit-startup t
)) (org-mode))
1839 (setq truncate-lines nil
)
1841 (goto-char (setq p
(point-max)))
1842 (insert (org-trim field
))
1843 (remove-text-properties p
(point-max)
1844 '(invisible t org-cwidth t display t
1847 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1848 (org-set-local 'org-window-configuration cw
)
1849 (org-set-local 'org-field-marker pos
)
1850 (message "Edit and finish with C-c C-c")))))
1852 (defun org-table-finish-edit-field ()
1853 "Finish editing a table data field.
1854 Remove all newline characters, insert the result into the table, realign
1855 the table and kill the editing buffer."
1856 (let ((pos org-field-marker
)
1857 (cw org-window-configuration
)
1858 (cb (current-buffer))
1860 (goto-char (point-min))
1861 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1862 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1863 (replace-match " "))
1864 (setq text
(org-trim (buffer-string)))
1865 (set-window-configuration cw
)
1867 (select-window (get-buffer-window (marker-buffer pos
)))
1869 (move-marker pos nil
)
1870 (org-table-check-inside-data-field)
1871 (org-table-get-field nil text
)
1873 (message "New field value inserted")))
1875 (define-minor-mode org-table-follow-field-mode
1876 "Minor mode to make the table field editor window follow the cursor.
1877 When this mode is active, the field editor window will always show the
1878 current field. The mode exits automatically when the cursor leaves the
1879 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
1880 nil
" TblFollow" nil
1881 (if org-table-follow-field-mode
1882 (org-add-hook 'post-command-hook
'org-table-follow-fields-with-editor
1884 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
1885 (let* ((buf (get-buffer "*Org Table Edit Field*"))
1886 (win (and buf
(get-buffer-window buf
))))
1887 (when win
(delete-window win
))
1889 (with-current-buffer buf
1890 (move-marker org-field-marker nil
))
1891 (kill-buffer buf
)))))
1893 (defun org-table-follow-fields-with-editor ()
1894 (if (and org-table-exit-follow-field-mode-when-leaving-table
1895 (not (org-at-table-p)))
1896 ;; We have left the table, exit the follow mode
1897 (org-table-follow-field-mode -
1)
1898 (when (org-table-check-inside-data-field 'noerror
)
1899 (let ((win (selected-window)))
1900 (org-table-edit-field nil
)
1901 (org-fit-window-to-buffer)
1902 (select-window win
)))))
1904 (defvar org-timecnt
) ; dynamically scoped parameter
1906 (defun org-table-sum (&optional beg end nlast
)
1907 "Sum numbers in region of current table column.
1908 The result will be displayed in the echo area, and will be available
1909 as kill to be inserted with \\[yank].
1911 If there is an active region, it is interpreted as a rectangle and all
1912 numbers in that rectangle will be summed. If there is no active
1913 region and point is located in a table column, sum all numbers in that
1916 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1917 numbers are assumed to be times as well (in decimal hours) and the
1918 numbers are added as such.
1920 If NLAST is a number, only the NLAST fields will actually be summed."
1923 (let (col (org-timecnt 0) diff h m s org-table-clip
)
1925 ((and beg end
)) ; beg and end given explicitly
1926 ((org-region-active-p)
1927 (setq beg
(region-beginning) end
(region-end)))
1929 (setq col
(org-table-current-column))
1930 (goto-char (org-table-begin))
1931 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
1932 (error "No table data"))
1933 (org-table-goto-column col
)
1935 (goto-char (org-table-end))
1936 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
1937 (error "No table data"))
1938 (org-table-goto-column col
)
1939 (setq end
(point))))
1940 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
1941 (items1 (cond ((not nlast
) items
)
1942 ((>= nlast
(length items
)) items
)
1943 (t (setq items
(reverse items
))
1944 (setcdr (nthcdr (1- nlast
) items
) nil
)
1946 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
1948 (res (apply '+ numbers
))
1949 (sres (if (= org-timecnt
0)
1950 (number-to-string res
)
1951 (setq diff
(* 3600 res
)
1952 h
(floor (/ diff
3600)) diff
(mod diff
3600)
1953 m
(floor (/ diff
60)) diff
(mod diff
60)
1955 (format "%d:%02d:%02d" h m s
))))
1957 (if (org-called-interactively-p 'interactive
)
1959 (substitute-command-keys
1960 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
1961 (length numbers
) sres
))))
1964 (defun org-table-get-number-for-summing (s)
1966 (if (string-match "^ *|? *" s
)
1967 (setq s
(replace-match "" nil nil s
)))
1968 (if (string-match " *|? *$" s
)
1969 (setq s
(replace-match "" nil nil s
)))
1970 (setq n
(string-to-number s
))
1972 ((and (string-match "0" s
)
1973 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
1974 ((string-match "\\`[ \t]+\\'" s
) nil
)
1975 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
1976 (let ((h (string-to-number (or (match-string 1 s
) "0")))
1977 (m (string-to-number (or (match-string 2 s
) "0")))
1978 (s (string-to-number (or (match-string 4 s
) "0"))))
1979 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
1980 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
1984 (defun org-table-current-field-formula (&optional key noerror
)
1985 "Return the formula active for the current field.
1986 Assumes that specials are in place.
1987 If KEY is given, return the key to this formula.
1988 Otherwise return the formula preceded with \"=\" or \":=\"."
1989 (let* ((name (car (rassoc (list (org-current-line)
1990 (org-table-current-column))
1991 org-table-named-field-locations
)))
1992 (col (org-table-current-column))
1993 (scol (int-to-string col
))
1994 (ref (format "@%d$%d" (org-table-current-dline) col
))
1995 (stored-list (org-table-get-stored-formulas noerror
))
1996 (ass (or (assoc name stored-list
)
1997 (assoc ref stored-list
)
1998 (assoc scol stored-list
))))
2001 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
2004 (defun org-table-get-formula (&optional equation named
)
2005 "Read a formula from the minibuffer, offer stored formula as default.
2006 When NAMED is non-nil, look for a named equation."
2007 (let* ((stored-list (org-table-get-stored-formulas))
2008 (name (car (rassoc (list (org-current-line)
2009 (org-table-current-column))
2010 org-table-named-field-locations
)))
2011 (ref (format "@%d$%d" (org-table-current-dline)
2012 (org-table-current-column)))
2013 (refass (assoc ref stored-list
))
2014 (nameass (assoc name stored-list
))
2016 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
2019 (int-to-string (org-table-current-column))))
2020 (dummy (and (or nameass refass
) (not named
)
2021 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2023 (name (or name ref
))
2024 (org-table-may-need-update nil
)
2025 (stored (cdr (assoc scol stored-list
)))
2027 ((and stored equation
(string-match "^ *=? *$" equation
))
2031 (t (org-table-formula-from-user
2033 (org-table-formula-to-user
2034 (format "%s formula %s%s="
2035 (if named
"Field" "Column")
2036 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
2038 (if stored
(org-table-formula-to-user stored
) "")
2039 'org-table-formula-history
2042 (when (not (string-match "\\S-" eq
))
2044 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2045 (org-table-store-formulas stored-list
)
2046 (error "Formula removed"))
2047 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2048 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2049 (if (and name
(not named
))
2050 ;; We set the column equation, delete the named one.
2051 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2054 (setcdr (assoc scol stored-list
) eq
)
2055 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2056 (if (or mustsave
(not (equal stored eq
)))
2057 (org-table-store-formulas stored-list
))
2060 (defun org-table-store-formulas (alist)
2061 "Store the list of formulas below the current table."
2062 (setq alist
(sort alist
'org-table-formula-less-p
))
2064 (goto-char (org-table-end))
2065 (if (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM:\\(.*\n?\\)")
2067 ;; don't overwrite TBLFM, we might use text properties to store stuff
2068 (goto-char (match-beginning 2))
2069 (delete-region (match-beginning 2) (match-end 0)))
2070 (org-indent-line-function)
2071 (insert "#+TBLFM:"))
2073 (mapconcat (lambda (x)
2075 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2076 (car x
) "=" (cdr x
)))
2080 (defsubst org-table-formula-make-cmp-string
(a)
2081 (when (string-match "\\`$[<>]" a
)
2082 (let ((arrow (string-to-char (substring a
1))))
2083 ;; Fake a high number to make sure this is sorted at the end.
2084 (setq a
(org-table-formula-handle-first/last-rc a
))
2085 (setq a
(format "$%d" (+ 10000
2086 (if (= arrow ?
<) -
1000 0)
2087 (string-to-number (substring a
1)))))))
2089 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2093 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2095 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2097 (concat "@@" (match-string 5 a
))))))
2099 (defun org-table-formula-less-p (a b
)
2100 "Compare two formulas for sorting."
2101 (let ((as (org-table-formula-make-cmp-string (car a
)))
2102 (bs (org-table-formula-make-cmp-string (car b
))))
2103 (and as bs
(string< as bs
))))
2105 (defun org-table-get-stored-formulas (&optional noerror
)
2106 "Return an alist with the stored formulas directly after current table."
2108 (let (scol eq eq-alist strings string seen
)
2110 (goto-char (org-table-end))
2111 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
2112 (setq strings
(org-split-string (org-match-string-no-properties 2)
2114 (while (setq string
(pop strings
))
2115 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2116 (setq scol
(if (match-end 2)
2117 (match-string 2 string
)
2118 (match-string 1 string
))
2119 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2120 (concat "$" scol
) scol
)
2121 eq
(match-string 3 string
)
2122 eq-alist
(cons (cons scol eq
) eq-alist
))
2123 (if (member scol seen
)
2126 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2129 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2130 (push scol seen
))))))
2131 (nreverse eq-alist
)))
2133 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2134 "Modify the equations after the table structure has been edited.
2135 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2136 For all numbers larger than LIMIT, shift them by DELTA."
2138 (goto-char (org-table-end))
2139 (when (looking-at "[ \t]*#\\+TBLFM:")
2140 (let ((re (concat key
"\\([0-9]+\\)"))
2143 (if (or (equal key
"$") (equal key
"$LR"))
2144 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2145 (regexp-quote key
) remove
)
2146 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2149 (while (re-search-forward re2
(point-at-eol) t
)
2150 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2151 (replace-match ""))))
2152 (while (re-search-forward re
(point-at-eol) t
)
2153 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2154 (setq s
(match-string 1) n
(string-to-number s
))
2156 ((setq a
(assoc s replace
))
2157 (replace-match (concat key
(cdr a
)) t t
))
2158 ((and limit
(> n limit
))
2159 (replace-match (concat key
(int-to-string (+ n delta
)))
2162 (defun org-table-get-specials ()
2163 "Get the column names and local parameters for this table."
2165 (let ((beg (org-table-begin)) (end (org-table-end))
2166 names name fields fields1 field cnt
2167 c v l line col types dlines hlines last-dline
)
2168 (setq org-table-column-names nil
2169 org-table-local-parameters nil
2170 org-table-named-field-locations nil
2171 org-table-current-begin-line nil
2172 org-table-current-begin-pos nil
2173 org-table-current-line-types nil
2174 org-table-current-ncol
0)
2176 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2177 (setq names
(org-split-string (match-string 1) " *| *")
2179 (while (setq name
(pop names
))
2181 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name
)
2182 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2183 (setq org-table-column-names
(nreverse org-table-column-names
))
2184 (setq org-table-column-name-regexp
2185 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2187 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2188 (setq fields
(org-split-string (match-string 1) " *| *"))
2189 (while (setq field
(pop fields
))
2190 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2191 (push (cons (match-string 1 field
) (match-string 2 field
))
2192 org-table-local-parameters
))))
2194 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2195 (setq c
(match-string 1)
2196 fields
(org-split-string (match-string 2) " *| *"))
2198 (beginning-of-line (if (equal c
"_") 2 0))
2199 (setq line
(org-current-line) col
1)
2200 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2201 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2202 (while (and fields1
(setq field
(pop fields
)))
2203 (setq v
(pop fields1
) col
(1+ col
))
2204 (when (and (stringp field
) (stringp v
)
2205 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field
))
2206 (push (cons field v
) org-table-local-parameters
)
2207 (push (list field line col
) org-table-named-field-locations
))))
2208 ;; Analyse the line types
2210 (setq org-table-current-begin-line
(org-current-line)
2211 org-table-current-begin-pos
(point)
2212 l org-table-current-begin-line
)
2213 (while (looking-at "[ \t]*|\\(-\\)?")
2214 (push (if (match-end 1) 'hline
'dline
) types
)
2215 (if (match-end 1) (push l hlines
) (push l dlines
))
2216 (beginning-of-line 2)
2218 (push 'hline types
) ;; add an imaginary extra hline to the end
2219 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2220 last-dline
(car dlines
)
2221 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2222 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2223 (org-goto-line last-dline
)
2224 (let* ((l last-dline
)
2225 (fields (org-split-string
2226 (buffer-substring (point-at-bol) (point-at-eol))
2228 (nfields (length fields
))
2230 (setq org-table-current-ncol nfields
)
2231 (loop for i from
1 to nfields do
2232 (push (list (format "LR%d" i
) l i
) al
)
2233 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2234 (setq org-table-named-field-locations
2235 (append org-table-named-field-locations al
))
2236 (setq org-table-local-parameters
2237 (append org-table-local-parameters al2
))))))
2239 (defun org-table-maybe-eval-formula ()
2240 "Check if the current field starts with \"=\" or \":=\".
2241 If yes, store the formula and apply it."
2242 ;; We already know we are in a table. Get field will only return a formula
2243 ;; when appropriate. It might return a separator line, but no problem.
2244 (when org-table-formula-evaluate-inline
2245 (let* ((field (org-trim (or (org-table-get-field) "")))
2247 (when (string-match "^:?=\\(.*\\)" field
)
2248 (setq named
(equal (string-to-char field
) ?
:)
2249 eq
(match-string 1 field
))
2250 (if (or (fboundp 'calc-eval
)
2251 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2252 (org-table-eval-formula (if named
'(4) nil
)
2253 (org-table-formula-from-user eq
))
2254 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2256 (defvar org-recalc-commands nil
2257 "List of commands triggering the recalculation of a line.
2258 Will be filled automatically during use.")
2260 (defvar org-recalc-marks
2261 '((" " .
"Unmarked: no special line, no automatic recalculation")
2262 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2263 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2264 ("!" .
"Column name definition line. Reference in formula as $name.")
2265 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2266 ("_" .
"Names for values in row below this one.")
2267 ("^" .
"Names for values in row above this one.")))
2269 (defun org-table-rotate-recalc-marks (&optional newchar
)
2270 "Rotate the recalculation mark in the first column.
2271 If in any row, the first field is not consistent with a mark,
2272 insert a new column for the markers.
2273 When there is an active region, change all the lines in the region,
2274 after prompting for the marking character.
2275 After each change, a message will be displayed indicating the meaning
2278 (unless (org-at-table-p) (error "Not at a table"))
2279 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2280 (beg (org-table-begin))
2281 (end (org-table-end))
2282 (l (org-current-line))
2283 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2284 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2288 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2289 (col (org-table-current-column))
2290 (forcenew (car (assoc newchar org-recalc-marks
)))
2293 (message "Change region to what mark? Type # * ! $ or SPC: ")
2294 (setq newchar
(char-to-string (read-char-exclusive))
2295 forcenew
(car (assoc newchar org-recalc-marks
))))
2296 (if (and newchar
(not forcenew
))
2297 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2299 (if l1
(org-goto-line l1
))
2301 (beginning-of-line 1)
2302 (unless (looking-at org-table-dataline-regexp
)
2303 (error "Not at a table data line")))
2305 (org-table-goto-column 1)
2306 (org-table-insert-column)
2307 (org-table-goto-column (1+ col
)))
2308 (setq epos
(point-at-eol))
2310 (beginning-of-line 1)
2311 (org-table-get-field
2312 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2314 (setq new
(or forcenew
2315 (cadr (member (match-string 1) marks
))))
2321 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2322 (and (looking-at org-table-dataline-regexp
)
2323 (org-table-get-field 1 (concat " " new
" "))))
2324 (org-goto-line l1
)))
2325 (if (not (= epos
(point-at-eol))) (org-table-align))
2327 (and (org-called-interactively-p 'interactive
)
2328 (message "%s" (cdr (assoc new org-recalc-marks
))))))
2330 (defun org-table-maybe-recalculate-line ()
2331 "Recompute the current line if marked for it, and if we haven't just done it."
2333 (and org-table-allow-automatic-line-recalculation
2334 (not (and (memq last-command org-recalc-commands
)
2335 (equal org-last-recalc-line
(org-current-line))))
2336 (save-excursion (beginning-of-line 1)
2337 (looking-at org-table-auto-recalculate-regexp
))
2338 (org-table-recalculate) t
))
2341 (defsubst org-set-calc-mode
(var &optional value
)
2343 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2344 ("R" calc-angle-mode rad
)
2345 ("F" calc-prefer-frac t
)
2346 ("S" calc-symbolic-mode t
)))
2347 value
(nth 2 var
) var
(nth 1 var
)))
2348 (if (memq var modes
)
2349 (setcar (cdr (memq var modes
)) value
)
2350 (cons var
(cons value modes
)))
2353 (defun org-table-eval-formula (&optional arg equation
2354 suppress-align suppress-const
2355 suppress-store suppress-analysis
)
2356 "Replace the table field value at the cursor by the result of a calculation.
2358 This function makes use of Dave Gillespie's Calc package, in my view the
2359 most exciting program ever written for GNU Emacs. So you need to have Calc
2360 installed in order to use this function.
2362 In a table, this command replaces the value in the current field with the
2363 result of a formula. It also installs the formula as the \"current\" column
2364 formula, by storing it in a special line below the table. When called
2365 with a `C-u' prefix, the current field must be a named field, and the
2366 formula is installed as valid in only this specific field.
2368 When called with two `C-u' prefixes, insert the active equation
2369 for the field back into the current field, so that it can be
2370 edited there. This is useful in order to use \\[org-table-show-reference]
2371 to check the referenced fields.
2373 When called, the command first prompts for a formula, which is read in
2374 the minibuffer. Previously entered formulas are available through the
2375 history list, and the last used formula is offered as a default.
2376 These stored formulas are adapted correctly when moving, inserting, or
2377 deleting columns with the corresponding commands.
2379 The formula can be any algebraic expression understood by the Calc package.
2380 For details, see the Org-mode manual.
2382 This function can also be called from Lisp programs and offers
2383 additional arguments: EQUATION can be the formula to apply. If this
2384 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2385 used to speed-up recursive calls by by-passing unnecessary aligns.
2386 SUPPRESS-CONST suppresses the interpretation of constants in the
2387 formula, assuming that this has been done already outside the function.
2388 SUPPRESS-STORE means the formula should not be stored, either because
2389 it is already stored, or because it is a modified equation that should
2390 not overwrite the stored one."
2392 (org-table-check-inside-data-field)
2393 (or suppress-analysis
(org-table-get-specials))
2394 (if (equal arg
'(16))
2395 (let ((eq (org-table-current-field-formula)))
2396 (or eq
(error "No equation active for current field"))
2397 (org-table-get-field nil eq
)
2399 (setq org-table-may-need-update t
))
2401 (ndown (if (integerp arg
) arg
1))
2402 (org-table-automatic-realign nil
)
2403 (case-fold-search nil
)
2405 (formula (if (and equation suppress-store
)
2407 (org-table-get-formula equation
(equal arg
'(4)))))
2408 (n0 (org-table-current-column))
2409 (modes (copy-sequence org-calc-default-modes
))
2410 (numbers nil
) ; was a variable, now fixed default
2412 n form form0 formrpl formrg bw fmt x ev orig c lispp literal duration
)
2413 ;; Parse the format string. Since we have a lot of modes, this is
2414 ;; a lot of work. However, I think calc still uses most of the time.
2415 (if (string-match ";" formula
)
2416 (let ((tmp (org-split-string formula
";")))
2417 (setq formula
(car tmp
)
2418 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2420 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2421 (setq c
(string-to-char (match-string 1 fmt
))
2422 n
(string-to-number (match-string 2 fmt
)))
2424 (setq modes
(org-set-calc-mode 'calc-internal-prec n
))
2425 (setq modes
(org-set-calc-mode
2427 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2428 (?s . sci
) (?e . eng
))))
2430 (setq fmt
(replace-match "" t t fmt
)))
2431 (if (string-match "T" fmt
)
2432 (setq duration t numbers t
2433 duration-output-format nil
2434 fmt
(replace-match "" t t fmt
)))
2435 (if (string-match "t" fmt
)
2437 duration-output-format org-table-duration-custom-format
2439 fmt
(replace-match "" t t fmt
)))
2440 (if (string-match "N" fmt
)
2442 fmt
(replace-match "" t t fmt
)))
2443 (if (string-match "L" fmt
)
2445 fmt
(replace-match "" t t fmt
)))
2446 (if (string-match "E" fmt
)
2448 fmt
(replace-match "" t t fmt
)))
2449 (while (string-match "[DRFS]" fmt
)
2450 (setq modes
(org-set-calc-mode (match-string 0 fmt
)))
2451 (setq fmt
(replace-match "" t t fmt
)))
2452 (unless (string-match "\\S-" fmt
)
2454 (if (and (not suppress-const
) org-table-formula-use-constants
)
2455 (setq formula
(org-table-formula-substitute-names formula
)))
2456 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2458 (setq fields
(org-split-string
2460 (buffer-substring (point-at-bol) (point-at-eol)))
2462 ;; replace fields with duration values if relevant
2465 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2468 (setq fields
(mapcar
2469 (lambda (x) (number-to-string (string-to-number x
)))
2471 (setq ndown
(1- ndown
))
2472 (setq form
(copy-sequence formula
)
2473 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2474 (if (and lispp literal
) (setq lispp
'literal
))
2476 ;; Insert row and column number of formula result field
2477 (while (string-match "[@$]#" form
)
2482 (if (equal (substring form
(match-beginning 0)
2483 (1+ (match-beginning 0)))
2485 (org-table-current-dline)
2486 (org-table-current-column))))
2489 ;; Check for old vertical references
2490 (setq form
(org-table-rewrite-old-row-references form
))
2491 ;; Insert remote references
2492 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2496 (org-table-make-reference
2497 (org-table-get-remote-range
2498 (match-string 1 form
) (match-string 2 form
))
2499 keep-empty numbers lispp
))
2501 ;; Insert complex ranges
2502 (while (and (string-match org-table-range-regexp form
)
2503 (> (length (match-string 0 form
)) 1))
2504 (setq formrg
(save-match-data
2505 (org-table-get-range (match-string 0 form
) nil n0
)))
2508 (org-table-make-reference
2509 ;; possibly handle durations
2512 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2513 (org-table-time-string-to-seconds formrg
))
2515 keep-empty numbers lispp
)))
2516 (if (not (save-match-data
2517 (string-match (regexp-quote form
) formrpl
)))
2518 (setq form
(replace-match formrpl t t form
))
2519 (error "Spreadsheet error: invalid reference \"%s\"" form
)))
2520 ;; Insert simple ranges
2521 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2525 (org-table-make-reference
2527 fields
(string-to-number (match-string 1 form
))
2528 (string-to-number (match-string 2 form
)))
2529 keep-empty numbers lispp
))
2532 ;; Insert the references to fields in same row
2533 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2534 (setq n
(+ (string-to-number (match-string 1 form
))
2535 (if (match-end 2) n0
0))
2536 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
))
2537 (unless x
(error "Invalid field specifier \"%s\""
2538 (match-string 0 form
)))
2539 (setq form
(replace-match
2541 (org-table-make-reference x nil numbers lispp
))
2545 (setq ev
(condition-case nil
2546 (eval (eval (read form
)))
2548 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2549 ev
(if duration
(org-table-time-seconds-to-string
2550 (string-to-number ev
)
2551 duration-output-format
) ev
))
2552 (or (fboundp 'calc-eval
)
2553 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2554 (setq ev
(calc-eval (cons form modes
) (if numbers
'num
))
2555 ev
(if duration
(org-table-time-seconds-to-string
2556 (string-to-number ev
)
2557 duration-output-format
) ev
)))
2559 (when org-table-formula-debug
2560 (with-output-to-temp-buffer "*Substitution History*"
2561 (princ (format "Substitution history of formula
2565 $1-> %s\n" orig formula form0 form
))
2567 (princ (format " %s^\nError: %s"
2568 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2569 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2571 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2572 (setq bw
(get-buffer-window "*Substitution History*"))
2573 (org-fit-window-to-buffer bw
)
2574 (unless (and (org-called-interactively-p 'any
) (not ndown
))
2575 (unless (let (inhibit-redisplay)
2576 (y-or-n-p "Debugging Formula. Continue to next? "))
2581 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2582 (org-table-justify-field-maybe
2583 (if fmt
(format fmt
(string-to-number ev
)) ev
))
2584 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2585 (call-interactively 'org-return
)
2587 (and down
(org-table-maybe-recalculate-line))
2588 (or suppress-align
(and org-table-may-need-update
2589 (org-table-align))))))
2591 (defun org-table-put-field-property (prop value
)
2593 (put-text-property (progn (skip-chars-backward "^|") (point))
2594 (progn (skip-chars-forward "^|") (point))
2597 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2598 "Get a calc vector from a column, according to descriptor DESC.
2599 Optional arguments TBEG and COL can give the beginning of the table and
2600 the current column, to avoid unnecessary parsing.
2602 HIGHLIGHT means just highlight the range.
2604 When CORNERS-ONLY is set, only return the corners of the range as
2605 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2606 in the buffer and column1 and column2 are table column numbers."
2607 (if (not (equal (string-to-char desc
) ?
@))
2608 (setq desc
(concat "@" desc
)))
2610 (or tbeg
(setq tbeg
(org-table-begin)))
2611 (or col
(setq col
(org-table-current-column)))
2612 (let ((thisline (org-current-line))
2613 beg end c1 c2 r1 r2 rangep tmp
)
2614 (unless (string-match org-table-range-regexp desc
)
2615 (error "Invalid table range specifier `%s'" desc
))
2616 (setq rangep
(match-end 3)
2617 r1
(and (match-end 1) (match-string 1 desc
))
2618 r2
(and (match-end 4) (match-string 4 desc
))
2619 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2620 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2622 (and c1
(setq c1
(+ (string-to-number c1
)
2623 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2624 (and c2
(setq c2
(+ (string-to-number c2
)
2625 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2626 (if (equal r1
"") (setq r1 nil
))
2627 (if (equal r2
"") (setq r2 nil
))
2628 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2629 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2630 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2631 (if (not r1
) (setq r1 thisline
))
2632 (if (not r2
) (setq r2 thisline
))
2633 (if (not c1
) (setq c1 col
))
2634 (if (not c2
) (setq c2 col
))
2635 (if (and (not corners-only
)
2636 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2640 (while (not (looking-at org-table-dataline-regexp
))
2641 (beginning-of-line 2))
2642 (prog1 (org-trim (org-table-get-field c1
))
2643 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2644 ;; A range, return a vector
2645 ;; First sort the numbers to get a regular ractangle
2646 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2647 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2649 ;; Only return the corners of the range
2651 ;; Copy the range values into a list
2653 (while (not (looking-at org-table-dataline-regexp
))
2654 (beginning-of-line 2))
2655 (org-table-goto-column c1
)
2658 (while (not (looking-at org-table-dataline-regexp
))
2659 (beginning-of-line 0))
2660 (org-table-goto-column c2
)
2663 (org-table-highlight-rectangle
2664 beg
(progn (skip-chars-forward "^|\n") (point))))
2665 ;; return string representation of calc vector
2667 (apply 'append
(org-table-copy-region beg end
))))))))
2669 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2670 "Analyze descriptor DESC and retrieve the corresponding line number.
2671 The cursor is currently in line CLINE, the table begins in line BLINE,
2672 and TABLE is a vector with line types."
2673 (if (string-match "^[0-9]+$" desc
)
2674 (aref org-table-dlines
(string-to-number desc
))
2675 (setq cline
(or cline
(org-current-line))
2676 bline
(or bline org-table-current-begin-line
)
2677 table
(or table org-table-current-line-types
))
2679 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2681 (and (not (match-end 3)) (not (match-end 6)))
2682 (and (match-end 3) (match-end 6) (not (match-end 5))))
2683 (error "Invalid row descriptor `%s'" desc
))
2684 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2685 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2686 (odir (and (match-end 5) (match-string 5 desc
)))
2687 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2689 (rel (and (match-end 6)
2690 (or (and (match-end 1) (not (match-end 3)))
2692 (if (and hn
(not hdir
))
2695 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2696 (if (and (not hn
) on
(not odir
))
2697 (error "Should never happen");;(aref org-table-dlines on)
2698 (if (and hn
(> hn
0))
2699 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2700 nil hn cline desc
)))
2702 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2703 rel on cline desc
)))
2706 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2707 "FIXME: Needs more documentation."
2708 (let ((l (length table
)))
2710 (while (and (setq i
(+ i
(if backwards -
1 1)))
2712 (not (eq (aref table i
) type
))
2713 (if (and relative
(eq (aref table i
) 'hline
))
2715 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2716 ((eq org-table-relative-ref-may-cross-hline
'error
)
2717 (error "Row descriptor %s used in line %d crosses hline" desc cline
))
2718 (t (setq i
(- i
(if backwards -
1 1))
2723 (if (or (< i
0) (>= i l
))
2724 (error "Row descriptor %s used in line %d leads outside table"
2728 (defun org-table-rewrite-old-row-references (s)
2729 (if (string-match "&[-+0-9I]" s
)
2730 (error "Formula contains old &row reference, please rewrite using @-syntax")
2733 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2734 "Convert list ELEMENTS to something appropriate to insert into formula.
2735 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2736 NUMBERS indicates that everything should be converted to numbers.
2737 LISPP means to return something appropriate for a Lisp list."
2738 (if (stringp elements
) ; just a single val
2740 (if (eq lispp
'literal
)
2742 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2743 (if (equal elements
"") (setq elements
"0"))
2744 (if numbers
(setq elements
(number-to-string (string-to-number elements
))))
2745 (concat "(" elements
")"))
2749 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2751 (setq elements
(or elements
'("0")))
2755 (if (eq lispp
'literal
)
2757 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2759 (concat "[" (mapconcat
2761 (if numbers
(number-to-string (string-to-number x
)) x
))
2765 (defun org-table-recalculate (&optional all noalign
)
2766 "Recalculate the current table line by applying all stored formulas.
2767 With prefix arg ALL, do this for all lines in the table.
2768 With the prefix argument ALL is `(16)' \
2769 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2770 it is the symbol `iterate', recompute the table until it no longer changes.
2771 If NOALIGN is not nil, do not re-align the table after the computations
2772 are done. This is typically used internally to save time, if it is
2773 known that the table will be realigned a little later anyway."
2775 (or (memq this-command org-recalc-commands
)
2776 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2777 (unless (org-at-table-p) (error "Not at a table"))
2778 (if (or (eq all
'iterate
) (equal all
'(16)))
2780 (org-table-get-specials)
2781 (let* ((eqlist (sort (org-table-get-stored-formulas)
2782 (lambda (a b
) (string< (car a
) (car b
)))))
2783 (eqlist1 (copy-sequence eqlist
))
2784 (inhibit-redisplay (not debug-on-error
))
2785 (line-re org-table-dataline-regexp
)
2786 (thisline (org-current-line))
2787 (thiscol (org-table-current-column))
2789 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
2790 ;; Insert constants in all formulas
2793 (when (string-match "\\`$[<>]" (car x
))
2795 (setq x
(cons (substring
2796 (org-table-formula-handle-first/last-rc
2799 (if (assoc (car x
) eqlist1
)
2800 (error "\"%s=\" formula tries to overwrite existing formula for column %s"
2803 (org-table-formula-handle-first/last-rc
(car x
))
2804 (org-table-formula-substitute-names
2805 (org-table-formula-handle-first/last-rc
(cdr x
)))))
2807 ;; Split the equation list
2808 (while (setq eq
(pop eqlist
))
2809 (if (<= (string-to-char (car eq
)) ?
9)
2812 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
2813 ;; Expand ranges in lhs of formulas
2814 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
2816 ;; Get the correct line range to process
2819 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
2820 (goto-char (setq beg
(org-table-begin)))
2821 (if (re-search-forward org-table-calculate-mark-regexp end t
)
2822 ;; This is a table with marked lines, compute selected lines
2823 (setq line-re org-table-recalculate-regexp
)
2824 ;; Move forward to the first non-header line
2825 (if (and (re-search-forward org-table-dataline-regexp end t
)
2826 (re-search-forward org-table-hline-regexp end t
)
2827 (re-search-forward org-table-dataline-regexp end t
))
2828 (setq beg
(match-beginning 0))
2829 nil
))) ;; just leave beg where it is
2830 (setq beg
(point-at-bol)
2831 end
(move-marker (make-marker) (1+ (point-at-eol)))))
2833 (and all
(message "Re-applying formulas to full table..."))
2835 ;; First find the named fields, and mark them untouchable.
2836 ;; Also check if several field/range formulas try to set the same field.
2837 (remove-text-properties beg end
'(org-untouchable t
))
2838 (while (setq eq
(pop eqlname
))
2840 a
(assoc name org-table-named-field-locations
))
2842 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
2844 (when (member name1 seen-fields
)
2845 (error "Several field/range formulas try to set %s" name1
))
2846 (push name1 seen-fields
)
2849 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
2852 (aref org-table-dlines
2853 (string-to-number (match-string 1 name
)))
2854 (error (error "Invalid row number in %s"
2856 (string-to-number (match-string 2 name
)))))
2857 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
2858 (message "Re-applying formula to field: %s" name
)
2859 (org-goto-line (nth 1 a
))
2860 (org-table-goto-column (nth 2 a
))
2861 (push (append a
(list (cdr eq
))) eqlname1
)
2862 (org-table-put-field-property :org-untouchable t
)))
2863 (setq eqlname1
(nreverse eqlname1
))
2865 ;; Now evaluate the column formulas, but skip fields covered by
2868 (while (re-search-forward line-re end t
)
2869 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2870 ;; Unprotected line, recalculate
2871 (and all
(message "Re-applying formulas to full table...(line %d)"
2872 (setq cnt
(1+ cnt
))))
2873 (setq org-last-recalc-line
(org-current-line))
2875 (while (setq entry
(pop eql
))
2876 (org-goto-line org-last-recalc-line
)
2877 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
2878 (unless (get-text-property (point) :org-untouchable
)
2879 (org-table-eval-formula nil
(cdr entry
)
2880 'noalign
'nocst
'nostore
'noanalysis
)))))
2882 ;; Now evaluate the field formulas
2883 (while (setq eq
(pop eqlname1
))
2884 (message "Re-applying formula to field: %s" (car eq
))
2885 (org-goto-line (nth 1 eq
))
2886 (org-table-goto-column (nth 2 eq
))
2887 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
2888 'nostore
'noanalysis
))
2890 (org-goto-line thisline
)
2891 (org-table-goto-column thiscol
)
2892 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
2893 (or noalign
(and org-table-may-need-update
(org-table-align))
2894 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
2896 ;; back to initial position
2897 (message "Re-applying formulas...done")
2898 (org-goto-line thisline
)
2899 (org-table-goto-column thiscol
)
2900 (or noalign
(and org-table-may-need-update
(org-table-align))
2901 (and all
(message "Re-applying formulas...done"))))))
2903 (defun org-table-iterate (&optional arg
)
2904 "Recalculate the table until it does not change anymore.
2905 The maximun number of iterations is 10, but you can chose a different value
2906 with the prefix ARG."
2908 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
2910 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2915 (org-table-recalculate 'all
)
2916 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
2917 (if (not (string= lasttbl thistbl
))
2918 (setq lasttbl thistbl
)
2920 (message "Convergence after %d iterations" i
)
2921 (message "Table was already stable"))
2923 (error "No convergence after %d iterations" i
))))
2925 (defun org-table-recalculate-buffer-tables ()
2926 "Recalculate all tables in the current buffer."
2931 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
2933 (defun org-table-iterate-buffer-tables ()
2934 "Iterate all tables in the buffer, to converge inter-table dependencies."
2937 (checksum (md5 (buffer-string)))
2947 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
2948 (if (equal checksum
(setq c1
(md5 (buffer-string))))
2950 (message "Convergence after %d iterations" (- imax i
))
2952 (setq checksum c1
)))
2953 (error "No convergence after %d iterations" imax
))))))
2955 (defun org-table-expand-lhs-ranges (equations)
2956 "Expand list of formulas.
2957 If some of the RHS in the formulas are ranges or a row reference, expand
2958 them to individual field equations for each field."
2959 (let (e res lhs rhs range r1 r2 c1 c2
)
2960 (while (setq e
(pop equations
))
2961 (setq lhs
(car e
) rhs
(cdr e
))
2963 ((string-match "^@-?[-+I0-9]+\\$-?[0-9]+$" lhs
)
2964 ;; This just refers to one fixed field
2966 ((string-match "^[a-zA-Z][a-zA-Z0-9]*$" lhs
)
2967 ;; This just refers to one fixed named field
2969 ((string-match "^@[0-9]+$" lhs
)
2970 (loop for ic from
1 to org-table-current-ncol do
2971 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
2972 (put-text-property 0 (length (caar res
))
2973 :orig-eqn e
(caar res
))))
2975 (setq range
(org-table-get-range lhs org-table-current-begin-pos
2977 (setq r1
(nth 0 range
) c1
(nth 1 range
)
2978 r2
(nth 2 range
) c2
(nth 3 range
))
2979 (setq r1
(org-table-line-to-dline r1
))
2980 (setq r2
(org-table-line-to-dline r2
'above
))
2981 (loop for ir from r1 to r2 do
2982 (loop for ic from c1 to c2 do
2983 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
2984 (put-text-property 0 (length (caar res
))
2985 :orig-eqn e
(caar res
)))))))
2988 (defun org-table-formula-handle-first/last-rc
(s)
2989 "Replace @<, @>, $<, $> with first/last row/column of the table.
2990 So @< and $< will always be replaced with @1 and $1, respectively.
2991 The advantage of these special markers are that structure editing of
2992 the table will not change them, while @1 and $1 will be modified
2993 when a line/row is swaped out of that privileged position. So for
2994 formulas that use a range of rows or columns, it may often be better
2995 to anchor the formula with \"I\" row markers, or to offset from the
2996 borders of the table using the @< @> $< $> makers."
2997 (let (n nmax len char
)
2998 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)" s
)
2999 (setq nmax
(if (equal (match-string 1 s
) "@")
3000 (1- (length org-table-dlines
))
3001 org-table-current-ncol
)
3002 len
(- (match-end 2) (match-beginning 2))
3003 char
(string-to-char (match-string 2 s
))
3007 (if (or (< n
1) (> n nmax
))
3008 (error "Reference \"%s\" in expression \"%s\" points outside table"
3009 (match-string 0 s
) s
))
3010 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
))))
3013 (defun org-table-formula-substitute-names (f)
3014 "Replace $const with values in string F."
3015 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
3016 ;; First, check for column names
3017 (while (setq start
(string-match org-table-column-name-regexp f start
))
3018 (setq start
(1+ start
))
3019 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
3020 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
3021 ;; Parameters and constants
3023 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
3025 (setq start
(match-end 2))
3026 (setq start
(1+ start
))
3027 (if (setq a
(save-match-data
3028 (org-table-get-constant (match-string 1 f
))))
3029 (setq f
(replace-match
3030 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
3031 (if org-table-formula-debug
3032 (put-text-property 0 (length f
) :orig-formula f1 f
))
3035 (defun org-table-get-constant (const)
3036 "Find the value for a parameter or constant in a formula.
3037 Parameters get priority."
3038 (or (cdr (assoc const org-table-local-parameters
))
3039 (cdr (assoc const org-table-formula-constants-local
))
3040 (cdr (assoc const org-table-formula-constants
))
3041 (and (fboundp 'constants-get
) (constants-get const
))
3042 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3043 (org-entry-get nil
(substring const
5) 'inherit
))
3046 (defvar org-table-fedit-map
3047 (let ((map (make-sparse-keymap)))
3048 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3049 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3050 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3051 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3052 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3053 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3054 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3055 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3056 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3057 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3058 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3059 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3060 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3061 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3062 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3063 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3064 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3065 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3066 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3067 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3070 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3072 ["Finish and Install" org-table-fedit-finish t
]
3073 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3074 ["Abort" org-table-fedit-abort t
]
3076 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3077 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3079 "Shift Reference at Point"
3080 ["Up" org-table-fedit-ref-up t
]
3081 ["Down" org-table-fedit-ref-down t
]
3082 ["Left" org-table-fedit-ref-left t
]
3083 ["Right" org-table-fedit-ref-right t
]
3085 "Change Test Row for Column Formulas"
3086 ["Up" org-table-fedit-line-up t
]
3087 ["Down" org-table-fedit-line-down t
]
3089 ["Scroll Table Window" org-table-fedit-scroll t
]
3090 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3091 ["Show Table Grid" org-table-fedit-toggle-coordinates
3092 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3093 org-table-overlay-coordinates
)]
3095 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3096 :style toggle
:selected org-table-buffer-is-an
]))
3100 (defun org-table-edit-formulas ()
3101 "Edit the formulas of the current table in a separate buffer."
3103 (when (save-excursion (beginning-of-line 1) (looking-at "[ \t]*#\\+TBLFM"))
3104 (beginning-of-line 0))
3105 (unless (org-at-table-p) (error "Not at a table"))
3106 (org-table-get-specials)
3107 (let ((key (org-table-current-field-formula 'key
'noerror
))
3108 (eql (sort (org-table-get-stored-formulas 'noerror
)
3109 'org-table-formula-less-p
))
3110 (pos (move-marker (make-marker) (point)))
3112 (wc (current-window-configuration))
3113 (sel-win (selected-window))
3114 (titles '((column .
"# Column Formulas\n")
3115 (field .
"# Field and Range Formulas\n")
3116 (named .
"# Named Field Formulas\n")))
3118 (org-switch-to-buffer-other-window "*Edit Formulas*")
3120 ;; Keep global-font-lock-mode from turning on font-lock-mode
3121 (let ((font-lock-global-modes '(not fundamental-mode
)))
3123 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
3124 (org-set-local 'org-pos pos
)
3125 (org-set-local 'org-window-configuration wc
)
3126 (org-set-local 'org-selected-window sel-win
)
3127 (use-local-map org-table-fedit-map
)
3128 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3129 (easy-menu-add org-table-fedit-menu
)
3130 (setq startline
(org-current-line))
3131 (while (setq entry
(pop eql
))
3133 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3134 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3135 ((string-match "^[0-9]" (car entry
)) 'column
)
3137 (when (setq title
(assq type titles
))
3138 (or (bobp) (insert "\n"))
3139 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3140 (setq titles
(remove title titles
)))
3141 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3142 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3143 (car entry
) " = " (cdr entry
) "\n"))
3144 (remove-text-properties 0 (length s
) '(face nil
) s
)
3146 (if (eq org-table-use-standard-references t
)
3147 (org-table-fedit-toggle-ref-type))
3148 (org-goto-line startline
)
3149 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3151 (defun org-table-fedit-post-command ()
3152 (when (not (memq this-command
'(lisp-complete-symbol)))
3153 (let ((win (selected-window)))
3156 (org-table-show-reference)
3158 (select-window win
)))))
3160 (defun org-table-formula-to-user (s)
3161 "Convert a formula from internal to user representation."
3162 (if (eq org-table-use-standard-references t
)
3163 (org-table-convert-refs-to-an s
)
3166 (defun org-table-formula-from-user (s)
3167 "Convert a formula from user to internal representation."
3168 (if org-table-use-standard-references
3169 (org-table-convert-refs-to-rc s
)
3172 (defun org-table-convert-refs-to-rc (s)
3173 "Convert spreadsheet references from A7 to @7$28.
3174 Works for single references, but also for entire formulas and even the
3177 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^)]*)\\)" s start
)
3180 ;; format match, just advance
3181 (setq start
(match-end 0)))
3182 ((and (> (match-beginning 0) 0)
3183 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3184 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3185 ;; 3.e5 or something like this.
3186 (setq start
(match-end 0)))
3187 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3188 ;; (member (match-string 1 s)
3189 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3191 ;; function name, just advance
3192 (setq start
(match-end 0)))
3194 (setq start
(match-beginning 0)
3196 (if (equal (match-string 2 s
) "&")
3197 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3199 (string-to-number (match-string 2 s
))
3200 (org-letters-to-number (match-string 1 s
))))
3204 (defun org-table-convert-refs-to-an (s)
3205 "Convert spreadsheet references from to @7$28 to AB7.
3206 Works for single references, but also for entire formulas and even the
3208 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3209 (setq s
(replace-match
3211 (org-number-to-letters
3212 (string-to-number (match-string 2 s
)))
3213 (string-to-number (match-string 1 s
)))
3215 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3216 (setq s
(replace-match (concat "\\1"
3217 (org-number-to-letters
3218 (string-to-number (match-string 2 s
))) "&")
3222 (defun org-letters-to-number (s)
3223 "Convert a base 26 number represented by letters into an integer.
3224 For example: AB -> 28."
3227 (while (> (length s
) 0)
3228 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3232 (defun org-number-to-letters (n)
3233 "Convert an integer into a base 26 number represented by letters.
3234 For example: 28 -> AB."
3237 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3241 (defun org-table-time-string-to-seconds (s)
3242 "Convert a time string into numerical duration in seconds.
3243 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3244 If S is a string representing a number, keep this number."
3245 (let (hour min sec res
)
3247 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3248 (setq minus
(< 0 (length (match-string 1 s
)))
3249 hour
(string-to-number (match-string 2 s
))
3250 min
(string-to-number (match-string 3 s
))
3251 sec
(string-to-number (match-string 4 s
)))
3253 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3254 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3255 ((and (not (string-match org-ts-regexp-both s
))
3256 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3257 (setq minus
(< 0 (length (match-string 1 s
)))
3258 hour
(string-to-number (match-string 2 s
))
3259 min
(string-to-number (match-string 3 s
)))
3261 (setq res
(- (+ (* hour
3600) (* min
60))))
3262 (setq res
(+ (* hour
3600) (* min
60)))))
3263 (t (setq res
(string-to-number s
))))
3264 (number-to-string res
)))
3266 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3267 "Convert a number of seconds to a time string.
3268 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3269 minutes or seconds."
3270 (cond ((eq output-format
'days
)
3271 (format "%.3f" (/ (float secs
) 86400)))
3272 ((eq output-format
'hours
)
3273 (format "%.2f" (/ (float secs
) 3600)))
3274 ((eq output-format
'minutes
)
3275 (format "%.1f" (/ (float secs
) 60)))
3276 ((eq output-format
'seconds
)
3278 (t (org-format-seconds "%.2h:%.2m:%.2s" secs
))))
3280 (defun org-table-fedit-convert-buffer (function)
3281 "Convert all references in this buffer, using FUNCTION."
3282 (let ((line (org-current-line)))
3283 (goto-char (point-min))
3285 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3286 (delete-region (point) (point-at-eol))
3287 (or (eobp) (forward-char 1)))
3288 (org-goto-line line
)))
3290 (defun org-table-fedit-toggle-ref-type ()
3291 "Convert all references in the buffer from B3 to @3$2 and back."
3293 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3294 (org-table-fedit-convert-buffer
3295 (if org-table-buffer-is-an
3296 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3297 (message "Reference type switched to %s"
3298 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3300 (defun org-table-fedit-ref-up ()
3301 "Shift the reference at point one row/hline up."
3303 (org-table-fedit-shift-reference 'up
))
3304 (defun org-table-fedit-ref-down ()
3305 "Shift the reference at point one row/hline down."
3307 (org-table-fedit-shift-reference 'down
))
3308 (defun org-table-fedit-ref-left ()
3309 "Shift the reference at point one field to the left."
3311 (org-table-fedit-shift-reference 'left
))
3312 (defun org-table-fedit-ref-right ()
3313 "Shift the reference at point one field to the right."
3315 (org-table-fedit-shift-reference 'right
))
3317 (defun org-table-fedit-shift-reference (dir)
3319 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3320 (if (memq dir
'(left right
))
3321 (org-rematch-and-replace 1 (eq dir
'left
))
3322 (error "Cannot shift reference in this direction")))
3323 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3324 ;; A B3-like reference
3325 (if (memq dir
'(up down
))
3326 (org-rematch-and-replace 2 (eq dir
'up
))
3327 (org-rematch-and-replace 1 (eq dir
'left
))))
3329 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3330 ;; An internal reference
3331 (if (memq dir
'(up down
))
3332 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3333 (org-rematch-and-replace 5 (eq dir
'left
))))))
3335 (defun org-rematch-and-replace (n &optional decr hline
)
3336 "Re-match the group N, and replace it with the shifted reference."
3337 (or (match-end n
) (error "Cannot shift reference in this direction"))
3338 (goto-char (match-beginning n
))
3339 (and (looking-at (regexp-quote (match-string n
)))
3340 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3343 (defun org-table-shift-refpart (ref &optional decr hline
)
3344 "Shift a reference part REF.
3345 If DECR is set, decrease the references row/column, else increase.
3346 If HLINE is set, this may be a hline reference, it certainly is not
3347 a translation reference."
3349 (let* ((sign (string-match "^[-+]" ref
)) n
)
3351 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3353 ((and hline
(string-match "^I+" ref
))
3354 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3355 (setq n
(+ n
(if decr -
1 1)))
3356 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3358 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3360 (concat sign
(make-string n ?I
)))
3362 ((string-match "^[0-9]+" ref
)
3363 (setq n
(string-to-number (concat sign ref
)))
3364 (setq n
(+ n
(if decr -
1 1)))
3366 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3367 (number-to-string (max 1 n
))))
3369 ((string-match "^[a-zA-Z]+" ref
)
3370 (org-number-to-letters
3371 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3373 (t (error "Cannot shift reference"))))))
3375 (defun org-table-fedit-toggle-coordinates ()
3376 "Toggle the display of coordinates in the referenced table."
3378 (let ((pos (marker-position org-pos
)))
3379 (with-current-buffer (marker-buffer org-pos
)
3382 (org-table-toggle-coordinate-overlays)))))
3384 (defun org-table-fedit-finish (&optional arg
)
3385 "Parse the buffer for formula definitions and install them.
3386 With prefix ARG, apply the new formulas to the table."
3388 (org-table-remove-rectangle-highlight)
3389 (if org-table-use-standard-references
3391 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3392 (setq org-table-buffer-is-an nil
)))
3393 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3394 (goto-char (point-min))
3395 (while (re-search-forward
3396 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3398 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3399 form
(match-string 3))
3400 (setq form
(org-trim form
))
3401 (when (not (equal form
""))
3402 (while (string-match "[ \t]*\n[ \t]*" form
)
3403 (setq form
(replace-match " " t t form
)))
3404 (when (assoc var eql
)
3405 (error "Double formulas for %s" var
))
3406 (push (cons var form
) eql
)))
3408 (set-window-configuration org-window-configuration
)
3409 (select-window sel-win
)
3411 (unless (org-at-table-p)
3412 (error "Lost table position - cannot install formulas"))
3413 (org-table-store-formulas eql
)
3414 (move-marker pos nil
)
3415 (kill-buffer "*Edit Formulas*")
3417 (org-table-recalculate 'all
)
3418 (message "New formulas installed - press C-u C-c C-c to apply."))))
3420 (defun org-table-fedit-abort ()
3421 "Abort editing formulas, without installing the changes."
3423 (org-table-remove-rectangle-highlight)
3424 (let ((pos org-pos
) (sel-win org-selected-window
))
3425 (set-window-configuration org-window-configuration
)
3426 (select-window sel-win
)
3428 (move-marker pos nil
)
3429 (message "Formula editing aborted without installing changes")))
3431 (defun org-table-fedit-lisp-indent ()
3432 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3434 (let ((pos (point)) beg end ind
)
3435 (beginning-of-line 1)
3437 ((looking-at "[ \t]")
3439 (call-interactively 'lisp-indent-line
))
3440 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3441 ((not (fboundp 'pp-buffer
))
3442 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3443 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3444 (goto-char (- (match-end 0) 2))
3446 (setq ind
(make-string (current-column) ?\
))
3447 (condition-case nil
(forward-sexp 1)
3449 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3452 (narrow-to-region beg end
)
3453 (if (eq last-command this-command
)
3455 (goto-char (point-min))
3456 (setq this-command nil
)
3457 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3458 (replace-match " ")))
3460 (untabify (point-min) (point-max))
3461 (goto-char (1+ (point-min)))
3462 (while (re-search-forward "^." nil t
)
3463 (beginning-of-line 1)
3465 (goto-char (point-max))
3466 (backward-delete-char 1)))
3470 (defvar org-show-positions nil
)
3472 (defun org-table-show-reference (&optional local
)
3473 "Show the location/value of the $ expression at point."
3475 (org-table-remove-rectangle-highlight)
3477 (let ((pos (if local
(point) org-pos
))
3479 (org-inhibit-highlight-removal t
)
3480 (win (selected-window))
3481 (org-show-positions nil
)
3482 var name e what match dest
)
3483 (if local
(org-table-get-specials))
3485 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3486 (setq match
(concat (substring (match-string 0) 0 -
1)
3488 (substring (match-string 0) 0 -
1)
3491 ((or (org-at-regexp-p org-table-range-regexp2
)
3492 (org-at-regexp-p org-table-translate-regexp
)
3493 (org-at-regexp-p org-table-range-regexp
))
3496 (org-table-convert-refs-to-rc (match-string 0))))
3498 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3499 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3501 (t (error "No reference at point")))
3502 match
(and what
(or match
(match-string 0))))
3503 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3504 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3505 'secondary-selection
))
3506 (org-add-hook 'before-change-functions
3507 'org-table-remove-rectangle-highlight
)
3508 (if (eq what
'name
) (setq var
(substring match
1)))
3509 (when (eq what
'range
)
3510 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3511 (setq match
(org-table-formula-substitute-names match
)))
3515 (re-search-backward "^\\S-" nil t
)
3516 (beginning-of-line 1)
3517 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3520 (org-table-convert-refs-to-rc (match-string 1))))
3521 (org-table-add-rectangle-overlay
3522 (match-beginning 1) (match-end 1) face2
))))
3523 (if (and (markerp pos
) (marker-buffer pos
))
3524 (if (get-buffer-window (marker-buffer pos
))
3525 (select-window (get-buffer-window (marker-buffer pos
)))
3526 (org-switch-to-buffer-other-window (get-buffer-window
3527 (marker-buffer pos
)))))
3529 (org-table-force-dataline)
3531 (setq name
(substring dest
1))
3533 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3534 (setq e
(assoc name org-table-named-field-locations
))
3535 (org-goto-line (nth 1 e
))
3536 (org-table-goto-column (nth 2 e
)))
3537 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3538 (let ((l (string-to-number (match-string 1 dest
)))
3539 (c (string-to-number (match-string 2 dest
))))
3540 (org-goto-line (aref org-table-dlines l
))
3541 (org-table-goto-column c
)))
3542 (t (org-table-goto-column (string-to-number name
))))
3543 (move-marker pos
(point))
3544 (org-table-highlight-rectangle nil nil face2
))
3546 ((equal dest match
))
3551 (org-table-get-range match nil nil
'highlight
))
3553 ((setq e
(assoc var org-table-named-field-locations
))
3554 (org-goto-line (nth 1 e
))
3555 (org-table-goto-column (nth 2 e
))
3556 (org-table-highlight-rectangle (point) (point))
3557 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3558 ((setq e
(assoc var org-table-column-names
))
3559 (org-table-goto-column (string-to-number (cdr e
)))
3560 (org-table-highlight-rectangle (point) (point))
3561 (goto-char (org-table-begin))
3562 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3565 (goto-char (match-beginning 1))
3566 (org-table-highlight-rectangle)
3567 (message "Named column (column %s)" (cdr e
)))
3568 (error "Column name not found")))
3571 (org-table-goto-column (string-to-number (substring match
1)))
3572 (org-table-highlight-rectangle (point) (point))
3573 (message "Column %s" (substring match
1)))
3574 ((setq e
(assoc var org-table-local-parameters
))
3575 (goto-char (org-table-begin))
3576 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3578 (goto-char (match-beginning 1))
3579 (org-table-highlight-rectangle)
3580 (message "Local parameter."))
3581 (error "Parameter not found")))
3584 ((not var
) (error "No reference at point"))
3585 ((setq e
(assoc var org-table-formula-constants-local
))
3586 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3588 ((setq e
(assoc var org-table-formula-constants
))
3589 (message "Constant: $%s=%s in `org-table-formula-constants'."
3591 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3592 (message "Constant: $%s=%s, from `constants.el'%s."
3593 var e
(format " (%s units)" constants-unit-system
)))
3594 (t (error "Undefined name $%s" var
)))))
3596 (when (and org-show-positions
3597 (not (memq this-command
'(org-table-fedit-scroll
3598 org-table-fedit-scroll-down
))))
3599 (push pos org-show-positions
)
3600 (push org-table-current-begin-pos org-show-positions
)
3601 (let ((min (apply 'min org-show-positions
))
3602 (max (apply 'max org-show-positions
)))
3603 (goto-char min
) (recenter 0)
3605 (or (pos-visible-in-window-p max
) (recenter -
1))))
3606 (select-window win
))))
3608 (defun org-table-force-dataline ()
3609 "Make sure the cursor is in a dataline in a table."
3610 (unless (save-excursion
3611 (beginning-of-line 1)
3612 (looking-at org-table-dataline-regexp
))
3613 (let* ((re org-table-dataline-regexp
)
3614 (p1 (save-excursion (re-search-forward re nil
'move
)))
3615 (p2 (save-excursion (re-search-backward re nil
'move
))))
3617 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3619 ((or p1 p2
) (goto-char (or p1 p2
)))
3620 (t (error "No table dataline around here"))))))
3622 (defun org-table-fedit-line-up ()
3623 "Move cursor one line up in the window showing the table."
3625 (org-table-fedit-move 'previous-line
))
3627 (defun org-table-fedit-line-down ()
3628 "Move cursor one line down in the window showing the table."
3630 (org-table-fedit-move 'next-line
))
3632 (defun org-table-fedit-move (command)
3633 "Move the cursor in the window showing the table.
3634 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3635 (let ((org-table-allow-automatic-line-recalculation nil
)
3636 (pos org-pos
) (win (selected-window)) p
)
3637 (select-window (get-buffer-window (marker-buffer org-pos
)))
3639 (call-interactively command
)
3640 (while (and (org-at-table-p)
3641 (org-at-table-hline-p))
3642 (call-interactively command
))
3643 (or (org-at-table-p) (goto-char p
))
3644 (move-marker pos
(point))
3645 (select-window win
)))
3647 (defun org-table-fedit-scroll (N)
3649 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3650 (scroll-other-window N
)))
3652 (defun org-table-fedit-scroll-down (N)
3654 (org-table-fedit-scroll (- N
)))
3656 (defvar org-table-rectangle-overlays nil
)
3658 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3659 "Add a new overlay."
3660 (let ((ov (make-overlay beg end
)))
3661 (overlay-put ov
'face
(or face
'secondary-selection
))
3662 (push ov org-table-rectangle-overlays
)))
3664 (defun org-table-highlight-rectangle (&optional beg end face
)
3665 "Highlight rectangular region in a table."
3666 (setq beg
(or beg
(point)) end
(or end
(point)))
3667 (let ((b (min beg end
))
3670 (and (boundp 'org-show-positions
)
3671 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3672 (goto-char (min beg end
))
3673 (setq l1
(org-current-line)
3674 c1
(org-table-current-column))
3675 (goto-char (max beg end
))
3676 (setq l2
(org-current-line)
3677 c2
(org-table-current-column))
3678 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3680 (beginning-of-line 1)
3681 (loop for line from l1 to l2 do
3682 (when (looking-at org-table-dataline-regexp
)
3683 (org-table-goto-column c1
)
3684 (skip-chars-backward "^|\n") (setq beg
(point))
3685 (org-table-goto-column c2
)
3686 (skip-chars-forward "^|\n") (setq end
(point))
3687 (org-table-add-rectangle-overlay beg end face
))
3688 (beginning-of-line 2))
3690 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3692 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3693 "Remove the rectangle overlays."
3694 (unless org-inhibit-highlight-removal
3695 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3696 (mapc 'delete-overlay org-table-rectangle-overlays
)
3697 (setq org-table-rectangle-overlays nil
)))
3699 (defvar org-table-coordinate-overlays nil
3700 "Collects the coordinate grid overlays, so that they can be removed.")
3701 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3703 (defun org-table-overlay-coordinates ()
3704 "Add overlays to the table at point, to show row/column coordinates."
3706 (mapc 'delete-overlay org-table-coordinate-overlays
)
3707 (setq org-table-coordinate-overlays nil
)
3709 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3710 (goto-char (org-table-begin))
3711 (while (org-at-table-p)
3712 (setq eol
(point-at-eol))
3713 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
3714 (push ov org-table-coordinate-overlays
)
3715 (setq hline
(looking-at org-table-hline-regexp
))
3716 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3717 (format "%4d" (setq id
(1+ id
)))))
3718 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3721 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3722 (setq beg
(1+ (match-beginning 0))
3724 s1
(concat "$" (int-to-string ic
))
3725 s2
(org-number-to-letters ic
)
3726 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3727 (setq ov
(make-overlay beg
(+ beg
(length str
))))
3728 (push ov org-table-coordinate-overlays
)
3729 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3730 (beginning-of-line 2)))))
3732 (defun org-table-toggle-coordinate-overlays ()
3733 "Toggle the display of Row/Column numbers in tables."
3735 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3736 (message "Row/Column number display turned %s"
3737 (if org-table-overlay-coordinates
"on" "off"))
3738 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3740 (unless org-table-overlay-coordinates
3741 (mapc 'delete-overlay org-table-coordinate-overlays
)
3742 (setq org-table-coordinate-overlays nil
)))
3744 (defun org-table-toggle-formula-debugger ()
3745 "Toggle the formula debugger in tables."
3747 (setq org-table-formula-debug
(not org-table-formula-debug
))
3748 (message "Formula debugging has been turned %s"
3749 (if org-table-formula-debug
"on" "off")))
3751 ;;; The orgtbl minor mode
3753 ;; Define a minor mode which can be used in other modes in order to
3754 ;; integrate the org-mode table editor.
3756 ;; This is really a hack, because the org-mode table editor uses several
3757 ;; keys which normally belong to the major mode, for example the TAB and
3758 ;; RET keys. Here is how it works: The minor mode defines all the keys
3759 ;; necessary to operate the table editor, but wraps the commands into a
3760 ;; function which tests if the cursor is currently inside a table. If that
3761 ;; is the case, the table editor command is executed. However, when any of
3762 ;; those keys is used outside a table, the function uses `key-binding' to
3763 ;; look up if the key has an associated command in another currently active
3764 ;; keymap (minor modes, major mode, global), and executes that command.
3765 ;; There might be problems if any of the keys used by the table editor is
3766 ;; otherwise used as a prefix key.
3768 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3769 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3770 ;; addresses this by checking explicitly for both bindings.
3772 ;; The optimized version (see variable `orgtbl-optimized') takes over
3773 ;; all keys which are bound to `self-insert-command' in the *global map*.
3774 ;; Some modes bind other commands to simple characters, for example
3775 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3776 ;; active, this binding is ignored inside tables and replaced with a
3777 ;; modified self-insert.
3780 (defvar orgtbl-mode-map
(make-keymap)
3781 "Keymap for `orgtbl-mode'.")
3784 (defun turn-on-orgtbl ()
3785 "Unconditionally turn on `orgtbl-mode'."
3788 (defvar org-old-auto-fill-inhibit-regexp nil
3789 "Local variable used by `orgtbl-mode'.")
3791 (defconst orgtbl-line-start-regexp
3792 "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\|TBLNAME\\):\\)"
3793 "Matches a line belonging to an orgtbl.")
3795 (defconst orgtbl-extra-font-lock-keywords
3796 (list (list (concat "^" orgtbl-line-start-regexp
".*")
3797 0 (quote 'org-table
) 'prepend
))
3798 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
3800 ;; Install it as a minor mode.
3801 (put 'orgtbl-mode
:included t
)
3802 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
3805 (define-minor-mode orgtbl-mode
3806 "The `org-mode' table editor as a minor mode for use in other modes."
3807 :lighter
" OrgTbl" :keymap orgtbl-mode-map
3808 (org-load-modules-maybe)
3811 ;; Exit without error, in case some hook functions calls this
3812 ;; by accident in org-mode.
3813 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
3815 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
3816 ;; Make sure we are first in minor-mode-map-alist
3817 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
3818 ;; FIXME: maybe it should use emulation-mode-map-alists?
3819 (and c
(setq minor-mode-map-alist
3820 (cons c
(delq c minor-mode-map-alist
)))))
3821 (org-set-local (quote org-table-may-need-update
) t
)
3822 (org-add-hook 'before-change-functions
'org-before-change-function
3824 (org-set-local 'org-old-auto-fill-inhibit-regexp
3825 auto-fill-inhibit-regexp
)
3826 (org-set-local 'auto-fill-inhibit-regexp
3827 (if auto-fill-inhibit-regexp
3828 (concat orgtbl-line-start-regexp
"\\|"
3829 auto-fill-inhibit-regexp
)
3830 orgtbl-line-start-regexp
))
3831 (add-to-invisibility-spec '(org-cwidth))
3832 (when (fboundp 'font-lock-add-keywords
)
3833 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
3834 (org-restart-font-lock))
3835 (easy-menu-add orgtbl-mode-menu
))
3837 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
3838 (org-table-cleanup-narrow-column-properties)
3839 (org-remove-from-invisibility-spec '(org-cwidth))
3840 (remove-hook 'before-change-functions
'org-before-change-function t
)
3841 (when (fboundp 'font-lock-remove-keywords
)
3842 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
3843 (org-restart-font-lock))
3844 (easy-menu-remove orgtbl-mode-menu
)
3845 (force-mode-line-update 'all
))))
3847 (defun org-table-cleanup-narrow-column-properties ()
3848 "Remove all properties related to narrow-column invisibility."
3849 (let ((s (point-min)))
3850 (while (setq s
(text-property-any s
(point-max)
3851 'display org-narrow-column-arrow
))
3852 (remove-text-properties s
(1+ s
) '(display t
)))
3853 (setq s
(point-min))
3854 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
3855 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
3856 (setq s
(point-min))
3857 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
3858 (remove-text-properties s
(1+ s
) '(invisible t
)))))
3860 (defun orgtbl-make-binding (fun n
&rest keys
)
3861 "Create a function for binding in the table minor mode.
3862 FUN is the command to call inside a table. N is used to create a unique
3863 command name. KEYS are keys that should be checked in for a command
3864 to execute outside of tables."
3867 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
3869 (concat "In tables, run `" (symbol-name fun
) "'.\n"
3870 "Outside of tables, run the binding of `"
3871 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
3876 (list 'call-interactively
(list 'quote fun
))
3877 (list 'let
'(orgtbl-mode)
3878 (list 'call-interactively
3881 (list 'key-binding k
))
3883 '('orgtbl-error
))))))))
3885 (defun orgtbl-error ()
3886 "Error when there is no default binding for a table key."
3888 (error "This key has no function outside tables"))
3890 (defun orgtbl-setup ()
3891 "Setup orgtbl keymaps."
3894 '(([(meta shift left
)] org-table-delete-column
)
3895 ([(meta left
)] org-table-move-column-left
)
3896 ([(meta right
)] org-table-move-column-right
)
3897 ([(meta shift right
)] org-table-insert-column
)
3898 ([(meta shift up
)] org-table-kill-row
)
3899 ([(meta shift down
)] org-table-insert-row
)
3900 ([(meta up
)] org-table-move-row-up
)
3901 ([(meta down
)] org-table-move-row-down
)
3902 ("\C-c\C-w" org-table-cut-region
)
3903 ("\C-c\M-w" org-table-copy-region
)
3904 ("\C-c\C-y" org-table-paste-rectangle
)
3905 ("\C-c-" org-table-insert-hline
)
3906 ("\C-c}" org-table-toggle-coordinate-overlays
)
3907 ("\C-c{" org-table-toggle-formula-debugger
)
3908 ("\C-m" org-table-next-row
)
3909 ([(shift return
)] org-table-copy-down
)
3910 ("\C-c?" org-table-field-info
)
3911 ("\C-c " org-table-blank-field
)
3912 ("\C-c+" org-table-sum
)
3913 ("\C-c=" org-table-eval-formula
)
3914 ("\C-c'" org-table-edit-formulas
)
3915 ("\C-c`" org-table-edit-field
)
3916 ("\C-c*" org-table-recalculate
)
3917 ("\C-c^" org-table-sort-lines
)
3918 ("\M-a" org-table-beginning-of-field
)
3919 ("\M-e" org-table-end-of-field
)
3920 ([(control ?
#)] org-table-rotate-recalc-marks
)))
3922 (while (setq elt
(pop bindings
))
3923 (setq nfunc
(1+ nfunc
))
3924 (setq key
(org-key (car elt
))
3926 cmd
(orgtbl-make-binding fun nfunc key
))
3927 (org-defkey orgtbl-mode-map key cmd
))
3929 ;; Special treatment needed for TAB and RET
3930 (org-defkey orgtbl-mode-map
[(return)]
3931 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
3932 (org-defkey orgtbl-mode-map
"\C-m"
3933 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
3935 (org-defkey orgtbl-mode-map
[(tab)]
3936 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
3937 (org-defkey orgtbl-mode-map
"\C-i"
3938 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
3940 (org-defkey orgtbl-mode-map
[(shift tab
)]
3941 (orgtbl-make-binding 'org-table-previous-field
104
3942 [(shift tab
)] [(tab)] "\C-i"))
3945 (unless (featurep 'xemacs
)
3946 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
3947 (orgtbl-make-binding 'org-table-previous-field
107
3948 [S-iso-lefttab
] [backtab] [(shift tab)]
3951 (org-defkey orgtbl-mode-map [backtab]
3952 (orgtbl-make-binding 'org-table-previous-field
108
3953 [backtab] [S-iso-lefttab] [(shift tab)]
3956 (org-defkey orgtbl-mode-map "\M-\C-m"
3957 (orgtbl-make-binding 'org-table-wrap-region 105
3958 "\M-\C-m" [(meta return)]))
3959 (org-defkey orgtbl-mode-map [(meta return)]
3960 (orgtbl-make-binding 'org-table-wrap-region 106
3961 [(meta return)] "\M-\C-m"))
3963 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
3964 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
3966 (when orgtbl-optimized
3967 ;; If the user wants maximum table support, we need to hijack
3968 ;; some standard editing functions
3969 (org-remap orgtbl-mode-map
3970 'self-insert-command 'orgtbl-self-insert-command
3971 'delete-char 'org-delete-char
3972 'delete-backward-char 'org-delete-backward-char)
3973 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
3974 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
3976 ["Create or convert" org-table-create-or-convert-from-region
3977 :active (not (org-at-table-p)) :keys "C-c |" ]
3979 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
3980 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
3981 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
3982 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
3984 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
3985 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
3986 ["Copy Field from Above"
3987 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
3990 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
3991 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
3992 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
3993 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
3995 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
3996 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
3997 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
3998 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
3999 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4001 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4003 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4004 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4005 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4006 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4009 ["Insert table template" orgtbl-insert-radio-table
4010 (assq major-mode orgtbl-radio-table-templates)]
4011 ["Comment/uncomment table" orgtbl-toggle-comment t])
4013 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4014 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4015 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4016 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4017 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4018 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4019 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4020 ["Sum Column/Rectangle" org-table-sum
4021 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4022 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4024 org-table-toggle-formula-debugger :active (org-at-table-p)
4026 :style toggle :selected org-table-formula-debug]
4027 ["Show Col/Row Numbers"
4028 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4030 :style toggle :selected org-table-overlay-coordinates]
4034 (defun orgtbl-ctrl-c-ctrl-c (arg)
4035 "If the cursor is inside a table, realign the table.
4036 If it is a table to be sent away to a receiver, do it.
4037 With prefix arg, also recompute table."
4039 (let ((pos (point)) action consts-str consts cst const-str)
4041 (beginning-of-line 1)
4043 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4044 ((looking-at "[ \t]*|") pos)
4045 ((looking-at "[ \t]*#\\+TBLFM:") 'recalc))))
4049 (org-table-maybe-eval-formula)
4051 (call-interactively 'org-table-recalculate)
4052 (org-table-maybe-recalculate-line))
4053 (call-interactively 'org-table-align)
4054 (when (orgtbl-send-table 'maybe)
4055 (run-hooks 'orgtbl-after-send-table-hook)))
4056 ((eq action 'recalc)
4058 (goto-char (point-min))
4059 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t)
4060 (setq const-str (substring-no-properties (match-string 1)))
4061 (setq consts (append consts (org-split-string const-str "[ \t]+")))
4064 (while (setq e (pop consts))
4065 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4066 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4067 (setq org-table-formula-constants-local cst)))))
4069 (beginning-of-line 1)
4070 (skip-chars-backward " \r\n\t")
4071 (if (org-at-table-p)
4072 (org-call-with-arg 'org-table-recalculate t))))
4073 (t (let (orgtbl-mode)
4074 (call-interactively (key-binding "\C-c\C-c")))))))
4076 (defun orgtbl-create-or-convert-from-region (arg)
4077 "Create table or convert region to table, if no conflicting binding.
4078 This installs the table binding `C-c |', but only if there is no
4079 conflicting binding to this key outside orgtbl-mode."
4081 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4083 (call-interactively cmd)
4084 (call-interactively 'org-table-create-or-convert-from-region))))
4086 (defun orgtbl-tab (arg)
4087 "Justification and field motion for `orgtbl-mode'."
4089 (if arg (org-table-edit-field t)
4090 (org-table-justify-field-maybe)
4091 (org-table-next-field)))
4093 (defun orgtbl-ret ()
4094 "Justification and field motion for `orgtbl-mode'."
4098 (org-table-justify-field-maybe)
4099 (org-table-next-row)))
4101 (defun orgtbl-self-insert-command (N)
4102 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4103 If the cursor is in a table looking at whitespace, the whitespace is
4104 overwritten, and the table is not marked as requiring realignment."
4106 (if (and (org-at-table-p)
4108 (and org-table-auto-blank-field
4109 (member last-command
4110 '(orgtbl-hijacker-command-100
4111 orgtbl-hijacker-command-101
4112 orgtbl-hijacker-command-102
4113 orgtbl-hijacker-command-103
4114 orgtbl-hijacker-command-104
4115 orgtbl-hijacker-command-105
4117 (org-table-blank-field))
4120 (looking-at "[^|\n]* +|"))
4121 (let (org-table-may-need-update)
4122 (goto-char (1- (match-end 0)))
4124 (goto-char (match-beginning 0))
4125 (self-insert-command N))
4126 (setq org-table-may-need-update t)
4129 (cmd (or (key-binding
4130 (or (and (listp function-key-map)
4131 (setq a (assoc last-input-event function-key-map))
4133 (vector last-input-event)))
4134 'self-insert-command)))
4135 (call-interactively cmd)
4136 (if (and org-self-insert-cluster-for-undo
4137 (eq cmd 'self-insert-command))
4138 (if (not (eq last-command 'orgtbl-self-insert-command))
4139 (setq org-self-insert-command-undo-counter 1)
4140 (if (>= org-self-insert-command-undo-counter 20)
4141 (setq org-self-insert-command-undo-counter 1)
4142 (and (> org-self-insert-command-undo-counter 0)
4144 (not (cadr buffer-undo-list)) ; remove nil entry
4145 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4146 (setq org-self-insert-command-undo-counter
4147 (1+ org-self-insert-command-undo-counter))))))))
4149 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4150 "Regular expression matching exponentials as produced by calc.")
4152 (defun orgtbl-export (table target)
4154 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
4155 (lines (org-split-string table "[ \t]*\n[ \t]*"))
4156 org-table-last-alignment org-table-last-column-widths
4158 (if (not (fboundp func))
4159 (error "Cannot export orgtbl table to %s" target))
4160 (setq lines (org-table-clean-before-export lines))
4164 (if (string-match org-table-hline-regexp x)
4166 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4168 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
4170 (loop for i from (1- maxcol) downto 0 do
4171 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
4172 (setq column (delq nil column))
4173 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
4174 (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))
4175 (funcall func table nil)))
4177 (defun orgtbl-gather-send-defs ()
4178 "Gather a plist of :name, :transform, :params for each destination before
4181 (goto-char (org-table-begin))
4183 (beginning-of-line 0)
4184 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4185 (let ((name (org-no-properties (match-string 1)))
4186 (transform (intern (match-string 2)))
4187 (params (if (match-end 3)
4188 (read (concat "(" (match-string 3) ")")))))
4189 (push (list :name name :transform transform :params params)
4191 (beginning-of-line 0)))
4194 (defun orgtbl-send-replace-tbl (name txt)
4195 "Find and replace table NAME with TXT."
4197 (goto-char (point-min))
4198 (unless (re-search-forward
4199 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4200 (error "Don't know where to insert translated table"))
4201 (goto-char (match-beginning 0))
4202 (beginning-of-line 2)
4204 (let ((beg (point)))
4205 (unless (re-search-forward
4206 (concat "END RECEIVE ORGTBL +" name) nil t)
4207 (error "Cannot find end of insertion region"))
4208 (beginning-of-line 1)
4209 (delete-region beg (point))))
4213 (defun org-table-to-lisp (&optional txt)
4214 "Convert the table at point to a Lisp structure.
4215 The structure will be a list. Each item is either the symbol `hline'
4216 for a horizontal separator line, or a list of field values as strings.
4217 The table is taken from the parameter TXT, or from the buffer at point."
4219 (unless (org-at-table-p)
4220 (error "No table at point")))
4222 (buffer-substring-no-properties (org-table-begin)
4224 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4228 (if (string-match org-table-hline-regexp x)
4230 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4233 (defun orgtbl-send-table (&optional maybe)
4234 "Send a transformed version of this table to the receiver position.
4235 With argument MAYBE, fail quietly if no transformation is defined for
4239 (unless (org-at-table-p) (error "Not at a table"))
4240 ;; when non-interactive, we assume align has just happened.
4241 (when (org-called-interactively-p 'any) (org-table-align))
4242 (let ((dests (orgtbl-gather-send-defs))
4243 (txt (buffer-substring-no-properties (org-table-begin)
4246 (unless dests (if maybe (throw 'exit nil)
4247 (error "Don't know how to transform this table")))
4248 (dolist (dest dests)
4249 (let* ((name (plist-get dest :name))
4250 (transform (plist-get dest :transform))
4251 (params (plist-get dest :params))
4252 (skip (plist-get params :skip))
4253 (skipcols (plist-get params :skipcols))
4255 (lines (org-table-clean-before-export
4257 (org-split-string txt "[ \t]*\n[ \t]*"))))
4258 (i0 (if org-table-clean-did-remove-column 2 1))
4261 (if (string-match org-table-hline-regexp x)
4263 (org-remove-by-index
4264 (org-split-string (org-trim x) "\\s-*|\\s-*")
4267 (fun (if (= i0 2) 'cdr 'identity))
4268 (org-table-last-alignment
4269 (org-remove-by-index (funcall fun org-table-last-alignment)
4271 (org-table-last-column-widths
4272 (org-remove-by-index (funcall fun org-table-last-column-widths)
4274 (txt (if (fboundp transform)
4275 (funcall transform table params)
4276 (error "No such transformation function %s" transform))))
4277 (orgtbl-send-replace-tbl name txt))
4278 (setq ntbl (1+ ntbl)))
4279 (message "Table converted and installed at %d receiver location%s"
4280 ntbl (if (> ntbl 1) "s" ""))
4285 (defun org-remove-by-index (list indices &optional i0)
4286 "Remove the elements in LIST with indices in INDICES.
4287 First element has index 0, or I0 if given."
4290 (if (integerp indices) (setq indices (list indices)))
4291 (setq i0 (1- (or i0 0)))
4292 (delq :rm (mapcar (lambda (x)
4294 (if (memq i0 indices) :rm x))
4297 (defun orgtbl-toggle-comment ()
4298 "Comment or uncomment the orgtbl at point."
4300 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4301 (re2 (concat "^" orgtbl-line-start-regexp))
4302 (commented (save-excursion (beginning-of-line 1)
4303 (cond ((looking-at re1) t)
4304 ((looking-at re2) nil)
4305 (t (error "Not at an org table")))))
4306 (re (if commented re1 re2))
4309 (beginning-of-line 1)
4310 (while (looking-at re) (beginning-of-line 0))
4311 (beginning-of-line 2)
4313 (while (looking-at re) (beginning-of-line 2))
4315 (comment-region beg end (if commented '(4) nil))))
4317 (defun orgtbl-insert-radio-table ()
4318 "Insert a radio table template appropriate for this major mode."
4320 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4323 (unless e (error "No radio table setup defined for %s" major-mode))
4324 (setq name (read-string "Table name: "))
4325 (while (string-match "%n" txt)
4326 (setq txt (replace-match name t t txt)))
4327 (or (bolp) (insert "\n"))
4332 ;; Dynamically bound input and output for table formatting.
4333 (defvar *orgtbl-table* nil
4334 "Carries the current table through formatting routines.")
4335 (defvar *orgtbl-rtn* nil
4336 "Formatting routines push the output lines here.")
4337 ;; Formatting parameters for the current table section.
4338 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4339 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4340 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4341 (defvar *orgtbl-fmt* nil "Format for each entry.")
4342 (defvar *orgtbl-efmt* nil "Format for numbers.")
4343 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4344 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4345 (defvar *orgtbl-lstart* nil "Text starting a row.")
4346 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4347 (defvar *orgtbl-lend* nil "Text ending a row.")
4348 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4350 (defsubst orgtbl-get-fmt (fmt i)
4351 "Retrieve the format from FMT corresponding to the Ith column."
4352 (if (and (not (functionp fmt)) (consp fmt))
4356 (defsubst orgtbl-apply-fmt (fmt &rest args)
4357 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4358 (cond ((functionp fmt) (apply fmt args))
4359 (fmt (apply 'format fmt args))
4363 (defsubst orgtbl-eval-str (str)
4364 "If STR is a function, evaluate it with no arguments."
4369 (defun orgtbl-format-line (line)
4370 "Format LINE as a table row."
4371 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4377 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4378 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4379 (orgtbl-apply-fmt efmt (match-string 1 f)
4382 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4383 *orgtbl-default-fmt*)
4386 (push (if *orgtbl-lfmt*
4387 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4388 (concat (orgtbl-eval-str *orgtbl-lstart*)
4389 (mapconcat 'identity line *orgtbl-sep*)
4390 (orgtbl-eval-str *orgtbl-lend*)))
4393 (defun orgtbl-format-section (section-stopper)
4394 "Format lines until the first occurrence of SECTION-STOPPER."
4397 (while (not (eq (car *orgtbl-table*) section-stopper))
4398 (if prevline (orgtbl-format-line prevline))
4399 (setq prevline (pop *orgtbl-table*)))
4400 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4401 (*orgtbl-lend* *orgtbl-llend*)
4402 (*orgtbl-lfmt* *orgtbl-llfmt*))
4403 (orgtbl-format-line prevline))))))
4405 (defun orgtbl-to-generic (table params)
4406 "Convert the orgtbl-mode TABLE to some other format.
4407 This generic routine can be used for many standard cases.
4408 TABLE is a list, each entry either the symbol `hline' for a horizontal
4409 separator line, or a list of fields for that line.
4410 PARAMS is a property list of parameters that can influence the conversion.
4411 For the generic converter, some parameters are obligatory: you need to
4412 specify either :lfmt, or all of (:lstart :lend :sep).
4414 Valid parameters are
4416 :splice When set to t, return only table body lines, don't wrap
4417 them into :tstart and :tend. Default is nil. When :splice
4418 is non-nil, this also means that the exporter should not look
4419 for and interpret header and footer sections.
4421 :hline String to be inserted on horizontal separation lines.
4422 May be nil to ignore hlines.
4424 :sep Separator between two fields
4425 :remove-nil-lines Do not include lines that evaluate to nil.
4428 Each in the following group may be either a string or a function
4429 of no arguments returning a string:
4430 :tstart String to start the table. Ignored when :splice is t.
4431 :tend String to end the table. Ignored when :splice is t.
4432 :lstart String to start a new table line.
4433 :llstart String to start the last table line, defaults to :lstart.
4434 :lend String to end a table line
4435 :llend String to end the last table line, defaults to :lend.
4437 Each in the following group may be a string, a function of one
4438 argument (the field or line) returning a string, or a plist
4439 mapping columns to either of the above:
4440 :lfmt Format for entire line, with enough %s to capture all fields.
4441 If this is present, :lstart, :lend, and :sep are ignored.
4442 :llfmt Format for the entire last line, defaults to :lfmt.
4443 :fmt A format to be used to wrap the field, should contain
4444 %s for the original field value. For example, to wrap
4445 everything in dollars, you could use :fmt \"$%s$\".
4446 This may also be a property list with column numbers and
4447 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4449 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4450 Same as above, specific for the header lines in the table.
4451 All lines before the first hline are treated as header.
4452 If any of these is not present, the data line value is used.
4454 This may be either a string or a function of two arguments:
4455 :efmt Use this format to print numbers with exponentials.
4456 The format should have %s twice for inserting mantissa
4457 and exponent, for example \"%s\\\\times10^{%s}\". This
4458 may also be a property list with column numbers and
4459 formats. :fmt will still be applied after :efmt.
4461 In addition to this, the parameters :skip and :skipcols are always handled
4462 directly by `orgtbl-send-table'. See manual."
4465 (let* ((splicep (plist-get params :splice))
4466 (hline (plist-get params :hline))
4467 (remove-nil-linesp (plist-get params :remove-nil-lines))
4468 (remove-newlines (plist-get params :remove-newlines))
4469 (*orgtbl-hline* hline)
4470 (*orgtbl-table* table)
4471 (*orgtbl-sep* (plist-get params :sep))
4472 (*orgtbl-efmt* (plist-get params :efmt))
4473 (*orgtbl-lstart* (plist-get params :lstart))
4474 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4475 (*orgtbl-lend* (plist-get params :lend))
4476 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4477 (*orgtbl-lfmt* (plist-get params :lfmt))
4478 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4479 (*orgtbl-fmt* (plist-get params :fmt))
4484 (when (plist-member params :tstart)
4485 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4486 (if tstart (push tstart *orgtbl-rtn*)))))
4488 ;; Do we have a heading section? If so, format it and handle the
4490 (if (and (not splicep)
4491 (or (consp (car *orgtbl-table*))
4492 (consp (nth 1 *orgtbl-table*)))
4493 (memq 'hline (cdr *orgtbl-table*)))
4495 (when (eq 'hline (car *orgtbl-table*))
4496 ;; there is a hline before the first data line
4497 (and hline (push hline *orgtbl-rtn*))
4498 (pop *orgtbl-table*))
4499 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4501 (*orgtbl-llstart* (or (plist-get params :hllstart)
4503 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4504 (*orgtbl-llend* (or (plist-get params :hllend)
4505 (plist-get params :hlend) *orgtbl-llend*))
4506 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4507 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4508 (plist-get params :hlfmt) *orgtbl-llfmt*))
4509 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4510 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4511 (orgtbl-format-section 'hline))
4512 (if hline (push hline *orgtbl-rtn*))
4513 (pop *orgtbl-table*)))
4515 ;; Now format the main section.
4516 (orgtbl-format-section nil)
4519 (when (plist-member params :tend)
4520 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4521 (if tend (push tend *orgtbl-rtn*)))))
4523 (mapconcat (if remove-newlines
4525 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4527 (nreverse (if remove-nil-linesp
4528 (remq nil *orgtbl-rtn*)
4529 *orgtbl-rtn*)) "\n")))
4531 (defun orgtbl-to-tsv (table params)
4532 "Convert the orgtbl-mode table to TAB separated material."
4533 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4534 (defun orgtbl-to-csv (table params)
4535 "Convert the orgtbl-mode table to CSV material.
4536 This does take care of the proper quoting of fields with comma or quotes."
4537 (orgtbl-to-generic table (org-combine-plists
4538 '(:sep "," :fmt org-quote-csv-field)
4541 (defun orgtbl-to-latex (table params)
4542 "Convert the orgtbl-mode TABLE to LaTeX.
4543 TABLE is a list, each entry either the symbol `hline' for a horizontal
4544 separator line, or a list of fields for that line.
4545 PARAMS is a property list of parameters that can influence the conversion.
4546 Supports all parameters from `orgtbl-to-generic'. Most important for
4549 :splice When set to t, return only table body lines, don't wrap
4550 them into a tabular environment. Default is nil.
4552 :fmt A format to be used to wrap the field, should contain %s for the
4553 original field value. For example, to wrap everything in dollars,
4554 use :fmt \"$%s$\". This may also be a property list with column
4555 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4556 The format may also be a function that formats its one argument.
4558 :efmt Format for transforming numbers with exponentials. The format
4559 should have %s twice for inserting mantissa and exponent, for
4560 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4561 This may also be a property list with column numbers and formats.
4562 The format may also be a function that formats its two arguments.
4564 :llend If you find too much space below the last line of a table,
4565 pass a value of \"\" for :llend to suppress the final \\\\.
4567 The general parameters :skip and :skipcols have already been applied when
4568 this function is called."
4569 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4570 org-table-last-alignment ""))
4573 :tstart (concat "\\begin{tabular}{" alignment "}")
4574 :tend "\\end{tabular}"
4575 :lstart "" :lend " \\\\" :sep " & "
4576 :efmt "%s\\,(%s)" :hline "\\hline")))
4577 (orgtbl-to-generic table (org-combine-plists params2 params))))
4579 (defun orgtbl-to-html (table params)
4580 "Convert the orgtbl-mode TABLE to HTML.
4581 TABLE is a list, each entry either the symbol `hline' for a horizontal
4582 separator line, or a list of fields for that line.
4583 PARAMS is a property list of parameters that can influence the conversion.
4584 Currently this function recognizes the following parameters:
4586 :splice When set to t, return only table body lines, don't wrap
4587 them into a <table> environment. Default is nil.
4589 The general parameters :skip and :skipcols have already been applied when
4590 this function is called. The function does *not* use `orgtbl-to-generic',
4591 so you cannot specify parameters for it."
4592 (let* ((splicep (plist-get params :splice))
4593 (html-table-tag org-export-html-table-tag)
4595 ;; Just call the formatter we already have
4596 ;; We need to make text lines for it, so put the fields back together.
4597 (setq html (org-format-org-table-html
4602 (concat "| " (mapconcat 'org-html-expand x " | ") " |")))
4605 (if (string-match "\n+\\'" html)
4606 (setq html (replace-match "" t t html)))
4609 (defun orgtbl-to-texinfo (table params)
4610 "Convert the orgtbl-mode TABLE to TeXInfo.
4611 TABLE is a list, each entry either the symbol `hline' for a horizontal
4612 separator line, or a list of fields for that line.
4613 PARAMS is a property list of parameters that can influence the conversion.
4614 Supports all parameters from `orgtbl-to-generic'. Most important for
4617 :splice nil/t When set to t, return only table body lines, don't wrap
4618 them into a multitable environment. Default is nil.
4620 :fmt fmt A format to be used to wrap the field, should contain
4621 %s for the original field value. For example, to wrap
4622 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4623 This may also be a property list with column numbers and
4624 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4625 Each format also may be a function that formats its one
4628 :cf \"f1 f2..\" The column fractions for the table. By default these
4629 are computed automatically from the width of the columns
4632 The general parameters :skip and :skipcols have already been applied when
4633 this function is called."
4634 (let* ((total (float (apply '+ org-table-last-column-widths)))
4635 (colfrac (or (plist-get params :cf)
4637 (lambda (x) (format "%.3f" (/ (float x) total)))
4638 org-table-last-column-widths " ")))
4641 :tstart (concat "@multitable @columnfractions " colfrac)
4642 :tend "@end multitable"
4643 :lstart "@item " :lend "" :sep " @tab "
4644 :hlstart "@headitem ")))
4645 (orgtbl-to-generic table (org-combine-plists params2 params))))
4647 (defun orgtbl-to-orgtbl (table params)
4648 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4649 Useful when slicing one table into many. The :hline, :sep,
4650 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4651 and :tend suppress strings without splicing; they can be set to
4652 provide ORGTBL directives for the generated table."
4656 :tstart nil :tend nil
4661 (params (org-combine-plists params2 params)))
4662 (orgtbl-to-generic table params)))
4664 (defun org-table-get-remote-range (name-or-id form)
4665 "Get a field value or a list of values in a range from table at ID.
4667 NAME-OR-ID may be the name of a table in the current file as set by
4668 a \"#+TBLNAME:\" directive. The first table following this line
4669 will then be used. Alternatively, it may be an ID referring to
4670 any entry, also in a different file. In this case, the first table
4671 in that entry will be referenced.
4672 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
4673 \"@I$2..@II$2\". All the references must be absolute, not relative.
4675 The return value is either a single string for a single field, or a
4676 list of the fields in the rectangle ."
4679 org-table-column-names org-table-column-name-regexp
4680 org-table-local-parameters org-table-named-field-locations
4681 org-table-current-line-types org-table-current-begin-line
4682 org-table-current-begin-pos org-table-dlines
4683 org-table-current-ncol
4684 org-table-hlines org-table-last-alignment
4685 org-table-last-column-widths org-table-last-alignment
4686 org-table-last-column-widths tbeg
4688 (setq form (org-table-convert-refs-to-rc form))
4693 (goto-char (point-min))
4694 (if (re-search-forward
4695 (concat "^[ \t]*#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4697 (setq buffer (current-buffer) loc (match-beginning 0))
4698 (setq id-loc (org-id-find name-or-id 'marker))
4699 (unless (and id-loc (markerp id-loc))
4700 (error "Can't find remote table \"%s\"" name-or-id))
4701 (setq buffer (marker-buffer id-loc)
4702 loc (marker-position id-loc))
4703 (move-marker id-loc nil)))
4704 (with-current-buffer buffer
4710 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4711 (not (match-beginning 1)))
4712 (error "Cannot find a table at NAME or ID %s" name-or-id))
4713 (setq tbeg (point-at-bol))
4714 (org-table-get-specials)
4715 (setq form (org-table-formula-substitute-names form))
4716 (if (and (string-match org-table-range-regexp form)
4717 (> (length (match-string 0 form)) 1))
4719 (org-table-get-range (match-string 0 form) tbeg 1))
4722 (provide 'org-table)
4724 ;; arch-tag: 4d21cfdd-0268-440a-84b0-09237a0fe0ef
4726 ;;; org-table.el ends here