1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004-2014 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;; This file contains the table editor and spreadsheet for Org-mode.
29 ;; Watch out: Here we are talking about two different kind of tables.
30 ;; Most of the code is for the tables created with the Org-mode table editor.
31 ;; Sometimes, we talk about tables created and edited with the table.el
32 ;; Emacs package. We call the former org-type tables, and the latter
33 ;; table.el-type tables.
41 (declare-function org-export-string-as
"ox"
42 (string backend
&optional body-only ext-plist
))
43 (declare-function org-export-create-backend
"ox")
44 (declare-function org-export-get-backend
"ox" (name))
46 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
48 (defvar orgtbl-mode
) ; defined below
49 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
50 (defvar constants-unit-system
)
51 (defvar org-table-follow-field-mode
)
53 (defvar orgtbl-after-send-table-hook nil
54 "Hook for functions attaching to `C-c C-c', if the table is sent.
55 This can be used to add additional functionality after the table is sent
56 to the receiver position, otherwise, if table is not sent, the functions
59 (defvar org-table-TBLFM-begin-regexp
"|\n[ \t]*#\\+TBLFM: ")
61 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
62 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
63 In the optimized version, the table editor takes over all simple keys that
64 normally just insert a character. In tables, the characters are inserted
65 in a way to minimize disturbing the table structure (i.e. in overwrite mode
66 for empty fields). Outside tables, the correct binding of the keys is
69 The default for this option is t if the optimized version is also used in
70 Org-mode. See the variable `org-enable-table-editor' for details. Changing
71 this variable requires a restart of Emacs to become effective."
75 (defcustom orgtbl-radio-table-templates
76 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
77 % END RECEIVE ORGTBL %n
79 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
82 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
83 @c END RECEIVE ORGTBL %n
85 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
88 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
89 <!-- END RECEIVE ORGTBL %n -->
91 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
94 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
95 #+ END RECEIVE ORGTBL %n
97 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
100 "Templates for radio tables in different major modes.
101 Each template must define lines that will be treated as a comment and that
102 must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
103 lines where \"%n\" will be replaced with the name of the table during
104 insertion of the template. The transformed table will later be inserted
107 The template should also contain a minimal table in a multiline comment.
108 If multiline comments are not possible in the buffer language,
109 you can pack it into a string that will not be used when the code
110 is compiled or executed. Above the table will you need a line with
111 the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
112 convert the table into a data structure useful in the
113 language of the buffer. Check the manual for the section on
114 \"Translator functions\", and more generally check out
115 http://orgmode.org/manual/Tables-in-arbitrary-syntax.html#Tables-in-arbitrary-syntax
117 All occurrences of %n in a template will be replaced with the name of the
118 table, obtained by prompting the user."
121 (list (symbol :tag
"Major mode")
122 (string :tag
"Format"))))
124 (defgroup org-table-settings nil
125 "Settings for tables in Org-mode."
126 :tag
"Org Table Settings"
129 (defcustom org-table-default-size
"5x2"
130 "The default size for newly created tables, Columns x Rows."
131 :group
'org-table-settings
134 (defcustom org-table-number-regexp
135 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
136 "Regular expression for recognizing numbers in table columns.
137 If a table column contains mostly numbers, it will be aligned to the
138 right. If not, it will be aligned to the left.
140 The default value of this option is a regular expression which allows
141 anything which looks remotely like a number as used in scientific
142 context. For example, all of the following will be considered a
144 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
146 Other options offered by the customize interface are more restrictive."
147 :group
'org-table-settings
149 (const :tag
"Positive Integers"
151 (const :tag
"Integers"
153 (const :tag
"Floating Point Numbers"
154 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
155 (const :tag
"Floating Point Number or Integer"
156 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
157 (const :tag
"Exponential, Floating point, Integer"
158 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
159 (const :tag
"Very General Number-Like, including hex and Calc radix"
160 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
161 (const :tag
"Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
162 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
163 (string :tag
"Regexp:")))
165 (defcustom org-table-number-fraction
0.5
166 "Fraction of numbers in a column required to make the column align right.
167 In a column all non-white fields are considered. If at least
168 this fraction of fields is matched by `org-table-number-regexp',
169 alignment to the right border applies."
170 :group
'org-table-settings
173 (defgroup org-table-editing nil
174 "Behavior of tables during editing in Org-mode."
175 :tag
"Org Table Editing"
178 (defcustom org-table-automatic-realign t
179 "Non-nil means automatically re-align table when pressing TAB or RETURN.
180 When nil, aligning is only done with \\[org-table-align], or after column
182 :group
'org-table-editing
185 (defcustom org-table-auto-blank-field t
186 "Non-nil means automatically blank table field when starting to type into it.
187 This only happens when typing immediately after a field motion
188 command (TAB, S-TAB or RET).
189 Only relevant when `org-enable-table-editor' is equal to `optimized'."
190 :group
'org-table-editing
193 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
194 "Non-nil means automatically exit the follow mode.
195 When nil, the follow mode will stay on and be active in any table
196 the cursor enters. Since the table follow filed mode messes with the
197 window configuration, it is not recommended to set this variable to nil,
198 except maybe locally in a special file that has mostly tables with long
204 (defcustom org-table-fix-formulas-confirm nil
205 "Whether the user should confirm when Org fixes formulas."
206 :group
'org-table-editing
209 (const :tag
"with yes-or-no" yes-or-no-p
)
210 (const :tag
"with y-or-n" y-or-n-p
)
211 (const :tag
"no confirmation" nil
)))
212 (put 'org-table-fix-formulas-confirm
214 #'(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
216 (defcustom org-table-tab-jumps-over-hlines t
217 "Non-nil means tab in the last column of a table with jump over a hline.
218 If a horizontal separator line is following the current line,
219 `org-table-next-field' can either create a new row before that line, or jump
220 over the line. When this option is nil, a new line will be created before
222 :group
'org-table-editing
225 (defgroup org-table-calculation nil
226 "Options concerning tables in Org-mode."
227 :tag
"Org Table Calculation"
230 (defcustom org-table-use-standard-references
'from
231 "Should org-mode work with table references like B3 instead of @3$2?
234 from accept as input, do not present for editing
235 t accept as input and present for editing"
236 :group
'org-table-calculation
238 (const :tag
"Never, don't even check user input for them" nil
)
239 (const :tag
"Always, both as user input, and when editing" t
)
240 (const :tag
"Convert user input, don't offer during editing" from
)))
242 (defcustom org-table-copy-increment t
243 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
244 :group
'org-table-calculation
246 :package-version
'(Org .
"8.3")
248 (const :tag
"Use the difference between the current and the above fields" t
)
249 (integer :tag
"Use a number" 1)
250 (const :tag
"Don't increment the value when copying a field" nil
)))
252 (defcustom org-calc-default-modes
253 '(calc-internal-prec 12
254 calc-float-format
(float 8)
257 calc-symbolic-mode nil
258 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
259 calc-display-working-message t
261 "List with Calc mode settings for use in `calc-eval' for table formulas.
262 The list must contain alternating symbols (Calc modes variables and values).
263 Don't remove any of the default settings, just change the values. Org-mode
264 relies on the variables to be present in the list."
265 :group
'org-table-calculation
268 (defcustom org-table-duration-custom-format
'hours
269 "Format for the output of calc computations like $1+$2;t.
270 The default value is 'hours, and will output the results as a
271 number of hours. Other allowed values are 'seconds, 'minutes and
272 'days, and the output will be a fraction of seconds, minutes or
274 :group
'org-table-calculation
276 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
277 (symbol :tag
"Minutes" 'minutes
)
278 (symbol :tag
"Hours " 'hours
)
279 (symbol :tag
"Days " 'days
)))
281 (defcustom org-table-formula-field-format
"%s"
282 "Format for fields which contain the result of a formula.
283 For example, using \"~%s~\" will display the result within tilde
284 characters. Beware that modifying the display can prevent the
285 field from being used in another formula."
286 :group
'org-table-settings
290 (defcustom org-table-formula-evaluate-inline t
291 "Non-nil means TAB and RET evaluate a formula in current table field.
292 If the current field starts with an equal sign, it is assumed to be a formula
293 which should be evaluated as described in the manual and in the documentation
294 string of the command `org-table-eval-formula'. This feature requires the
296 When this variable is nil, formula calculation is only available through
297 the command \\[org-table-eval-formula]."
298 :group
'org-table-calculation
301 (defcustom org-table-formula-use-constants t
302 "Non-nil means interpret constants in formulas in tables.
303 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
304 by the value given in `org-table-formula-constants', or by a value obtained
305 from the `constants.el' package."
306 :group
'org-table-calculation
309 (defcustom org-table-formula-constants nil
310 "Alist with constant names and values, for use in table formulas.
311 The car of each element is a name of a constant, without the `$' before it.
312 The cdr is the value as a string. For example, if you'd like to use the
313 speed of light in a formula, you would configure
315 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
317 and then use it in an equation like `$1*$c'.
319 Constants can also be defined on a per-file basis using a line like
321 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
322 :group
'org-table-calculation
324 (cons (string :tag
"name")
325 (string :tag
"value"))))
327 (defcustom org-table-allow-automatic-line-recalculation t
328 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
329 Automatically means when TAB or RET or C-c C-c are pressed in the line."
330 :group
'org-table-calculation
333 (defcustom org-table-error-on-row-ref-crossing-hline t
334 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
338 (defcustom org-table-relative-ref-may-cross-hline t
339 "Non-nil means relative formula references may cross hlines.
340 Here are the allowed values:
342 nil Relative references may not cross hlines. They will reference the
343 field next to the hline instead. Coming from below, the reference
344 will be to the field below the hline. Coming from above, it will be
346 t Relative references may cross hlines.
347 error An attempt to cross a hline will throw an error.
349 It is probably good to never set this variable to nil, for the sake of
350 portability of tables."
351 :group
'org-table-calculation
353 (const :tag
"Allow to cross" t
)
354 (const :tag
"Stick to hline" nil
)
355 (const :tag
"Error on attempt to cross" error
)))
357 (defcustom org-table-formula-create-columns nil
358 "Non-nil means that evaluation of a field formula can add new
359 columns if an out-of-bounds field is being set."
360 :group
'org-table-calculation
362 :package-version
'(Org .
"8.3")
364 (const :tag
"Setting an out-of-bounds field generates an error (default)" nil
)
365 (const :tag
"Setting an out-of-bounds field silently adds columns as needed" t
)
366 (const :tag
"Setting an out-of-bounds field adds columns as needed, but issues a warning message" warn
)
367 (const :tag
"When setting an out-of-bounds field, the user is prompted" prompt
)))
369 (defgroup org-table-import-export nil
370 "Options concerning table import and export in Org-mode."
371 :tag
"Org Table Import Export"
374 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
375 "Default export parameters for `org-table-export'.
376 These can be overridden for a specific table by setting the
377 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
378 radio tables for the different export transformations and
379 available parameters."
380 :group
'org-table-import-export
383 (defcustom org-table-convert-region-max-lines
999
384 "Max lines that `org-table-convert-region' will attempt to process.
386 The function can be slow on larger regions; this safety feature
387 prevents it from hanging emacs."
388 :group
'org-table-import-export
391 :package-version
'(Org .
"8.3"))
393 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
394 "Detects a table line marked for automatic recalculation.")
395 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
396 "Detects a table line marked for automatic recalculation.")
397 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
398 "Detects a table line marked for automatic recalculation.")
399 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
400 "Searching from within a table (any type) this finds the first line outside the table.")
401 (defvar org-table-last-highlighted-reference nil
)
402 (defvar org-table-formula-history nil
)
404 (defvar org-table-column-names nil
405 "Alist with column names, derived from the `!' line.")
406 (defvar org-table-column-name-regexp nil
407 "Regular expression matching the current column names.")
408 (defvar org-table-local-parameters nil
409 "Alist with parameter names, derived from the `$' line.")
410 (defvar org-table-named-field-locations nil
411 "Alist with locations of named fields.")
413 (defvar org-table-current-line-types nil
414 "Table row types, non-nil only for the duration of a command.")
415 (defvar org-table-current-begin-line nil
416 "Table begin line, non-nil only for the duration of a command.")
417 (defvar org-table-current-begin-pos nil
418 "Table begin position, non-nil only for the duration of a command.")
419 (defvar org-table-current-ncol nil
420 "Number of columns in table, non-nil only for the duration of a command.")
421 (defvar org-table-dlines nil
422 "Vector of data line line numbers in the current table.")
423 (defvar org-table-hlines nil
424 "Vector of hline line numbers in the current table.")
426 (defconst org-table-range-regexp
427 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
429 "Regular expression for matching ranges in formulas.")
431 (defconst org-table-range-regexp2
433 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
435 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
436 "Match a range for reference display.")
438 (defun org-table-colgroup-line-p (line)
439 "Is this a table line colgroup information?"
441 (and (string-match "[<>]\\|&[lg]t;" line
)
442 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
448 (not (member s
'("" "<" ">" "<>" "<" ">" "<>"))))
449 (org-split-string (match-string 1 line
) "[ \t]*|[ \t]*")))))))
451 (defun org-table-cookie-line-p (line)
452 "Is this a table line with only alignment/width cookies?"
454 (and (string-match "[<>]\\|&[lg]t;" line
)
456 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line
)
457 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line
))
458 (not (delq nil
(mapcar
460 (not (or (equal s
"")
462 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s
)
464 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'"
466 (org-split-string (match-string 1 line
)
467 "[ \t]*|[ \t]*")))))))
469 (defconst org-table-translate-regexp
470 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
471 "Match a reference that needs translation, for reference display.")
474 (defun org-table-create-with-table.el
()
475 "Use the table.el package to insert a new table.
476 If there is already a table at point, convert between Org-mode tables
477 and table.el tables."
482 (if (y-or-n-p "Convert table to Org-mode table? ")
483 (org-table-convert)))
485 (when (y-or-n-p "Convert table to table.el table? ")
487 (org-table-convert)))
488 (t (call-interactively 'table-insert
))))
491 (defun org-table-create-or-convert-from-region (arg)
492 "Convert region to table, or create an empty table.
493 If there is an active region, convert it to a table, using the function
494 `org-table-convert-region'. See the documentation of that function
495 to learn how the prefix argument is interpreted to determine the field
497 If there is no such region, create an empty table with `org-table-create'."
499 (if (org-region-active-p)
500 (org-table-convert-region (region-beginning) (region-end) arg
)
501 (org-table-create arg
)))
504 (defun org-table-create (&optional size
)
505 "Query for a size and insert a table skeleton.
506 SIZE is a string Columns x Rows like for example \"3x2\"."
509 (setq size
(read-string
510 (concat "Table size Columns x Rows [e.g. "
511 org-table-default-size
"]: ")
512 "" nil org-table-default-size
)))
515 (indent (make-string (current-column) ?\
))
516 (split (org-split-string size
" *x *"))
517 (rows (string-to-number (nth 1 split
)))
518 (columns (string-to-number (car split
)))
519 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
521 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
522 (point-at-bol) (point)))
523 (beginning-of-line 1)
525 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
526 (dotimes (i rows
) (insert line
))
529 ;; Insert a hline after the first row.
537 (defun org-table-convert-region (beg0 end0
&optional separator
)
538 "Convert region to a table.
539 The region goes from BEG0 to END0, but these borders will be moved
540 slightly, to make sure a beginning of line in the first line is included.
542 SEPARATOR specifies the field separator in the lines. It can have the
545 '(4) Use the comma as a field separator
546 '(16) Use a TAB as field separator
547 '(64) Prompt for a regular expression as field separator
548 integer When a number, use that many spaces as field separator
549 regexp When a regular expression, use it to match the separator
550 nil When nil, the command tries to be smart and figure out the
551 separator in the following way:
552 - when each line contains a TAB, assume TAB-separated material
553 - when each line contains a comma, assume CSV material
554 - else, assume one or more SPACE characters as separator."
556 (let* ((beg (min beg0 end0
))
557 (end (max beg0 end0
))
559 (if (> (count-lines beg end
) org-table-convert-region-max-lines
)
560 (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
561 org-table-convert-region-max-lines
)
562 (if (equal separator
'(64))
563 (setq separator
(read-regexp "Regexp for field separator")))
565 (beginning-of-line 1)
566 (setq beg
(point-marker))
568 (if (bolp) (backward-char 1) (end-of-line 1))
569 (setq end
(point-marker))
570 ;; Get the right field separator
575 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
576 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
579 (if (equal separator
'(4))
580 (while (< (point) end
)
581 ;; parse the csv stuff
583 ((looking-at "^") (insert "| "))
584 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
585 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
586 (replace-match "\\1")
587 (if (looking-at "\"") (insert "\"")))
588 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
589 ((looking-at "[ \t]*,") (replace-match " | "))
590 (t (beginning-of-line 2))))
592 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
593 ((equal separator
'(16)) "^\\|\t")
594 ((integerp separator
)
596 (user-error "Number of spaces in separator must be >= 1")
597 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
599 (format "^ *\\|%s" separator
))
600 (t (error "This should not happen"))))
601 (while (re-search-forward re end t
)
602 (replace-match "| " t t
)))
607 (defun org-table-import (file arg
)
608 "Import FILE as a table.
609 The file is assumed to be tab-separated. Such files can be produced by most
610 spreadsheet and database applications. If no tabs (at least one per line)
611 are found, lines will be split on whitespace into fields."
613 (or (bolp) (newline))
616 (insert-file-contents file
)
617 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
621 (defun org-table-export (&optional file format
)
622 "Export table to a file, with configurable format.
623 Such a file can be imported into usual spreadsheet programs.
625 FILE can be the output file name. If not given, it will be taken
626 from a TABLE_EXPORT_FILE property in the current entry or higher
627 up in the hierarchy, or the user will be prompted for a file
628 name. FORMAT can be an export format, of the same kind as it
629 used when `orgtbl-mode' sends a table in a different format.
631 The command suggests a format depending on TABLE_EXPORT_FORMAT,
632 whether it is set locally or up in the hierarchy, then on the
633 extension of the given file name, and finally on the variable
634 `org-table-export-default-format'."
636 (unless (org-at-table-p) (user-error "No table at point"))
637 (org-table-align) ; Make sure we have everything we need.
638 (let ((file (or file
(org-entry-get (point) "TABLE_EXPORT_FILE" t
))))
640 (setq file
(read-file-name "Export table to: "))
641 (unless (or (not (file-exists-p file
))
642 (y-or-n-p (format "Overwrite file %s? " file
)))
643 (user-error "File not written")))
644 (when (file-directory-p file
)
645 (user-error "This is a directory path, not a file"))
646 (when (and (buffer-file-name (buffer-base-buffer))
649 (file-truename (buffer-file-name (buffer-base-buffer)))))
650 (user-error "Please specify a file name that is different from current"))
651 (let ((fileext (concat (file-name-extension file
) "$"))
652 (format (or format
(org-entry-get (point) "TABLE_EXPORT_FORMAT" t
))))
654 (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
655 "orgtbl-to-html" "orgtbl-to-generic"
656 "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
657 "orgtbl-to-unicode"))
659 (replace-regexp-in-string
661 (replace-regexp-in-string
666 (and (org-string-match-p fileext f
) f
))
668 org-table-export-default-format
)
672 "Format: " formats nil nil deffmt-readable
))))
673 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
674 (let ((transform (intern (match-string 1 format
)))
675 (params (and (match-end 2)
676 (read (concat "(" (match-string 2 format
) ")"))))
677 (table (org-table-to-lisp
678 (buffer-substring-no-properties
679 (org-table-begin) (org-table-end)))))
680 (unless (fboundp transform
)
681 (user-error "No such transformation function %s" transform
))
683 (with-current-buffer (find-file-noselect file
)
684 (setq buf
(current-buffer))
687 (insert (funcall transform table params
) "\n")
690 (message "Export done."))
691 (user-error "TABLE_EXPORT_FORMAT invalid")))))
693 (defvar org-table-aligned-begin-marker
(make-marker)
694 "Marker at the beginning of the table last aligned.
695 Used to check if cursor still is in that table, to minimize realignment.")
696 (defvar org-table-aligned-end-marker
(make-marker)
697 "Marker at the end of the table last aligned.
698 Used to check if cursor still is in that table, to minimize realignment.")
699 (defvar org-table-last-alignment nil
700 "List of flags for flushright alignment, from the last re-alignment.
701 This is being used to correctly align a single field after TAB or RET.")
702 (defvar org-table-last-column-widths nil
703 "List of max width of fields in each column.
704 This is being used to correctly align a single field after TAB or RET.")
705 (defvar org-table-formula-debug nil
706 "Non-nil means debug table formulas.
707 When nil, simply write \"#ERROR\" in corrupted fields.")
708 (make-variable-buffer-local 'org-table-formula-debug
)
709 (defvar org-table-overlay-coordinates nil
710 "Overlay coordinates after each align of a table.")
711 (make-variable-buffer-local 'org-table-overlay-coordinates
)
713 (defvar org-last-recalc-line nil
)
714 (defvar org-table-do-narrow t
) ; for dynamic scoping
715 (defconst org-narrow-column-arrow
"=>"
716 "Used as display property in narrowed table columns.")
719 (defun org-table-align ()
720 "Align the table at point by aligning all vertical bars."
724 (beg (org-table-begin))
725 (end (org-table-end))
726 ;; Current cursor position
727 (linepos (org-current-line))
728 (colpos (org-table-current-column))
729 (winstart (window-start))
730 (winstartline (org-current-line (min winstart
(1- (point-max)))))
731 lines
(new "") lengths l typenums ty fields maxfields i
739 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
741 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
742 emptystrings links dates emph raise narrow
743 falign falign1 fmax f1 f2 len c e space
)
745 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
746 ;; Check if we have links or dates
748 (setq links
(re-search-forward org-bracket-link-regexp end t
))
750 (setq emph
(and org-hide-emphasis-markers
751 (re-search-forward org-emph-re end t
)))
753 (setq raise
(and org-use-sub-superscripts
754 (re-search-forward org-match-substring-regexp end t
)))
756 (setq dates
(and org-display-custom-times
757 (re-search-forward org-ts-regexp-both end t
)))
758 ;; Make sure the link properties are right
759 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
760 ;; Make sure the date properties are right
761 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
762 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
763 (when raise
(goto-char beg
) (while (org-raise-scripts end
)))
765 ;; Check if we are narrowing any columns
767 (setq narrow
(and org-table-do-narrow
768 org-format-transports-properties-p
769 (re-search-forward "<[lrc]?[0-9]+>" end t
)))
771 (setq falign
(re-search-forward "<[lrc][0-9]*>" end t
))
774 (setq lines
(org-split-string
775 (buffer-substring beg end
) "\n"))
776 ;; Store the indentation of the first line
777 (if (string-match "^ *" (car lines
))
778 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
779 ;; Mark the hlines by setting the corresponding element to nil
780 ;; At the same time, we remove trailing space.
781 (setq lines
(mapcar (lambda (l)
782 (if (string-match "^ *|-" l
)
784 (if (string-match "[ \t]+$" l
)
785 (substring l
0 (match-beginning 0))
788 ;; Get the data fields by splitting the lines.
791 (org-split-string l
" *| *"))
792 (delq nil
(copy-sequence lines
))))
793 ;; How many fields in the longest line?
795 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
797 (kill-region beg end
)
798 (org-table-create org-table-default-size
)
799 (user-error "Empty table - created default table")))
800 ;; A list of empty strings to fill any short rows on output
801 (setq emptystrings
(make-list maxfields
""))
802 ;; Check for special formatting.
804 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
805 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
806 ;; Check if there is an explicit width specified
808 (when (or narrow falign
)
809 (setq c column fmax nil falign1 nil
)
812 (when (and (stringp e
) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e
))
813 (if (match-end 1) (setq falign1
(match-string 1 e
)))
814 (if (and org-table-do-narrow
(match-end 2))
815 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
816 ;; Find fields that are wider than fmax, and shorten them
818 (loop for xx in column do
819 (when (and (stringp xx
)
820 (> (org-string-width xx
) fmax
))
821 (org-add-props xx nil
823 (concat "Clipped table field, use C-c ` to edit. Full value is:\n"
824 (org-no-properties (copy-sequence xx
))))
825 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
827 (user-error "Cannot narrow field starting with wide link \"%s\""
828 (match-string 0 xx
)))
829 (setq f2
(length xx
))
830 (if (= (org-string-width xx
)
834 (while (< (org-string-width (substring xx
0 f2
))
837 (add-text-properties f2
(length xx
) (list 'org-cwidth t
) xx
)
838 (add-text-properties (if (>= (string-width (substring xx
(1- f2
) f2
)) 2)
840 (list 'display org-narrow-column-arrow
)
842 ;; Get the maximum width for each column
843 (push (apply 'max
(or fmax
1) 1 (mapcar 'org-string-width column
))
845 ;; Get the fraction of numbers, to decide about alignment of the column
847 (push (equal (downcase falign1
) "r") typenums
)
848 (setq cnt
0 frac
0.0)
849 (loop for x in column do
852 (setq frac
( / (+ (* frac cnt
)
853 (if (string-match org-table-number-regexp x
) 1 0))
854 (setq cnt
(1+ cnt
))))))
855 (push (>= frac org-table-number-fraction
) typenums
)))
856 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
858 ;; Store the alignment of this table, for later editing of single fields
859 (setq org-table-last-alignment typenums
860 org-table-last-column-widths lengths
)
862 ;; With invisible characters, `format' does not get the field width right
863 ;; So we need to make these fields wide by hand.
864 (when (or links emph raise
)
865 (loop for i from
0 upto
(1- maxfields
) do
866 (setq len
(nth i lengths
))
867 (loop for j from
0 upto
(1- (length fields
)) do
868 (setq c
(nthcdr i
(car (nthcdr j fields
))))
869 (if (and (stringp (car c
))
870 (or (text-property-any 0 (length (car c
))
871 'invisible
'org-link
(car c
))
872 (text-property-any 0 (length (car c
))
873 'org-dwidth t
(car c
)))
874 (< (org-string-width (car c
)) len
))
876 (setq space
(make-string (- len
(org-string-width (car c
))) ?\
))
877 (setcar c
(if (nth i typenums
)
878 (concat space
(car c
))
879 (concat (car c
) space
))))))))
881 ;; Compute the formats needed for output of the table
882 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
883 (while (setq l
(pop lengths
))
884 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
885 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
886 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
887 (setq rfmt
(concat rfmt
"\n")
888 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
892 (if l
(apply 'format rfmt
893 (append (pop fields
) emptystrings
))
896 (move-marker org-table-aligned-begin-marker
(point))
898 ;; Replace the old one
899 (delete-region (point) end
)
900 (move-marker end nil
)
901 (move-marker org-table-aligned-end-marker
(point))
902 (when (and orgtbl-mode
(not (derived-mode-p 'org-mode
)))
903 (goto-char org-table-aligned-begin-marker
)
904 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
905 ;; Try to move to the old location
906 (org-goto-line winstartline
)
907 (setq winstart
(point-at-bol))
908 (org-goto-line linepos
)
909 (when (eq (window-buffer (selected-window)) (current-buffer))
910 (set-window-start (selected-window) winstart
'noforce
))
911 (org-table-goto-column colpos
)
912 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
913 (setq org-table-may-need-update nil
)
917 (defun org-table-begin (&optional table-type
)
918 "Find the beginning of the table and return its position.
919 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
921 (if (not (re-search-backward
922 (if table-type org-table-any-border-regexp
923 org-table-border-regexp
)
925 (progn (goto-char (point-min)) (point))
926 (goto-char (match-beginning 0))
927 (beginning-of-line 2)
931 (defun org-table-end (&optional table-type
)
932 "Find the end of the table and return its position.
933 With argument TABLE-TYPE, go to the end of a table.el-type table."
935 (if (not (re-search-forward
936 (if table-type org-table-any-border-regexp
937 org-table-border-regexp
)
939 (goto-char (point-max))
940 (goto-char (match-beginning 0)))
944 (defun org-table-justify-field-maybe (&optional new
)
945 "Justify the current field, text to left, number to right.
946 Optional argument NEW may specify text to replace the current field content."
948 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
949 ((org-at-table-hline-p))
951 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
953 (< (point) org-table-aligned-begin-marker
)
954 (>= (point) org-table-aligned-end-marker
)))
955 ;; This is not the same table, force a full re-align
956 (setq org-table-may-need-update t
))
957 (t ;; realign the current field, based on previous full realign
958 (let* ((pos (point)) s
959 (col (org-table-current-column))
960 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
963 (skip-chars-backward "^|\n")
964 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
966 (setq s
(match-string 1)
970 (buffer-substring-no-properties
971 (match-end 0) (match-beginning 0))) 3))
972 e
(not (= (match-beginning 2) (match-end 2))))
973 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
974 l
(if e
"|" (setq org-table-may-need-update t
) ""))
977 (if (<= (org-string-width new
) l
)
978 (setq n
(format f new
))
979 (setq n
(concat new
"|") org-table-may-need-update t
)))
980 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
982 (let (org-table-may-need-update)
983 (replace-match n t t
))))
984 (setq org-table-may-need-update t
))
988 (defun org-table-next-field ()
989 "Go to the next field in the current table, creating new lines as needed.
990 Before doing so, re-align the table if necessary."
992 (org-table-maybe-eval-formula)
993 (org-table-maybe-recalculate-line)
994 (if (and org-table-automatic-realign
995 org-table-may-need-update
)
997 (let ((end (org-table-end)))
998 (if (org-at-table-hline-p)
1002 (re-search-forward "|" end
)
1003 (if (looking-at "[ \t]*$")
1004 (re-search-forward "|" end
))
1005 (if (and (looking-at "-")
1006 org-table-tab-jumps-over-hlines
1007 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
1008 (goto-char (match-beginning 1)))
1009 (if (looking-at "-")
1011 (beginning-of-line 0)
1012 (org-table-insert-row 'below
))
1013 (if (looking-at " ") (forward-char 1))))
1015 (org-table-insert-row 'below
)))))
1018 (defun org-table-previous-field ()
1019 "Go to the previous field in the table.
1020 Before doing so, re-align the table if necessary."
1022 (org-table-justify-field-maybe)
1023 (org-table-maybe-recalculate-line)
1024 (if (and org-table-automatic-realign
1025 org-table-may-need-update
)
1027 (if (org-at-table-hline-p)
1031 (re-search-backward "|" (org-table-begin))
1032 (re-search-backward "|" (org-table-begin)))
1033 (error (user-error "Cannot move to previous table field")))
1034 (while (looking-at "|\\(-\\|[ \t]*$\\)")
1035 (re-search-backward "|" (org-table-begin)))
1036 (if (looking-at "| ?")
1037 (goto-char (match-end 0))))
1039 (defun org-table-beginning-of-field (&optional n
)
1040 "Move to the end of the current table field.
1041 If already at or after the end, move to the end of the next table field.
1042 With numeric argument N, move N-1 fields forward first."
1044 (let ((pos (point)))
1047 (org-table-previous-field))
1048 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1049 (user-error "No more table fields before the current")
1050 (goto-char (match-end 0))
1051 (and (looking-at " ") (forward-char 1)))
1052 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
1054 (defun org-table-end-of-field (&optional n
)
1055 "Move to the beginning of the current table field.
1056 If already at or before the beginning, move to the beginning of the
1058 With numeric argument N, move N-1 fields backward first."
1060 (let ((pos (point)))
1063 (org-table-next-field))
1064 (when (re-search-forward "|" (point-at-eol 1) t
)
1066 (skip-chars-backward " ")
1067 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
1069 (if (<= (point) pos
) (org-table-end-of-field 2))))
1072 (defun org-table-next-row ()
1073 "Go to the next row (same column) in the current table.
1074 Before doing so, re-align the table if necessary."
1076 (org-table-maybe-eval-formula)
1077 (org-table-maybe-recalculate-line)
1078 (if (or (looking-at "[ \t]*$")
1079 (save-excursion (skip-chars-backward " \t") (bolp)))
1081 (if (and org-table-automatic-realign
1082 org-table-may-need-update
)
1084 (let ((col (org-table-current-column)))
1085 (beginning-of-line 2)
1086 (if (or (not (org-at-table-p))
1087 (org-at-table-hline-p))
1089 (beginning-of-line 0)
1090 (org-table-insert-row 'below
)))
1091 (org-table-goto-column col
)
1092 (skip-chars-backward "^|\n\r")
1093 (if (looking-at " ") (forward-char 1)))))
1096 (defun org-table-copy-down (n)
1097 "Copy the value of the current field one row below.
1099 If the field at the cursor is empty, copy the content of the
1100 nearest non-empty field above. With argument N, use the Nth
1103 If the current field is not empty, it is copied down to the next
1104 row, and the cursor is moved with it. Therefore, repeating this
1105 command causes the column to be filled row-by-row.
1107 If the variable `org-table-copy-increment' is non-nil and the
1108 field is an integer or a timestamp, it will be incremented while
1109 copying. By default, increment by the difference between the
1110 value in the current field and the one in the field above. To
1111 increment using a fixed integer, set `org-table-copy-increment'
1112 to a number. In the case of a timestamp, increment by days."
1114 (let* ((colpos (org-table-current-column))
1115 (col (current-column))
1116 (field (save-excursion (org-table-get-field)))
1117 (field-up (or (save-excursion
1118 (org-table-get (1- (org-table-current-line))
1119 (org-table-current-column))) ""))
1120 (non-empty (string-match "[^ \t]" field
))
1121 (non-empty-up (string-match "[^ \t]" field-up
))
1122 (beg (org-table-begin))
1125 (org-table-check-inside-data-field)
1130 (while (progn (beginning-of-line 1)
1131 (re-search-backward org-table-dataline-regexp
1133 (org-table-goto-column colpos t
)
1134 (if (and (looking-at
1135 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1136 (<= (setq n
(1- n
)) 0))
1137 (throw 'exit
(match-string 1))))))
1140 (while (progn (beginning-of-line 1)
1141 (re-search-backward org-table-dataline-regexp
1143 (org-table-goto-column colpos t
)
1144 (if (and (looking-at
1145 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1146 (<= (setq n
(1- n
)) 0))
1147 (throw 'exit
(match-string 1))))))
1148 (setq non-empty-up
(and field-up
(string-match "[^ \t]" field-up
))))
1149 ;; Above field was not empty, go down to the next row
1150 (setq txt
(org-trim field
))
1151 (org-table-next-row)
1152 (org-table-blank-field))
1153 (if non-empty-up
(setq txt-up
(org-trim field-up
)))
1155 ((numberp org-table-copy-increment
) org-table-copy-increment
)
1156 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up
)
1157 (string-match org-ts-regexp3 txt
))
1158 (- (org-time-string-to-absolute txt
)
1159 (org-time-string-to-absolute txt-up
)))
1160 ((string-match org-ts-regexp3 txt
) 1)
1161 ((string-match "^[0-9]+\\(\.[0-9]+\\)?" txt-up
)
1162 (- (string-to-number txt
)
1163 (string-to-number (match-string 0 txt-up
))))
1167 (user-error "No non-empty field found")
1168 (if (and org-table-copy-increment
1169 (not (equal orig-n
0))
1170 (string-match "^[-+^/*0-9eE.]+$" txt
)
1171 (< (string-to-number txt
) 100000000))
1172 (setq txt
(calc-eval (concat txt
"+" (number-to-string inc
)))))
1174 (org-move-to-column col
)
1175 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1176 (org-timestamp-up-day inc
)
1177 (org-table-maybe-recalculate-line))
1179 (org-move-to-column col
))))
1181 (defun org-table-check-inside-data-field (&optional noerror
)
1182 "Is point inside a table data field?
1183 I.e. not on a hline or before the first or after the last column?
1184 This actually throws an error, so it aborts the current command."
1185 (if (or (not (org-at-table-p))
1186 (= (org-table-current-column) 0)
1187 (org-at-table-hline-p)
1188 (looking-at "[ \t]*$"))
1191 (user-error "Not in table data field"))
1194 (defvar org-table-clip nil
1195 "Clipboard for table regions.")
1197 (defun org-table-get (line column
)
1198 "Get the field in table line LINE, column COLUMN.
1199 If LINE is larger than the number of data lines in the table, the function
1200 returns nil. However, if COLUMN is too large, we will simply return an
1202 If LINE is nil, use the current line.
1203 If COLUMN is nil, use the current column."
1204 (setq column
(or column
(org-table-current-column)))
1206 (and (or (not line
) (org-table-goto-line line
))
1207 (org-trim (org-table-get-field column
)))))
1209 (defun org-table-put (line column value
&optional align
)
1210 "Put VALUE into line LINE, column COLUMN.
1211 When ALIGN is set, also realign the table."
1212 (setq column
(or column
(org-table-current-column)))
1213 (prog1 (save-excursion
1214 (and (or (not line
) (org-table-goto-line line
))
1215 (progn (org-table-goto-column column nil
'force
) t
)
1216 (org-table-get-field column value
)))
1217 (and align
(org-table-align))))
1219 (defun org-table-current-line ()
1220 "Return the index of the current data line."
1221 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1223 (goto-char (org-table-begin))
1224 (while (and (re-search-forward org-table-dataline-regexp end t
)
1226 (< (point-at-eol) pos
))))
1229 (defun org-table-goto-line (N)
1230 "Go to the Nth data line in the current table.
1231 Return t when the line exists, nil if it does not exist."
1232 (goto-char (org-table-begin))
1233 (let ((end (org-table-end)) (cnt 0))
1234 (while (and (re-search-forward org-table-dataline-regexp end t
)
1235 (< (setq cnt
(1+ cnt
)) N
)))
1239 (defun org-table-blank-field ()
1240 "Blank the current table field or active region."
1242 (org-table-check-inside-data-field)
1243 (if (and (org-called-interactively-p 'any
) (org-region-active-p))
1244 (let (org-table-clip)
1245 (org-table-cut-region (region-beginning) (region-end)))
1246 (skip-chars-backward "^|")
1248 (if (looking-at "|[^|\n]+")
1249 (let* ((pos (match-beginning 0))
1250 (match (match-string 0))
1251 (len (org-string-width match
)))
1252 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1253 (goto-char (+ 2 pos
))
1254 (substring match
1)))))
1256 (defun org-table-get-field (&optional n replace
)
1257 "Return the value of the field in column N of current row.
1258 N defaults to current field.
1259 If REPLACE is a string, replace field with this value. The return value
1260 is always the old value."
1261 (and n
(org-table-goto-column n
))
1262 (skip-chars-backward "^|\n")
1264 (if (looking-at "|[^|\r\n]*")
1265 (let* ((pos (match-beginning 0))
1266 (val (buffer-substring (1+ pos
) (match-end 0))))
1268 (replace-match (concat "|" (if (equal replace
"") " " replace
))
1270 (goto-char (min (point-at-eol) (+ 2 pos
)))
1272 (forward-char 1) ""))
1275 (defun org-table-field-info (arg)
1276 "Show info about the current field, and highlight any reference at point."
1278 (unless (org-at-table-p) (user-error "Not at a table"))
1279 (org-table-get-specials)
1281 (let* ((pos (point))
1282 (col (org-table-current-column))
1283 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1284 (name (car (rassoc (list (org-current-line) col
)
1285 org-table-named-field-locations
)))
1286 (eql (org-table-expand-lhs-ranges
1289 (cons (org-table-formula-handle-first/last-rc
1291 (org-table-get-stored-formulas))))
1292 (dline (org-table-current-dline))
1293 (ref (format "@%d$%d" dline col
))
1294 (ref1 (org-table-convert-refs-to-an ref
))
1295 (fequation (or (assoc name eql
) (assoc ref eql
)))
1296 (cequation (assoc (int-to-string col
) eql
))
1297 (eqn (or fequation cequation
)))
1298 (if (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))
1299 (setq eqn
(get-text-property 0 :orig-eqn
(car eqn
))))
1302 (org-table-show-reference 'local
)
1304 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1306 (if cname
(concat " or $" cname
) "")
1308 (if name
(concat " or $" name
) "")
1309 ;; FIXME: formula info not correct if special table line
1311 (concat ", formula: "
1312 (org-table-formula-to-user
1314 (if (string-match "^[$@]"(car eqn
)) "" "$")
1315 (car eqn
) "=" (cdr eqn
))))
1318 (defun org-table-current-column ()
1319 "Find out which column we are in."
1321 (if (org-called-interactively-p 'any
) (org-table-check-inside-data-field))
1323 (let ((cnt 0) (pos (point)))
1324 (beginning-of-line 1)
1325 (while (search-forward "|" pos t
)
1326 (setq cnt
(1+ cnt
)))
1327 (when (org-called-interactively-p 'interactive
)
1328 (message "In table column %d" cnt
))
1332 (defun org-table-current-dline ()
1333 "Find out what table data line we are in.
1334 Only data lines count for this."
1336 (when (org-called-interactively-p 'any
)
1337 (org-table-check-inside-data-field))
1339 (let ((cnt 0) (pos (point)))
1340 (goto-char (org-table-begin))
1341 (while (<= (point) pos
)
1342 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1343 (beginning-of-line 2))
1344 (when (org-called-interactively-p 'any
)
1345 (message "This is table line %d" cnt
))
1349 (defun org-table-goto-column (n &optional on-delim force
)
1350 "Move the cursor to the Nth column in the current table line.
1351 With optional argument ON-DELIM, stop with point before the left delimiter
1353 If there are less than N fields, just go to after the last delimiter.
1354 However, when FORCE is non-nil, create new columns if necessary."
1356 (beginning-of-line 1)
1358 (while (and (> (setq n
(1- n
)) -
1)
1359 (or (search-forward "|" (point-at-eol) t
)
1361 (progn (end-of-line 1)
1362 (skip-chars-backward "^|")
1365 (when (and force
(not (looking-at ".*|")))
1366 (save-excursion (end-of-line 1) (insert " | ")))
1369 (if (looking-at " ") (forward-char 1)))))
1372 (defun org-table-insert-column ()
1373 "Insert a new column into the table."
1375 (if (not (org-at-table-p))
1376 (user-error "Not at a table"))
1377 (org-table-find-dataline)
1378 (let* ((col (max 1 (org-table-current-column)))
1379 (beg (org-table-begin))
1380 (end (org-table-end))
1381 ;; Current cursor position
1382 (linepos (org-current-line))
1385 (while (< (point) end
)
1386 (if (org-at-table-hline-p)
1388 (org-table-goto-column col t
)
1390 (beginning-of-line 2))
1391 (move-marker end nil
)
1392 (org-goto-line linepos
)
1393 (org-table-goto-column colpos
)
1395 (when (or (not org-table-fix-formulas-confirm
)
1396 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1397 (org-table-fix-formulas "$" nil
(1- col
) 1)
1398 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1400 (defun org-table-find-dataline ()
1401 "Find a data line in the current table, which is needed for column commands."
1402 (if (and (org-at-table-p)
1403 (not (org-at-table-hline-p)))
1405 (let ((col (current-column))
1406 (end (org-table-end)))
1407 (org-move-to-column col
)
1408 (while (and (< (point) end
)
1409 (or (not (= (current-column) col
))
1410 (org-at-table-hline-p)))
1411 (beginning-of-line 2)
1412 (org-move-to-column col
))
1413 (if (and (org-at-table-p)
1414 (not (org-at-table-hline-p)))
1417 "Please position cursor in a data line for column operations")))))
1419 (defun org-table-line-to-dline (line &optional above
)
1420 "Turn a buffer line number into a data line number.
1421 If there is no data line in this line, return nil.
1422 If there is no matching dline (most likely te reference was a hline), the
1423 first dline below it is used. When ABOVE is non-nil, the one above is used."
1425 (let ((ll (length org-table-dlines
))
1431 (if (<= (aref org-table-dlines i
) line
)
1436 (if (>= (aref org-table-dlines i
) line
)
1442 (defun org-table-delete-column ()
1443 "Delete a column from the table."
1445 (if (not (org-at-table-p))
1446 (user-error "Not at a table"))
1447 (org-table-find-dataline)
1448 (org-table-check-inside-data-field)
1449 (let* ((col (org-table-current-column))
1450 (beg (org-table-begin))
1451 (end (org-table-end))
1452 ;; Current cursor position
1453 (linepos (org-current-line))
1456 (while (< (point) end
)
1457 (if (org-at-table-hline-p)
1459 (org-table-goto-column col t
)
1460 (and (looking-at "|[^|\n]+|")
1461 (replace-match "|")))
1462 (beginning-of-line 2))
1463 (move-marker end nil
)
1464 (org-goto-line linepos
)
1465 (org-table-goto-column colpos
)
1467 (when (or (not org-table-fix-formulas-confirm
)
1468 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1469 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1471 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1475 (defun org-table-move-column-right ()
1476 "Move column to the right."
1478 (org-table-move-column nil
))
1480 (defun org-table-move-column-left ()
1481 "Move column to the left."
1483 (org-table-move-column 'left
))
1486 (defun org-table-move-column (&optional left
)
1487 "Move the current column to the right. With arg LEFT, move to the left."
1489 (if (not (org-at-table-p))
1490 (user-error "Not at a table"))
1491 (org-table-find-dataline)
1492 (org-table-check-inside-data-field)
1493 (let* ((col (org-table-current-column))
1494 (col1 (if left
(1- col
) col
))
1495 (beg (org-table-begin))
1496 (end (org-table-end))
1497 ;; Current cursor position
1498 (linepos (org-current-line))
1499 (colpos (if left
(1- col
) (1+ col
))))
1500 (if (and left
(= col
1))
1501 (user-error "Cannot move column further left"))
1502 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1503 (user-error "Cannot move column further right"))
1505 (while (< (point) end
)
1506 (if (org-at-table-hline-p)
1508 (org-table-goto-column col1 t
)
1509 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1510 (replace-match "|\\2|\\1|")))
1511 (beginning-of-line 2))
1512 (move-marker end nil
)
1513 (org-goto-line linepos
)
1514 (org-table-goto-column colpos
)
1516 (when (or (not org-table-fix-formulas-confirm
)
1517 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1518 (org-table-fix-formulas
1519 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1520 (cons (number-to-string colpos
) (number-to-string col
))))
1521 (org-table-fix-formulas
1522 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1523 (cons (number-to-string colpos
) (number-to-string col
)))))))
1526 (defun org-table-move-row-down ()
1527 "Move table row down."
1529 (org-table-move-row nil
))
1531 (defun org-table-move-row-up ()
1532 "Move table row up."
1534 (org-table-move-row 'up
))
1537 (defun org-table-move-row (&optional up
)
1538 "Move the current table line down. With arg UP, move it up."
1540 (let* ((col (current-column))
1542 (hline1p (save-excursion (beginning-of-line 1)
1543 (looking-at org-table-hline-regexp
)))
1544 (dline1 (org-table-current-dline))
1545 (dline2 (+ dline1
(if up -
1 1)))
1548 (beginning-of-line tonew
)
1549 (unless (org-at-table-p)
1551 (user-error "Cannot move row further"))
1552 (setq hline2p
(looking-at org-table-hline-regexp
))
1554 (beginning-of-line 1)
1556 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1557 (delete-region (point) (1+ (point-at-eol)))
1558 (beginning-of-line tonew
)
1560 (beginning-of-line 0)
1561 (org-move-to-column col
)
1562 (unless (or hline1p hline2p
1563 (not (or (not org-table-fix-formulas-confirm
)
1564 (funcall org-table-fix-formulas-confirm
1565 "Fix formulas? "))))
1566 (org-table-fix-formulas
1567 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1568 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1571 (defun org-table-insert-row (&optional arg
)
1572 "Insert a new row above the current line into the table.
1573 With prefix ARG, insert below the current line."
1575 (if (not (org-at-table-p))
1576 (user-error "Not at a table"))
1577 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1578 (new (org-table-clean-line line
)))
1579 ;; Fix the first field if necessary
1580 (if (string-match "^[ \t]*| *[#$] *|" line
)
1581 (setq new
(replace-match (match-string 0 line
) t t new
)))
1582 (beginning-of-line (if arg
2 1))
1583 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1584 (beginning-of-line 0)
1585 (re-search-forward "| ?" (point-at-eol) t
)
1586 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1588 (when (or (not org-table-fix-formulas-confirm
)
1589 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1590 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1593 (defun org-table-insert-hline (&optional above
)
1594 "Insert a horizontal-line below the current line into the table.
1595 With prefix ABOVE, insert above the current line."
1597 (if (not (org-at-table-p))
1598 (user-error "Not at a table"))
1599 (when (eobp) (insert "\n") (backward-char 1))
1600 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1602 (let ((line (org-table-clean-line
1603 (buffer-substring (point-at-bol) (point-at-eol))))
1604 (col (current-column)))
1605 (while (string-match "|\\( +\\)|" line
)
1606 (setq line
(replace-match
1607 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1608 ?-
) "|") t t line
)))
1609 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1610 (beginning-of-line (if above
1 2))
1612 (beginning-of-line (if above
1 -
1))
1613 (org-move-to-column col
)
1614 (and org-table-overlay-coordinates
(org-table-align))))
1617 (defun org-table-hline-and-move (&optional same-column
)
1618 "Insert a hline and move to the row below that line."
1620 (let ((col (org-table-current-column)))
1621 (org-table-maybe-eval-formula)
1622 (org-table-maybe-recalculate-line)
1623 (org-table-insert-hline)
1625 (if (looking-at "\n[ \t]*|-")
1626 (progn (insert "\n|") (org-table-align))
1627 (org-table-next-field))
1628 (if same-column
(org-table-goto-column col
))))
1630 (defun org-table-clean-line (s)
1631 "Convert a table line S into a string with only \"|\" and space.
1632 In particular, this does handle wide and invisible characters."
1633 (if (string-match "^[ \t]*|-" s
)
1634 ;; It's a hline, just map the characters
1635 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1636 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1637 (setq s
(replace-match
1638 (concat "|" (make-string (org-string-width (match-string 1 s
))
1644 (defun org-table-kill-row ()
1645 "Delete the current row or horizontal line from the table."
1647 (if (not (org-at-table-p))
1648 (user-error "Not at a table"))
1649 (let ((col (current-column))
1650 (dline (org-table-current-dline)))
1651 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1652 (if (not (org-at-table-p)) (beginning-of-line 0))
1653 (org-move-to-column col
)
1654 (when (or (not org-table-fix-formulas-confirm
)
1655 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1656 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1660 (defun org-table-sort-lines (with-case &optional sorting-type getkey-func compare-func
)
1661 "Sort table lines according to the column at point.
1663 The position of point indicates the column to be used for
1664 sorting, and the range of lines is the range between the nearest
1665 horizontal separator lines, or the entire table of no such lines
1666 exist. If point is before the first column, you will be prompted
1667 for the sorting column. If there is an active region, the mark
1668 specifies the first line and the sorting column, while point
1669 should be in the last line to be included into the sorting.
1671 The command then prompts for the sorting type which can be
1672 alphabetically, numerically, or by time (as given in a time stamp
1673 in the field, or as a HH:MM value). Sorting in reverse order is
1676 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1678 If SORTING-TYPE is specified when this function is called from a Lisp
1679 program, no prompting will take place. SORTING-TYPE must be a character,
1680 any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
1681 sorting should be done in reverse order.
1683 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
1684 a function to be called to extract the key. It must return either
1685 a string or a number that should serve as the sorting key for that
1686 row. It will then use COMPARE-FUNC to compare entries. If GETKEY-FUNC
1687 is specified interactively, the comparison will be either a string or
1688 numeric compare based on the type of the first key in the table."
1690 (let* ((thisline (org-current-line))
1691 (thiscol (org-table-current-column))
1692 (otc org-table-overlay-coordinates
)
1693 beg end bcol ecol tend tbeg column lns pos
)
1694 (when (equal thiscol
0)
1695 (if (org-called-interactively-p 'any
)
1698 (read-string "Use column N for sorting: ")))
1700 (org-table-goto-column thiscol
))
1701 (org-table-check-inside-data-field)
1702 (if (org-region-active-p)
1704 (setq beg
(region-beginning) end
(region-end))
1706 (setq column
(org-table-current-column)
1709 (setq end
(point-at-bol 2)))
1710 (setq column
(org-table-current-column)
1712 tbeg
(org-table-begin)
1713 tend
(org-table-end))
1714 (if (re-search-backward org-table-hline-regexp tbeg t
)
1715 (setq beg
(point-at-bol 2))
1717 (setq beg
(point-at-bol 1)))
1719 (if (re-search-forward org-table-hline-regexp tend t
)
1720 (setq end
(point-at-bol 1))
1722 (setq end
(point-at-bol))))
1723 (setq beg
(move-marker (make-marker) beg
)
1724 end
(move-marker (make-marker) end
))
1727 (org-table-goto-column column
)
1728 (skip-chars-backward "^|")
1729 (setq bcol
(current-column))
1730 (org-table-goto-column (1+ column
))
1731 (skip-chars-backward "^|")
1732 (setq ecol
(1- (current-column)))
1733 (org-table-goto-column column
)
1734 (setq lns
(mapcar (lambda(x) (cons
1735 (org-sort-remove-invisible
1737 (org-split-string x
"[ \t]*|[ \t]*")))
1739 (org-split-string (buffer-substring beg end
) "\n")))
1740 (setq lns
(org-table--do-sort
1741 lns
"Table" with-case sorting-type getkey-func compare-func
))
1742 (when org-table-overlay-coordinates
1743 (org-table-toggle-coordinate-overlays))
1744 (delete-region beg end
)
1745 (move-marker beg nil
)
1746 (move-marker end nil
)
1747 (insert (mapconcat 'cdr lns
"\n") "\n")
1748 (org-goto-line thisline
)
1749 (org-table-goto-column thiscol
)
1750 (when otc
(org-table-toggle-coordinate-overlays))
1751 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1753 (defun org-table--do-sort (table what
&optional with-case sorting-type getkey-func compare-func
)
1754 "Sort TABLE of WHAT according to SORTING-TYPE.
1755 The user will be prompted for the SORTING-TYPE if the call to this
1756 function does not specify it.
1757 WHAT is only for the prompt, to indicate what is being sorted.
1758 The sorting key will be extracted from the car of the elements of
1759 the table. If WITH-CASE is non-nil, the sorting will be case-sensitive.
1761 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
1762 a function to be called to extract the key. It must return either
1763 a string or a number that should serve as the sorting key for that
1764 row. It will then use COMPARE-FUNC to compare entries. If GETKEY-FUNC
1765 is specified interactively, the comparison will be either a string or
1766 numeric compare based on the type of the first key in the table."
1767 (unless sorting-type
1769 "Sort %s: [a]lphabetic, [n]umeric, [t]ime, [f]unc. A/N/T/F means reversed:"
1771 (setq sorting-type
(read-char-exclusive)))
1772 (let (extractfun comparefun tempfun
)
1773 ;; Define the appropriate functions
1776 (setq extractfun
#'string-to-number
1777 comparefun
(if (= sorting-type ?n
) #'< #'>)))
1779 (setq extractfun
(if with-case
(lambda(x) (org-sort-remove-invisible x
))
1780 (lambda(x) (downcase (org-sort-remove-invisible x
))))
1781 comparefun
(if (= sorting-type ?a
) #'string
< #'org-string
>)))
1785 (cond ((or (string-match org-ts-regexp x
)
1786 (string-match org-ts-regexp-both x
))
1788 (org-time-string-to-time (match-string 0 x
))))
1789 ((string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" x
)
1790 (org-hh:mm-string-to-minutes x
))
1792 comparefun
(if (= sorting-type ?t
) #'< #'>)))
1794 (setq tempfun
(or getkey-func
1795 (intern (org-icompleting-read
1796 "Sort using function: "
1797 obarray
#'fboundp t nil nil
))))
1798 (let ((extract-string-p (stringp (funcall tempfun
(caar table
)))))
1799 (setq extractfun
(if (and extract-string-p
(not with-case
))
1800 (lambda (x) (downcase (funcall tempfun x
)))
1802 (setq comparefun
(cond (compare-func
1803 (if (= sorting-type ?f
) compare-func
1804 (lambda (a b
) (funcall compare-func b a
))))
1806 (if (= sorting-type ?f
) #'string
<
1808 (t (if (= sorting-type ?f
) #'< #'>))))))
1809 (t (error "Invalid sorting type `%c'" sorting-type
)))
1811 (sort (mapcar (lambda (x) (cons (funcall extractfun
(car x
)) (cdr x
)))
1813 (lambda (a b
) (funcall comparefun
(car a
) (car b
))))))
1816 (defun org-table-cut-region (beg end
)
1817 "Copy region in table to the clipboard and blank all relevant fields.
1818 If there is no active region, use just the field at point."
1820 (if (org-region-active-p) (region-beginning) (point))
1821 (if (org-region-active-p) (region-end) (point))))
1822 (org-table-copy-region beg end
'cut
))
1825 (defun org-table-copy-region (beg end
&optional cut
)
1826 "Copy rectangular region in table to clipboard.
1827 A special clipboard is used which can only be accessed
1828 with `org-table-paste-rectangle'."
1830 (if (org-region-active-p) (region-beginning) (point))
1831 (if (org-region-active-p) (region-end) (point))
1832 current-prefix-arg
))
1833 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1835 (rpl (if cut
" " nil
)))
1837 (org-table-check-inside-data-field)
1838 (setq l01
(org-current-line)
1839 c01
(org-table-current-column))
1841 (org-table-check-inside-data-field)
1842 (setq l02
(org-current-line)
1843 c02
(org-table-current-column))
1844 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1845 c1
(min c01 c02
) c2
(max c01 c02
))
1849 (if (> l1 l2
) (throw 'exit t
))
1851 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1852 (setq cols nil ic1 c1 ic2 c2
)
1853 (while (< ic1
(1+ ic2
))
1854 (push (org-table-get-field ic1 rpl
) cols
)
1855 (setq ic1
(1+ ic1
)))
1856 (push (nreverse cols
) region
)
1857 (setq l1
(1+ l1
)))))
1858 (setq org-table-clip
(nreverse region
))
1859 (if cut
(org-table-align))
1863 (defun org-table-paste-rectangle ()
1864 "Paste a rectangular region into a table.
1865 The upper right corner ends up in the current field. All involved fields
1866 will be overwritten. If the rectangle does not fit into the present table,
1867 the table is enlarged as needed. The process ignores horizontal separator
1870 (unless (and org-table-clip
(listp org-table-clip
))
1871 (user-error "First cut/copy a region to paste!"))
1872 (org-table-check-inside-data-field)
1873 (let* ((clip org-table-clip
)
1874 (line (org-current-line))
1875 (col (org-table-current-column))
1876 (org-enable-table-editor t
)
1877 (org-table-automatic-realign nil
)
1879 (while (setq cols
(pop clip
))
1880 (while (org-at-table-hline-p) (beginning-of-line 2))
1881 (if (not (org-at-table-p))
1882 (progn (end-of-line 0) (org-table-next-field)))
1884 (while (setq field
(pop cols
))
1885 (org-table-goto-column c nil
'force
)
1886 (org-table-get-field nil field
)
1888 (beginning-of-line 2))
1889 (org-goto-line line
)
1890 (org-table-goto-column col
)
1894 (defun org-table-convert ()
1895 "Convert from `org-mode' table to table.el and back.
1896 Obviously, this only works within limits. When an Org-mode table is
1897 converted to table.el, all horizontal separator lines get lost, because
1898 table.el uses these as cell boundaries and has no notion of horizontal lines.
1899 A table.el table can be converted to an Org-mode table only if it does not
1900 do row or column spanning. Multiline cells will become multiple cells.
1901 Beware, Org-mode does not test if the table can be successfully converted - it
1902 blindly applies a recipe that works for simple tables."
1905 (if (org-at-table.el-p
)
1906 ;; convert to Org-mode table
1907 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1908 (end (move-marker (make-marker) (org-table-end t
))))
1909 (table-unrecognize-region beg end
)
1911 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1914 (if (org-at-table-p)
1915 ;; convert to table.el table
1916 (let ((beg (move-marker (make-marker) (org-table-begin)))
1917 (end (move-marker (make-marker) (org-table-end))))
1918 ;; first, get rid of all horizontal lines
1920 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1922 ;; insert a hline before first
1924 (org-table-insert-hline 'above
)
1925 (beginning-of-line -
1)
1926 ;; insert a hline after each line
1927 (while (progn (beginning-of-line 3) (< (point) end
))
1928 (org-table-insert-hline))
1930 (setq end
(move-marker end
(org-table-end)))
1931 ;; replace "+" at beginning and ending of hlines
1932 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1933 (replace-match "\\1+-"))
1935 (while (re-search-forward "-|[ \t]*$" end t
)
1936 (replace-match "-+"))
1939 (defun org-table-transpose-table-at-point ()
1940 "Transpose Org table at point and eliminate hlines.
1948 will be transposed as
1955 Note that horizontal lines disappear."
1957 (let* ((table (delete 'hline
(org-table-to-lisp)))
1958 (dline_old (org-table-current-line))
1959 (col_old (org-table-current-column))
1960 (contents (mapcar (lambda (p)
1966 (setq tp
(cdr tp
))))
1969 (goto-char (org-table-begin))
1970 (re-search-forward "|")
1972 (delete-region (point) (org-table-end))
1975 (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
1977 (org-table-goto-line col_old
)
1978 (org-table-goto-column dline_old
))
1982 (defun org-table-wrap-region (arg)
1983 "Wrap several fields in a column like a paragraph.
1984 This is useful if you'd like to spread the contents of a field over several
1985 lines, in order to keep the table compact.
1987 If there is an active region, and both point and mark are in the same column,
1988 the text in the column is wrapped to minimum width for the given number of
1989 lines. Generally, this makes the table more compact. A prefix ARG may be
1990 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1991 formats the selected text to two lines. If the region was longer than two
1992 lines, the remaining lines remain empty. A negative prefix argument reduces
1993 the current number of lines by that amount. The wrapped text is pasted back
1994 into the table. If you formatted it to more lines than it was before, fields
1995 further down in the table get overwritten - so you might need to make space in
1998 If there is no region, the current field is split at the cursor position and
1999 the text fragment to the right of the cursor is prepended to the field one
2002 If there is no region, but you specify a prefix ARG, the current field gets
2003 blank, and the content is appended to the field above."
2005 (org-table-check-inside-data-field)
2006 (if (org-region-active-p)
2007 ;; There is a region: fill as a paragraph
2008 (let* ((beg (region-beginning))
2009 (cline (save-excursion (goto-char beg
) (org-current-line)))
2010 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
2012 (org-table-cut-region (region-beginning) (region-end))
2013 (if (> (length (car org-table-clip
)) 1)
2014 (user-error "Region must be limited to single column"))
2015 (setq nlines
(if arg
2017 (+ (length org-table-clip
) arg
)
2019 (length org-table-clip
)))
2020 (setq org-table-clip
2021 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
2023 (org-goto-line cline
)
2024 (org-table-goto-column ccol
)
2025 (org-table-paste-rectangle))
2026 ;; No region, split the current field at point
2027 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
2028 (skip-chars-forward "^\r\n|"))
2030 ;; combine with field above
2031 (let ((s (org-table-blank-field))
2032 (col (org-table-current-column)))
2033 (beginning-of-line 0)
2034 (while (org-at-table-hline-p) (beginning-of-line 0))
2035 (org-table-goto-column col
)
2036 (skip-chars-forward "^|")
2037 (skip-chars-backward " ")
2038 (insert " " (org-trim s
))
2041 (if (looking-at "\\([^|]+\\)+|")
2042 (let ((s (match-string 1)))
2043 (replace-match " |")
2044 (goto-char (match-beginning 0))
2045 (org-table-next-row)
2046 (insert (org-trim s
) " ")
2048 (org-table-next-row)))))
2050 (defvar org-field-marker nil
)
2053 (defun org-table-edit-field (arg)
2054 "Edit table field in a different window.
2055 This is mainly useful for fields that contain hidden parts.
2056 When called with a \\[universal-argument] prefix, just make the full field visible so that
2057 it can be edited in place."
2061 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
2063 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
2064 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
2065 (remove-text-properties b e
'(org-cwidth t invisible t
2066 display t intangible t
))
2067 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
2068 (font-lock-fontify-block))))
2070 (let ((pos (point-marker))
2072 (if (eq org-table-use-standard-references t
)
2073 (concat (org-number-to-letters (org-table-current-column))
2074 (int-to-string (org-table-current-dline)))
2075 (concat "@" (int-to-string (org-table-current-dline))
2076 "$" (int-to-string (org-table-current-column)))))
2077 (field (org-table-get-field))
2078 (cw (current-window-configuration))
2081 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
2082 (when (and (local-variable-p 'org-field-marker
)
2083 (markerp org-field-marker
))
2084 (move-marker org-field-marker nil
))
2086 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
2087 (let ((org-inhibit-startup t
)) (org-mode))
2089 (setq truncate-lines nil
)
2091 (goto-char (setq p
(point-max)))
2092 (insert (org-trim field
))
2093 (remove-text-properties p
(point-max)
2094 '(invisible t org-cwidth t display t
2097 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
2098 (org-set-local 'org-window-configuration cw
)
2099 (org-set-local 'org-field-marker pos
)
2100 (message "Edit and finish with C-c C-c")))))
2102 (defun org-table-finish-edit-field ()
2103 "Finish editing a table data field.
2104 Remove all newline characters, insert the result into the table, realign
2105 the table and kill the editing buffer."
2106 (let ((pos org-field-marker
)
2107 (cw org-window-configuration
)
2108 (cb (current-buffer))
2110 (goto-char (point-min))
2111 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
2112 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
2113 (replace-match " "))
2114 (setq text
(org-trim (buffer-string)))
2115 (set-window-configuration cw
)
2117 (select-window (get-buffer-window (marker-buffer pos
)))
2119 (move-marker pos nil
)
2120 (org-table-check-inside-data-field)
2121 (org-table-get-field nil text
)
2123 (message "New field value inserted")))
2125 (define-minor-mode org-table-follow-field-mode
2126 "Minor mode to make the table field editor window follow the cursor.
2127 When this mode is active, the field editor window will always show the
2128 current field. The mode exits automatically when the cursor leaves the
2129 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
2130 nil
" TblFollow" nil
2131 (if org-table-follow-field-mode
2132 (org-add-hook 'post-command-hook
'org-table-follow-fields-with-editor
2134 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
2135 (let* ((buf (get-buffer "*Org Table Edit Field*"))
2136 (win (and buf
(get-buffer-window buf
))))
2137 (when win
(delete-window win
))
2139 (with-current-buffer buf
2140 (move-marker org-field-marker nil
))
2141 (kill-buffer buf
)))))
2143 (defun org-table-follow-fields-with-editor ()
2144 (if (and org-table-exit-follow-field-mode-when-leaving-table
2145 (not (org-at-table-p)))
2146 ;; We have left the table, exit the follow mode
2147 (org-table-follow-field-mode -
1)
2148 (when (org-table-check-inside-data-field 'noerror
)
2149 (let ((win (selected-window)))
2150 (org-table-edit-field nil
)
2151 (org-fit-window-to-buffer)
2152 (select-window win
)))))
2154 (defvar org-timecnt
) ; dynamically scoped parameter
2157 (defun org-table-sum (&optional beg end nlast
)
2158 "Sum numbers in region of current table column.
2159 The result will be displayed in the echo area, and will be available
2160 as kill to be inserted with \\[yank].
2162 If there is an active region, it is interpreted as a rectangle and all
2163 numbers in that rectangle will be summed. If there is no active
2164 region and point is located in a table column, sum all numbers in that
2167 If at least one number looks like a time HH:MM or HH:MM:SS, all other
2168 numbers are assumed to be times as well (in decimal hours) and the
2169 numbers are added as such.
2171 If NLAST is a number, only the NLAST fields will actually be summed."
2174 (let (col (org-timecnt 0) diff h m s org-table-clip
)
2176 ((and beg end
)) ; beg and end given explicitly
2177 ((org-region-active-p)
2178 (setq beg
(region-beginning) end
(region-end)))
2180 (setq col
(org-table-current-column))
2181 (goto-char (org-table-begin))
2182 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
2183 (user-error "No table data"))
2184 (org-table-goto-column col
)
2186 (goto-char (org-table-end))
2187 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
2188 (user-error "No table data"))
2189 (org-table-goto-column col
)
2190 (setq end
(point))))
2191 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
2192 (items1 (cond ((not nlast
) items
)
2193 ((>= nlast
(length items
)) items
)
2194 (t (setq items
(reverse items
))
2195 (setcdr (nthcdr (1- nlast
) items
) nil
)
2197 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
2199 (res (apply '+ numbers
))
2200 (sres (if (= org-timecnt
0)
2201 (number-to-string res
)
2202 (setq diff
(* 3600 res
)
2203 h
(floor (/ diff
3600)) diff
(mod diff
3600)
2204 m
(floor (/ diff
60)) diff
(mod diff
60)
2206 (format "%.0f:%02.0f:%02.0f" h m s
))))
2208 (if (org-called-interactively-p 'interactive
)
2210 (substitute-command-keys
2211 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
2212 (length numbers
) sres
))))
2215 (defun org-table-get-number-for-summing (s)
2217 (if (string-match "^ *|? *" s
)
2218 (setq s
(replace-match "" nil nil s
)))
2219 (if (string-match " *|? *$" s
)
2220 (setq s
(replace-match "" nil nil s
)))
2221 (setq n
(string-to-number s
))
2223 ((and (string-match "0" s
)
2224 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
2225 ((string-match "\\`[ \t]+\\'" s
) nil
)
2226 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
2227 (let ((h (string-to-number (or (match-string 1 s
) "0")))
2228 (m (string-to-number (or (match-string 2 s
) "0")))
2229 (s (string-to-number (or (match-string 4 s
) "0"))))
2230 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
2231 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
2235 (defun org-table-current-field-formula (&optional key noerror
)
2236 "Return the formula active for the current field.
2237 Assumes that specials are in place.
2238 If KEY is given, return the key to this formula.
2239 Otherwise return the formula preceded with \"=\" or \":=\"."
2240 (let* ((name (car (rassoc (list (org-current-line)
2241 (org-table-current-column))
2242 org-table-named-field-locations
)))
2243 (col (org-table-current-column))
2244 (scol (int-to-string col
))
2245 (ref (format "@%d$%d" (org-table-current-dline) col
))
2246 (stored-list (org-table-get-stored-formulas noerror
))
2247 (ass (or (assoc name stored-list
)
2248 (assoc ref stored-list
)
2249 (assoc scol stored-list
))))
2252 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
2255 (defun org-table-get-formula (&optional equation named
)
2256 "Read a formula from the minibuffer, offer stored formula as default.
2257 When NAMED is non-nil, look for a named equation."
2258 (let* ((stored-list (org-table-get-stored-formulas))
2259 (name (car (rassoc (list (org-current-line)
2260 (org-table-current-column))
2261 org-table-named-field-locations
)))
2262 (ref (format "@%d$%d" (org-table-current-dline)
2263 (org-table-current-column)))
2264 (refass (assoc ref stored-list
))
2265 (nameass (assoc name stored-list
))
2267 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
2270 (int-to-string (org-table-current-column))))
2271 (dummy (and (or nameass refass
) (not named
)
2272 (not (y-or-n-p "Replace existing field formula with column formula? " ))
2273 (message "Formula not replaced")))
2274 (name (or name ref
))
2275 (org-table-may-need-update nil
)
2276 (stored (cdr (assoc scol stored-list
)))
2278 ((and stored equation
(string-match "^ *=? *$" equation
))
2282 (t (org-table-formula-from-user
2284 (org-table-formula-to-user
2285 (format "%s formula %s%s="
2286 (if named
"Field" "Column")
2287 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
2289 (if stored
(org-table-formula-to-user stored
) "")
2290 'org-table-formula-history
2293 (when (not (string-match "\\S-" eq
))
2295 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2296 (org-table-store-formulas stored-list
)
2297 (user-error "Formula removed"))
2298 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2299 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2300 (if (and name
(not named
))
2301 ;; We set the column equation, delete the named one.
2302 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2305 (setcdr (assoc scol stored-list
) eq
)
2306 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2307 (if (or mustsave
(not (equal stored eq
)))
2308 (org-table-store-formulas stored-list
))
2311 (defun org-table-store-formulas (alist)
2312 "Store the list of formulas below the current table."
2313 (setq alist
(sort alist
'org-table-formula-less-p
))
2314 (let ((case-fold-search t
))
2316 (goto-char (org-table-end))
2317 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
2319 ;; don't overwrite TBLFM, we might use text properties to store stuff
2320 (goto-char (match-beginning 3))
2321 (delete-region (match-beginning 3) (match-end 0)))
2323 (insert (or (match-string 2) "#+TBLFM:")))
2325 (mapconcat (lambda (x)
2327 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2328 (car x
) "=" (cdr x
)))
2332 (defsubst org-table-formula-make-cmp-string
(a)
2333 (when (string-match "\\`$[<>]" a
)
2334 (let ((arrow (string-to-char (substring a
1))))
2335 ;; Fake a high number to make sure this is sorted at the end.
2336 (setq a
(org-table-formula-handle-first/last-rc a
))
2337 (setq a
(format "$%d" (+ 10000
2338 (if (= arrow ?
<) -
1000 0)
2339 (string-to-number (substring a
1)))))))
2341 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2345 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2347 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2349 (concat "@@" (match-string 5 a
))))))
2351 (defun org-table-formula-less-p (a b
)
2352 "Compare two formulas for sorting."
2353 (let ((as (org-table-formula-make-cmp-string (car a
)))
2354 (bs (org-table-formula-make-cmp-string (car b
))))
2355 (and as bs
(string< as bs
))))
2358 (defun org-table-get-stored-formulas (&optional noerror
)
2359 "Return an alist with the stored formulas directly after current table."
2360 (interactive) ;; FIXME interactive?
2361 (let ((case-fold-search t
) scol eq eq-alist strings string seen
)
2363 (goto-char (org-table-end))
2364 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
2365 (setq strings
(org-split-string (org-match-string-no-properties 2)
2367 (while (setq string
(pop strings
))
2368 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2369 (setq scol
(if (match-end 2)
2370 (match-string 2 string
)
2371 (match-string 1 string
))
2372 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2373 (concat "$" scol
) scol
)
2374 eq
(match-string 3 string
)
2375 eq-alist
(cons (cons scol eq
) eq-alist
))
2376 (if (member scol seen
)
2379 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2382 (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2383 (push scol seen
))))))
2384 (nreverse eq-alist
)))
2386 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2387 "Modify the equations after the table structure has been edited.
2388 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2389 For all numbers larger than LIMIT, shift them by DELTA."
2391 (goto-char (org-table-end))
2392 (while (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2393 (let ((msg "The formulas in #+TBLFM have been updated")
2394 (re (concat key
"\\([0-9]+\\)"))
2397 (if (or (equal key
"$") (equal key
"$LR"))
2398 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2399 (regexp-quote key
) remove
)
2400 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2403 (while (re-search-forward re2
(point-at-eol) t
)
2404 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2405 (if (equal (char-before (match-beginning 0)) ?.
)
2407 "Change makes TBLFM term %s invalid, use undo to recover"
2409 (replace-match "")))))
2410 (while (re-search-forward re
(point-at-eol) t
)
2411 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2412 (setq s
(match-string 1) n
(string-to-number s
))
2414 ((setq a
(assoc s replace
))
2415 (replace-match (concat key
(cdr a
)) t t
)
2417 ((and limit
(> n limit
))
2418 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2422 (defun org-table-get-specials ()
2423 "Get the column names and local parameters for this table."
2425 (let ((beg (org-table-begin)) (end (org-table-end))
2426 names name fields fields1 field cnt
2427 c v l line col types dlines hlines last-dline
)
2428 (setq org-table-column-names nil
2429 org-table-local-parameters nil
2430 org-table-named-field-locations nil
2431 org-table-current-begin-line nil
2432 org-table-current-begin-pos nil
2433 org-table-current-line-types nil
2434 org-table-current-ncol
0)
2436 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2437 (setq names
(org-split-string (match-string 1) " *| *")
2439 (while (setq name
(pop names
))
2441 (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name
)
2442 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2443 (setq org-table-column-names
(nreverse org-table-column-names
))
2444 (setq org-table-column-name-regexp
2445 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2447 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2448 (setq fields
(org-split-string (match-string 1) " *| *"))
2449 (while (setq field
(pop fields
))
2450 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2451 (push (cons (match-string 1 field
) (match-string 2 field
))
2452 org-table-local-parameters
))))
2454 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2455 (setq c
(match-string 1)
2456 fields
(org-split-string (match-string 2) " *| *"))
2458 (beginning-of-line (if (equal c
"_") 2 0))
2459 (setq line
(org-current-line) col
1)
2460 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2461 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2462 (while (and fields1
(setq field
(pop fields
)))
2463 (setq v
(pop fields1
) col
(1+ col
))
2464 (when (and (stringp field
) (stringp v
)
2465 (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field
))
2466 (push (cons field v
) org-table-local-parameters
)
2467 (push (list field line col
) org-table-named-field-locations
))))
2468 ;; Analyse the line types
2470 (setq org-table-current-begin-line
(org-current-line)
2471 org-table-current-begin-pos
(point)
2472 l org-table-current-begin-line
)
2473 (while (looking-at "[ \t]*|\\(-\\)?")
2474 (push (if (match-end 1) 'hline
'dline
) types
)
2475 (if (match-end 1) (push l hlines
) (push l dlines
))
2476 (beginning-of-line 2)
2478 (push 'hline types
) ;; add an imaginary extra hline to the end
2479 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2480 last-dline
(car dlines
)
2481 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2482 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2483 (org-goto-line last-dline
)
2484 (let* ((l last-dline
)
2485 (fields (org-split-string
2486 (buffer-substring (point-at-bol) (point-at-eol))
2488 (nfields (length fields
))
2490 (setq org-table-current-ncol nfields
)
2491 (loop for i from
1 to nfields do
2492 (push (list (format "LR%d" i
) l i
) al
)
2493 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2494 (setq org-table-named-field-locations
2495 (append org-table-named-field-locations al
))
2496 (setq org-table-local-parameters
2497 (append org-table-local-parameters al2
))))))
2500 (defun org-table-maybe-eval-formula ()
2501 "Check if the current field starts with \"=\" or \":=\".
2502 If yes, store the formula and apply it."
2503 ;; We already know we are in a table. Get field will only return a formula
2504 ;; when appropriate. It might return a separator line, but no problem.
2505 (when org-table-formula-evaluate-inline
2506 (let* ((field (org-trim (or (org-table-get-field) "")))
2508 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2509 (setq named
(equal (string-to-char field
) ?
:)
2510 eq
(match-string 1 field
))
2511 (if (or (fboundp 'calc-eval
)
2512 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2513 (org-table-eval-formula (if named
'(4) nil
)
2514 (org-table-formula-from-user eq
))
2515 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2517 (defvar org-recalc-commands nil
2518 "List of commands triggering the recalculation of a line.
2519 Will be filled automatically during use.")
2521 (defvar org-recalc-marks
2522 '((" " .
"Unmarked: no special line, no automatic recalculation")
2523 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2524 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2525 ("!" .
"Column name definition line. Reference in formula as $name.")
2526 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2527 ("_" .
"Names for values in row below this one.")
2528 ("^" .
"Names for values in row above this one.")))
2531 (defun org-table-rotate-recalc-marks (&optional newchar
)
2532 "Rotate the recalculation mark in the first column.
2533 If in any row, the first field is not consistent with a mark,
2534 insert a new column for the markers.
2535 When there is an active region, change all the lines in the region,
2536 after prompting for the marking character.
2537 After each change, a message will be displayed indicating the meaning
2540 (unless (org-at-table-p) (user-error "Not at a table"))
2541 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2542 (beg (org-table-begin))
2543 (end (org-table-end))
2544 (l (org-current-line))
2545 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2546 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2550 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2551 (col (org-table-current-column))
2552 (forcenew (car (assoc newchar org-recalc-marks
)))
2555 (message "Change region to what mark? Type # * ! $ or SPC: ")
2556 (setq newchar
(char-to-string (read-char-exclusive))
2557 forcenew
(car (assoc newchar org-recalc-marks
))))
2558 (if (and newchar
(not forcenew
))
2559 (user-error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2561 (if l1
(org-goto-line l1
))
2563 (beginning-of-line 1)
2564 (unless (looking-at org-table-dataline-regexp
)
2565 (user-error "Not at a table data line")))
2567 (org-table-goto-column 1)
2568 (org-table-insert-column)
2569 (org-table-goto-column (1+ col
)))
2570 (setq epos
(point-at-eol))
2572 (beginning-of-line 1)
2573 (org-table-get-field
2574 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2576 (setq new
(or forcenew
2577 (cadr (member (match-string 1) marks
))))
2583 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2584 (and (looking-at org-table-dataline-regexp
)
2585 (org-table-get-field 1 (concat " " new
" "))))
2586 (org-goto-line l1
)))
2587 (if (not (= epos
(point-at-eol))) (org-table-align))
2589 (and (org-called-interactively-p 'interactive
)
2590 (message "%s" (cdr (assoc new org-recalc-marks
))))))
2593 (defun org-table-maybe-recalculate-line ()
2594 "Recompute the current line if marked for it, and if we haven't just done it."
2596 (and org-table-allow-automatic-line-recalculation
2597 (not (and (memq last-command org-recalc-commands
)
2598 (equal org-last-recalc-line
(org-current-line))))
2599 (save-excursion (beginning-of-line 1)
2600 (looking-at org-table-auto-recalculate-regexp
))
2601 (org-table-recalculate) t
))
2603 (defvar org-tbl-calc-modes
) ;; Dynamically bound in `org-table-eval-formula'
2604 (defsubst org-set-calc-mode
(var &optional value
)
2606 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2607 ("R" calc-angle-mode rad
)
2608 ("F" calc-prefer-frac t
)
2609 ("S" calc-symbolic-mode t
)))
2610 value
(nth 2 var
) var
(nth 1 var
)))
2611 (if (memq var org-tbl-calc-modes
)
2612 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
2613 (cons var
(cons value org-tbl-calc-modes
)))
2617 (defun org-table-eval-formula (&optional arg equation
2618 suppress-align suppress-const
2619 suppress-store suppress-analysis
)
2620 "Replace the table field value at the cursor by the result of a calculation.
2622 This function makes use of Dave Gillespie's Calc package, in my view the
2623 most exciting program ever written for GNU Emacs. So you need to have Calc
2624 installed in order to use this function.
2626 In a table, this command replaces the value in the current field with the
2627 result of a formula. It also installs the formula as the \"current\" column
2628 formula, by storing it in a special line below the table. When called
2629 with a `C-u' prefix, the current field must be a named field, and the
2630 formula is installed as valid in only this specific field.
2632 When called with two `C-u' prefixes, insert the active equation
2633 for the field back into the current field, so that it can be
2634 edited there. This is useful in order to use \\[org-table-show-reference]
2635 to check the referenced fields.
2637 When called, the command first prompts for a formula, which is read in
2638 the minibuffer. Previously entered formulas are available through the
2639 history list, and the last used formula is offered as a default.
2640 These stored formulas are adapted correctly when moving, inserting, or
2641 deleting columns with the corresponding commands.
2643 The formula can be any algebraic expression understood by the Calc package.
2644 For details, see the Org-mode manual.
2646 This function can also be called from Lisp programs and offers
2647 additional arguments: EQUATION can be the formula to apply. If this
2648 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2649 used to speed-up recursive calls by by-passing unnecessary aligns.
2650 SUPPRESS-CONST suppresses the interpretation of constants in the
2651 formula, assuming that this has been done already outside the function.
2652 SUPPRESS-STORE means the formula should not be stored, either because
2653 it is already stored, or because it is a modified equation that should
2654 not overwrite the stored one."
2656 (org-table-check-inside-data-field)
2657 (or suppress-analysis
(org-table-get-specials))
2658 (if (equal arg
'(16))
2659 (let ((eq (org-table-current-field-formula)))
2660 (or eq
(user-error "No equation active for current field"))
2661 (org-table-get-field nil eq
)
2663 (setq org-table-may-need-update t
))
2665 (ndown (if (integerp arg
) arg
1))
2666 (org-table-automatic-realign nil
)
2667 (case-fold-search nil
)
2669 (formula (if (and equation suppress-store
)
2671 (org-table-get-formula equation
(equal arg
'(4)))))
2672 (n0 (org-table-current-column))
2673 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2674 (numbers nil
) ; was a variable, now fixed default
2676 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2677 duration duration-output-format
)
2678 ;; Parse the format string. Since we have a lot of modes, this is
2679 ;; a lot of work. However, I think calc still uses most of the time.
2680 (if (string-match ";" formula
)
2681 (let ((tmp (org-split-string formula
";")))
2682 (setq formula
(car tmp
)
2683 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2685 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2686 (setq c
(string-to-char (match-string 1 fmt
))
2687 n
(string-to-number (match-string 2 fmt
)))
2689 (setq org-tbl-calc-modes
(org-set-calc-mode 'calc-internal-prec n
))
2690 (setq org-tbl-calc-modes
2693 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2694 (?s . sci
) (?e . eng
))))
2696 (setq fmt
(replace-match "" t t fmt
)))
2697 (if (string-match "T" fmt
)
2698 (setq duration t numbers t
2699 duration-output-format nil
2700 fmt
(replace-match "" t t fmt
)))
2701 (if (string-match "t" fmt
)
2703 duration-output-format org-table-duration-custom-format
2705 fmt
(replace-match "" t t fmt
)))
2706 (if (string-match "N" fmt
)
2708 fmt
(replace-match "" t t fmt
)))
2709 (if (string-match "L" fmt
)
2711 fmt
(replace-match "" t t fmt
)))
2712 (if (string-match "E" fmt
)
2714 fmt
(replace-match "" t t fmt
)))
2715 (while (string-match "[DRFS]" fmt
)
2716 (setq org-tbl-calc-modes
(org-set-calc-mode (match-string 0 fmt
)))
2717 (setq fmt
(replace-match "" t t fmt
)))
2718 (unless (string-match "\\S-" fmt
)
2720 (if (and (not suppress-const
) org-table-formula-use-constants
)
2721 (setq formula
(org-table-formula-substitute-names formula
)))
2722 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2724 (setq fields
(org-split-string
2725 (buffer-substring-no-properties (point-at-bol) (point-at-eol))
2727 ;; replace fields with duration values if relevant
2730 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2733 (setq fields
(mapcar
2735 (if (string-match "\\S-" x
)
2736 (number-to-string (string-to-number x
))
2739 (setq ndown
(1- ndown
))
2740 (setq form
(copy-sequence formula
)
2741 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2742 (if (and lispp literal
) (setq lispp
'literal
))
2744 ;; Insert row and column number of formula result field
2745 (while (string-match "[@$]#" form
)
2750 (if (equal (substring form
(match-beginning 0)
2751 (1+ (match-beginning 0)))
2753 (org-table-current-dline)
2754 (org-table-current-column))))
2757 ;; Check for old vertical references
2758 (org-table--error-on-old-row-references form
)
2759 ;; Insert remote references
2760 (setq form
(org-table-remote-reference-indirection form
))
2761 (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2765 (org-table-make-reference
2766 (let ((rmtrng (org-table-get-remote-range
2767 (match-string 1 form
) (match-string 2 form
))))
2770 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2771 (org-table-time-string-to-seconds rmtrng
))
2773 keep-empty numbers lispp
))
2775 ;; Insert complex ranges
2776 (while (and (string-match org-table-range-regexp form
)
2777 (> (length (match-string 0 form
)) 1))
2778 (setq formrg
(save-match-data
2779 (org-table-get-range (match-string 0 form
) nil n0
)))
2782 (org-table-make-reference
2783 ;; possibly handle durations
2786 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2787 (org-table-time-string-to-seconds formrg
))
2789 keep-empty numbers lispp
)))
2790 (if (not (save-match-data
2791 (string-match (regexp-quote form
) formrpl
)))
2792 (setq form
(replace-match formrpl t t form
))
2793 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2794 ;; Insert simple ranges
2795 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2799 (org-table-make-reference
2801 fields
(string-to-number (match-string 1 form
))
2802 (string-to-number (match-string 2 form
)))
2803 keep-empty numbers lispp
))
2806 ;; Insert the references to fields in same row
2807 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2808 (setq n
(+ (string-to-number (match-string 1 form
))
2809 (if (match-end 2) n0
0))
2810 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
)
2811 formrpl
(save-match-data
2812 (org-table-make-reference
2813 x keep-empty numbers lispp
)))
2816 (string-match (regexp-quote formula
) formrpl
)))
2817 (user-error "Invalid field specifier \"%s\""
2818 (match-string 0 form
)))
2819 (setq form
(replace-match formrpl t t form
)))
2822 (setq ev
(condition-case nil
2823 (eval (eval (read form
)))
2825 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2826 ev
(if duration
(org-table-time-seconds-to-string
2827 (string-to-number ev
)
2828 duration-output-format
) ev
))
2829 (or (fboundp 'calc-eval
)
2830 (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2831 ;; Use <...> time-stamps so that Calc can handle them
2832 (while (string-match (concat "\\[" org-ts-regexp1
"\\]") form
)
2833 (setq form
(replace-match "<\\1>" nil nil form
)))
2834 ;; I18n-ize local time-stamps by setting (system-time-locale "C")
2835 (when (string-match org-ts-regexp2 form
)
2836 (let* ((ts (match-string 0 form
))
2837 (tsp (apply 'encode-time
(save-match-data (org-parse-time-string ts
))))
2838 (system-time-locale "C")
2839 (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2840 (cdr org-time-stamp-formats
))
2841 (car org-time-stamp-formats
))))
2842 (setq form
(replace-match (format-time-string tf tsp
) t t form
))))
2844 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2846 (calc-eval (cons form org-tbl-calc-modes
)
2847 (when (and (not keep-empty
) numbers
) 'num
)))
2848 ev
(if duration
(org-table-time-seconds-to-string
2849 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2850 (string-to-number (org-table-time-string-to-seconds ev
))
2851 (string-to-number ev
))
2852 duration-output-format
)
2855 (when org-table-formula-debug
2856 (with-output-to-temp-buffer "*Substitution History*"
2857 (princ (format "Substitution history of formula
2861 $1-> %s\n" orig formula form0 form
))
2863 (princ (format " %s^\nError: %s"
2864 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2865 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2867 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2868 (setq bw
(get-buffer-window "*Substitution History*"))
2869 (org-fit-window-to-buffer bw
)
2870 (unless (and (org-called-interactively-p 'any
) (not ndown
))
2871 (unless (let (inhibit-redisplay)
2872 (y-or-n-p "Debugging Formula. Continue to next? "))
2874 (user-error "Abort"))
2877 (when (consp ev
) (setq fmt nil ev
"#ERROR"))
2878 (org-table-justify-field-maybe
2879 (format org-table-formula-field-format
2880 (if fmt
(format fmt
(string-to-number ev
)) ev
)))
2881 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2882 (call-interactively 'org-return
)
2884 (and down
(org-table-maybe-recalculate-line))
2885 (or suppress-align
(and org-table-may-need-update
2886 (org-table-align))))))
2888 (defun org-table-put-field-property (prop value
)
2890 (put-text-property (progn (skip-chars-backward "^|") (point))
2891 (progn (skip-chars-forward "^|") (point))
2894 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2895 "Get a calc vector from a column, according to descriptor DESC.
2896 Optional arguments TBEG and COL can give the beginning of the table and
2897 the current column, to avoid unnecessary parsing.
2899 HIGHLIGHT means just highlight the range.
2901 When CORNERS-ONLY is set, only return the corners of the range as
2902 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2903 in the buffer and column1 and column2 are table column numbers."
2904 (if (not (equal (string-to-char desc
) ?
@))
2905 (setq desc
(concat "@" desc
)))
2907 (or tbeg
(setq tbeg
(org-table-begin)))
2908 (or col
(setq col
(org-table-current-column)))
2909 (let ((thisline (org-current-line))
2910 beg end c1 c2 r1 r2 rangep tmp
)
2911 (unless (string-match org-table-range-regexp desc
)
2912 (user-error "Invalid table range specifier `%s'" desc
))
2913 (setq rangep
(match-end 3)
2914 r1
(and (match-end 1) (match-string 1 desc
))
2915 r2
(and (match-end 4) (match-string 4 desc
))
2916 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2917 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2919 (and c1
(setq c1
(+ (string-to-number c1
)
2920 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2921 (and c2
(setq c2
(+ (string-to-number c2
)
2922 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2923 (if (equal r1
"") (setq r1 nil
))
2924 (if (equal r2
"") (setq r2 nil
))
2925 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2926 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2927 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2928 (if (not r1
) (setq r1 thisline
))
2929 (if (not r2
) (setq r2 thisline
))
2930 (if (or (not c1
) (= 0 c1
)) (setq c1 col
))
2931 (if (or (not c2
) (= 0 c2
)) (setq c2 col
))
2932 (if (and (not corners-only
)
2933 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2937 (while (not (looking-at org-table-dataline-regexp
))
2938 (beginning-of-line 2))
2939 (prog1 (org-trim (org-table-get-field c1
))
2940 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2941 ;; A range, return a vector
2942 ;; First sort the numbers to get a regular rectangle
2943 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2944 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2946 ;; Only return the corners of the range
2948 ;; Copy the range values into a list
2950 (while (not (looking-at org-table-dataline-regexp
))
2951 (beginning-of-line 2))
2952 (org-table-goto-column c1
)
2955 (while (not (looking-at org-table-dataline-regexp
))
2956 (beginning-of-line 0))
2957 (org-table-goto-column c2
)
2960 (org-table-highlight-rectangle
2961 beg
(progn (skip-chars-forward "^|\n") (point))))
2962 ;; return string representation of calc vector
2964 (apply 'append
(org-table-copy-region beg end
))))))))
2966 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2967 "Analyze descriptor DESC and retrieve the corresponding line number.
2968 The cursor is currently in line CLINE, the table begins in line BLINE,
2969 and TABLE is a vector with line types."
2970 (if (string-match "^[0-9]+$" desc
)
2971 (aref org-table-dlines
(string-to-number desc
))
2972 (setq cline
(or cline
(org-current-line))
2973 bline
(or bline org-table-current-begin-line
)
2974 table
(or table org-table-current-line-types
))
2976 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2978 (and (not (match-end 3)) (not (match-end 6)))
2979 (and (match-end 3) (match-end 6) (not (match-end 5))))
2980 (user-error "Invalid row descriptor `%s'" desc
))
2981 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2982 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2983 (odir (and (match-end 5) (match-string 5 desc
)))
2984 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2986 (rel (and (match-end 6)
2987 (or (and (match-end 1) (not (match-end 3)))
2989 (if (and hn
(not hdir
))
2992 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2993 (if (and (not hn
) on
(not odir
))
2994 (user-error "Should never happen");;(aref org-table-dlines on)
2995 (if (and hn
(> hn
0))
2996 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2997 nil hn cline desc
)))
2999 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
3000 rel on cline desc
)))
3003 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
3004 "FIXME: Needs more documentation."
3005 (let ((l (length table
)))
3007 (while (and (setq i
(+ i
(if backwards -
1 1)))
3009 (not (eq (aref table i
) type
))
3010 (if (and relative
(eq (aref table i
) 'hline
))
3012 ((eq org-table-relative-ref-may-cross-hline t
) t
)
3013 ((eq org-table-relative-ref-may-cross-hline
'error
)
3014 (user-error "Row descriptor %s used in line %d crosses hline" desc cline
))
3015 (t (setq i
(- i
(if backwards -
1 1))
3020 (cond ((or (< i
0) (>= i l
))
3021 (user-error "Row descriptor %s used in line %d leads outside table"
3023 ;; The last hline doesn't exist. Instead, point to last row
3025 ((= i
(1- l
)) (1- i
))
3028 (defun org-table--error-on-old-row-references (s)
3029 (when (string-match "&[-+0-9I]" s
)
3030 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
3032 (defun org-table-make-reference (elements keep-empty numbers lispp
)
3033 "Convert list ELEMENTS to something appropriate to insert into formula.
3034 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
3035 NUMBERS indicates that everything should be converted to numbers.
3036 LISPP non-nil means to return something appropriate for a Lisp
3037 list, 'literal is for the format specifier L."
3038 ;; Calc nan (not a number) is used for the conversion of the empty
3039 ;; field to a reference for several reasons: (i) It is accepted in a
3040 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
3041 ;; (ii) In a single field (not in range) it can be distinguished
3042 ;; from "(nan)" which is the reference made from a single field
3043 ;; containing "nan".
3044 (if (stringp elements
)
3047 (if (eq lispp
'literal
)
3049 (if (and (eq elements
"") (not keep-empty
))
3052 (if numbers
(string-to-number elements
) elements
))))
3053 (if (string-match "\\S-" elements
)
3055 (when numbers
(setq elements
(number-to-string
3056 (string-to-number elements
))))
3057 (concat "(" elements
")"))
3058 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
3063 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
3065 (setq elements
(or elements
'())) ; if delq returns nil then we need '()
3069 (if (eq lispp
'literal
)
3071 (prin1-to-string (if numbers
(string-to-number x
) x
))))
3073 (concat "[" (mapconcat
3075 (if (string-match "\\S-" x
)
3077 (number-to-string (string-to-number x
))
3079 (if (or (not keep-empty
) numbers
) "0" "nan")))
3083 (defun org-table-message-once-per-second (t1 &rest args
)
3084 "If there has been more than one second since T1, display message.
3085 ARGS are passed as arguments to the `message' function. Returns
3086 current time if a message is printed, otherwise returns T1. If
3087 T1 is nil, always messages."
3088 (let ((curtime (current-time)))
3089 (if (or (not t1
) (< 0 (nth 1 (time-subtract curtime t1
))))
3090 (progn (apply 'message args
)
3095 (defun org-table-recalculate (&optional all noalign
)
3096 "Recalculate the current table line by applying all stored formulas.
3097 With prefix arg ALL, do this for all lines in the table.
3098 With the prefix argument ALL is `(16)' \
3099 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
3100 it is the symbol `iterate', recompute the table until it no longer changes.
3101 If NOALIGN is not nil, do not re-align the table after the computations
3102 are done. This is typically used internally to save time, if it is
3103 known that the table will be realigned a little later anyway."
3105 (or (memq this-command org-recalc-commands
)
3106 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
3107 (unless (org-at-table-p) (user-error "Not at a table"))
3108 (if (or (eq all
'iterate
) (equal all
'(16)))
3110 (org-table-get-specials)
3111 (let* ((eqlist (sort (org-table-get-stored-formulas)
3112 (lambda (a b
) (string< (car a
) (car b
)))))
3113 (eqlist1 (copy-sequence eqlist
))
3114 (inhibit-redisplay (not debug-on-error
))
3115 (line-re org-table-dataline-regexp
)
3116 (thisline (org-current-line))
3117 (thiscol (org-table-current-column))
3118 (log-first-time (current-time))
3119 (log-last-time log-first-time
)
3121 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
3122 ;; Insert constants in all formulas
3127 (if (string-match "^@-?I+" (car x
))
3128 (user-error "Can't assign to hline relative reference"))
3129 (when (string-match "\\`$[<>]" (car x
))
3131 (setq x
(cons (substring
3132 (org-table-formula-handle-first/last-rc
3135 (if (assoc (car x
) eqlist1
)
3136 (user-error "\"%s=\" formula tries to overwrite existing formula for column %s"
3139 (org-table-formula-handle-first/last-rc
(car x
))
3140 (org-table-formula-substitute-names
3141 (org-table-formula-handle-first/last-rc
(cdr x
)))))
3143 ;; Split the equation list
3144 (while (setq eq
(pop eqlist
))
3145 (if (<= (string-to-char (car eq
)) ?
9)
3148 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
3149 ;; Expand ranges in lhs of formulas
3150 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
3152 ;; Get the correct line range to process
3155 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
3156 (goto-char (setq beg
(org-table-begin)))
3157 (if (re-search-forward org-table-calculate-mark-regexp end t
)
3158 ;; This is a table with marked lines, compute selected lines
3159 (setq line-re org-table-recalculate-regexp
)
3160 ;; Move forward to the first non-header line
3161 (if (and (re-search-forward org-table-dataline-regexp end t
)
3162 (re-search-forward org-table-hline-regexp end t
)
3163 (re-search-forward org-table-dataline-regexp end t
))
3164 (setq beg
(match-beginning 0))
3165 nil
))) ;; just leave beg where it is
3166 (setq beg
(point-at-bol)
3167 end
(move-marker (make-marker) (1+ (point-at-eol)))))
3170 ;; First find the named fields, and mark them untouchable.
3171 ;; Also check if several field/range formulas try to set the same field.
3172 (remove-text-properties beg end
'(org-untouchable t
))
3173 (while (setq eq
(pop eqlname
))
3175 a
(assoc name org-table-named-field-locations
))
3177 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
3179 (when (member name1 seen-fields
)
3180 (user-error "Several field/range formulas try to set %s" name1
))
3181 (push name1 seen-fields
)
3184 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
3187 (aref org-table-dlines
3188 (string-to-number (match-string 1 name
)))
3189 (error (user-error "Invalid row number in %s"
3191 (string-to-number (match-string 2 name
)))))
3192 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
3194 (org-table-message-once-per-second
3195 (and all log-last-time
)
3196 "Re-applying formula to field: %s" name
))
3197 (org-goto-line (nth 1 a
))
3198 (org-table-goto-column (nth 2 a
))
3199 (push (append a
(list (cdr eq
))) eqlname1
)
3200 (org-table-put-field-property :org-untouchable t
)))
3201 (setq eqlname1
(nreverse eqlname1
))
3203 ;; Now evaluate the column formulas, but skip fields covered
3204 ;; by field formulas
3206 (while (re-search-forward line-re end t
)
3207 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
3208 ;; Unprotected line, recalculate
3210 (and all
(setq log-last-time
3211 (org-table-message-once-per-second
3213 "Re-applying formulas to full table...(line %d)" cnt
)))
3214 (setq org-last-recalc-line
(org-current-line))
3216 (while (setq entry
(pop eql
))
3217 (org-goto-line org-last-recalc-line
)
3218 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
3219 (unless (get-text-property (point) :org-untouchable
)
3220 (org-table-eval-formula
3222 'noalign
'nocst
'nostore
'noanalysis
)))))
3224 ;; Now evaluate the field formulas
3225 (while (setq eq
(pop eqlname1
))
3227 (org-table-message-once-per-second
3228 (and all log-last-time
)
3229 "Re-applying formula to field: %s" (car eq
)))
3230 (org-goto-line (nth 1 eq
))
3231 (let ((column-target (nth 2 eq
)))
3232 (when (> column-target
1000)
3233 (user-error "Formula column target too large"))
3234 (let* ((column-count (progn (end-of-line)
3235 (1- (org-table-current-column))))
3237 (and (> column-target column-count
)
3238 (or (eq org-table-formula-create-columns t
)
3240 (eq org-table-formula-create-columns
'warn
)
3242 (org-display-warning
3243 "Out-of-bounds formula added columns")
3246 (eq org-table-formula-create-columns
'prompt
)
3248 "Out-of-bounds formula. Add columns?"))))))
3249 (org-table-goto-column column-target nil create-new-column
))
3251 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
3252 'nostore
'noanalysis
)))
3254 (org-goto-line thisline
)
3255 (org-table-goto-column thiscol
)
3256 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
3257 (or noalign
(and org-table-may-need-update
(org-table-align))
3258 (and all
(org-table-message-once-per-second
3260 "Re-applying formulas to %d lines...done" cnt
)))
3263 ;; back to initial position
3264 (org-table-message-once-per-second
3265 (and all log-first-time
)
3266 "Re-applying formulas...done")
3268 (org-goto-line thisline
)
3269 (org-table-goto-column thiscol
)
3270 (or noalign
(and org-table-may-need-update
(org-table-align)))))))
3273 (defun org-table-iterate (&optional arg
)
3274 "Recalculate the table until it does not change anymore.
3275 The maximum number of iterations is 10, but you can choose a different value
3276 with the prefix ARG."
3278 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
3280 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
3285 (org-table-recalculate 'all
)
3286 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
3287 (if (not (string= lasttbl thistbl
))
3288 (setq lasttbl thistbl
)
3290 (message "Convergence after %d iterations" i
)
3291 (message "Table was already stable"))
3293 (user-error "No convergence after %d iterations" i
))))
3296 (defun org-table-recalculate-buffer-tables ()
3297 "Recalculate all tables in the current buffer."
3302 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
3305 (defun org-table-iterate-buffer-tables ()
3306 "Iterate all tables in the buffer, to converge inter-table dependencies."
3310 (checksum (md5 (buffer-string)))
3318 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
3319 (if (equal checksum
(setq c1
(md5 (buffer-string))))
3321 (message "Convergence after %d iterations" (- imax i
))
3323 (setq checksum c1
)))
3324 (user-error "No convergence after %d iterations" imax
))))))
3326 (defun org-table-calc-current-TBLFM (&optional arg
)
3327 "Apply the #+TBLFM in the line at point to the table."
3329 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
3330 (let ((formula (buffer-substring
3335 ;; Insert a temporary formula at right after the table
3336 (goto-char (org-table-TBLFM-begin))
3337 (setq s
(set-marker (make-marker) (point)))
3338 (insert (concat formula
"\n"))
3339 (setq e
(set-marker (make-marker) (point)))
3340 ;; Recalculate the table
3341 (beginning-of-line 0) ; move to the inserted line
3342 (skip-chars-backward " \r\n\t")
3343 (if (org-at-table-p)
3345 (org-call-with-arg 'org-table-recalculate
(or arg t
))
3346 ;; delete the formula inserted temporarily
3347 (delete-region s e
))))))
3349 (defun org-table-TBLFM-begin ()
3350 "Find the beginning of the TBLFM lines and return its position.
3351 Return nil when the beginning of TBLFM line was not found."
3353 (when (progn (forward-line 1)
3355 org-table-TBLFM-begin-regexp
3359 (defun org-table-expand-lhs-ranges (equations)
3360 "Expand list of formulas.
3361 If some of the RHS in the formulas are ranges or a row reference, expand
3362 them to individual field equations for each field."
3363 (let (e res lhs rhs range r1 r2 c1 c2
)
3364 (while (setq e
(pop equations
))
3365 (setq lhs
(car e
) rhs
(cdr e
))
3367 ((string-match "^@-?[-+0-9]+\\$-?[0-9]+$" lhs
)
3368 ;; This just refers to one fixed field
3370 ((string-match "^[a-zA-Z][_a-zA-Z0-9]*$" lhs
)
3371 ;; This just refers to one fixed named field
3373 ((string-match "^@[0-9]+$" lhs
)
3374 (loop for ic from
1 to org-table-current-ncol do
3375 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
3376 (put-text-property 0 (length (caar res
))
3377 :orig-eqn e
(caar res
))))
3379 (setq range
(org-table-get-range lhs org-table-current-begin-pos
3381 (setq r1
(nth 0 range
) c1
(nth 1 range
)
3382 r2
(nth 2 range
) c2
(nth 3 range
))
3383 (setq r1
(org-table-line-to-dline r1
))
3384 (setq r2
(org-table-line-to-dline r2
'above
))
3385 (loop for ir from r1 to r2 do
3386 (loop for ic from c1 to c2 do
3387 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
3388 (put-text-property 0 (length (caar res
))
3389 :orig-eqn e
(caar res
)))))))
3392 (defun org-table-formula-handle-first/last-rc
(s)
3393 "Replace @<, @>, $<, $> with first/last row/column of the table.
3394 So @< and $< will always be replaced with @1 and $1, respectively.
3395 The advantage of these special markers are that structure editing of
3396 the table will not change them, while @1 and $1 will be modified
3397 when a line/row is swapped out of that privileged position. So for
3398 formulas that use a range of rows or columns, it may often be better
3399 to anchor the formula with \"I\" row markers, or to offset from the
3400 borders of the table using the @< @> $< $> makers."
3401 (let (n nmax len char
(start 0))
3402 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^\)]+)\\)"
3405 (setq start
(match-end 3))
3406 (setq nmax
(if (equal (match-string 1 s
) "@")
3407 (1- (length org-table-dlines
))
3408 org-table-current-ncol
)
3409 len
(- (match-end 2) (match-beginning 2))
3410 char
(string-to-char (match-string 2 s
))
3414 (if (or (< n
1) (> n nmax
))
3415 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3416 (match-string 0 s
) s
))
3417 (setq start
(match-beginning 0))
3418 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3421 (defun org-table-formula-substitute-names (f)
3422 "Replace $const with values in string F."
3423 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
3424 ;; First, check for column names
3425 (while (setq start
(string-match org-table-column-name-regexp f start
))
3426 (setq start
(1+ start
))
3427 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
3428 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
3429 ;; Parameters and constants
3431 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
3433 (setq start
(match-end 2))
3434 (setq start
(1+ start
))
3435 (if (setq a
(save-match-data
3436 (org-table-get-constant (match-string 1 f
))))
3437 (setq f
(replace-match
3438 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
3439 (if org-table-formula-debug
3440 (put-text-property 0 (length f
) :orig-formula f1 f
))
3443 (defun org-table-get-constant (const)
3444 "Find the value for a parameter or constant in a formula.
3445 Parameters get priority."
3446 (or (cdr (assoc const org-table-local-parameters
))
3447 (cdr (assoc const org-table-formula-constants-local
))
3448 (cdr (assoc const org-table-formula-constants
))
3449 (and (fboundp 'constants-get
) (constants-get const
))
3450 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3451 (org-entry-get nil
(substring const
5) 'inherit
))
3454 (defvar org-table-fedit-map
3455 (let ((map (make-sparse-keymap)))
3456 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3457 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3458 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3459 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3460 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3461 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3462 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3463 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3464 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3465 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3466 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3467 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3468 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3469 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3470 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3471 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3472 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3473 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3474 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3475 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3478 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3480 ["Finish and Install" org-table-fedit-finish t
]
3481 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3482 ["Abort" org-table-fedit-abort t
]
3484 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3485 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3487 "Shift Reference at Point"
3488 ["Up" org-table-fedit-ref-up t
]
3489 ["Down" org-table-fedit-ref-down t
]
3490 ["Left" org-table-fedit-ref-left t
]
3491 ["Right" org-table-fedit-ref-right t
]
3493 "Change Test Row for Column Formulas"
3494 ["Up" org-table-fedit-line-up t
]
3495 ["Down" org-table-fedit-line-down t
]
3497 ["Scroll Table Window" org-table-fedit-scroll t
]
3498 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3499 ["Show Table Grid" org-table-fedit-toggle-coordinates
3500 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3501 org-table-overlay-coordinates
)]
3503 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3504 :style toggle
:selected org-table-buffer-is-an
]))
3509 (defun org-table-edit-formulas ()
3510 "Edit the formulas of the current table in a separate buffer."
3512 (when (save-excursion (beginning-of-line 1) (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+TBLFM")))
3513 (beginning-of-line 0))
3514 (unless (org-at-table-p) (user-error "Not at a table"))
3515 (org-table-get-specials)
3516 (let ((key (org-table-current-field-formula 'key
'noerror
))
3517 (eql (sort (org-table-get-stored-formulas 'noerror
)
3518 'org-table-formula-less-p
))
3519 (pos (point-marker))
3521 (wc (current-window-configuration))
3522 (sel-win (selected-window))
3523 (titles '((column .
"# Column Formulas\n")
3524 (field .
"# Field and Range Formulas\n")
3525 (named .
"# Named Field Formulas\n")))
3527 (org-switch-to-buffer-other-window "*Edit Formulas*")
3529 ;; Keep global-font-lock-mode from turning on font-lock-mode
3530 (let ((font-lock-global-modes '(not fundamental-mode
)))
3532 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
3533 (org-set-local 'org-pos pos
)
3534 (org-set-local 'org-window-configuration wc
)
3535 (org-set-local 'org-selected-window sel-win
)
3536 (use-local-map org-table-fedit-map
)
3537 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3538 (easy-menu-add org-table-fedit-menu
)
3539 (setq startline
(org-current-line))
3540 (while (setq entry
(pop eql
))
3542 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3543 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3544 ((string-match "^[0-9]" (car entry
)) 'column
)
3546 (when (setq title
(assq type titles
))
3547 (or (bobp) (insert "\n"))
3548 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3549 (setq titles
(remove title titles
)))
3550 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3551 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3552 (car entry
) " = " (cdr entry
) "\n"))
3553 (remove-text-properties 0 (length s
) '(face nil
) s
)
3555 (if (eq org-table-use-standard-references t
)
3556 (org-table-fedit-toggle-ref-type))
3557 (org-goto-line startline
)
3558 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3560 (defun org-table-fedit-post-command ()
3561 (when (not (memq this-command
'(lisp-complete-symbol)))
3562 (let ((win (selected-window)))
3565 (org-table-show-reference)
3567 (select-window win
)))))
3569 (defun org-table-formula-to-user (s)
3570 "Convert a formula from internal to user representation."
3571 (if (eq org-table-use-standard-references t
)
3572 (org-table-convert-refs-to-an s
)
3575 (defun org-table-formula-from-user (s)
3576 "Convert a formula from user to internal representation."
3577 (if org-table-use-standard-references
3578 (org-table-convert-refs-to-rc s
)
3581 (defun org-table-convert-refs-to-rc (s)
3582 "Convert spreadsheet references from A7 to @7$28.
3583 Works for single references, but also for entire formulas and even the
3586 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3589 ;; format match, just advance
3590 (setq start
(match-end 0)))
3591 ((and (> (match-beginning 0) 0)
3592 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3593 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3594 ;; 3.e5 or something like this.
3595 (setq start
(match-end 0)))
3596 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3597 ;; (member (match-string 1 s)
3598 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3600 ;; function name, just advance
3601 (setq start
(match-end 0)))
3603 (setq start
(match-beginning 0)
3605 (if (equal (match-string 2 s
) "&")
3606 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3608 (string-to-number (match-string 2 s
))
3609 (org-letters-to-number (match-string 1 s
))))
3613 (defun org-table-convert-refs-to-an (s)
3614 "Convert spreadsheet references from to @7$28 to AB7.
3615 Works for single references, but also for entire formulas and even the
3617 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3618 (setq s
(replace-match
3620 (org-number-to-letters
3621 (string-to-number (match-string 2 s
)))
3622 (string-to-number (match-string 1 s
)))
3624 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3625 (setq s
(replace-match (concat "\\1"
3626 (org-number-to-letters
3627 (string-to-number (match-string 2 s
))) "&")
3631 (defun org-letters-to-number (s)
3632 "Convert a base 26 number represented by letters into an integer.
3633 For example: AB -> 28."
3636 (while (> (length s
) 0)
3637 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3641 (defun org-number-to-letters (n)
3642 "Convert an integer into a base 26 number represented by letters.
3643 For example: 28 -> AB."
3646 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3650 (defun org-table-time-string-to-seconds (s)
3651 "Convert a time string into numerical duration in seconds.
3652 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3653 If S is a string representing a number, keep this number."
3656 (let (hour minus min sec res
)
3658 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3659 (setq minus
(< 0 (length (match-string 1 s
)))
3660 hour
(string-to-number (match-string 2 s
))
3661 min
(string-to-number (match-string 3 s
))
3662 sec
(string-to-number (match-string 4 s
)))
3664 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3665 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3666 ((and (not (string-match org-ts-regexp-both s
))
3667 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3668 (setq minus
(< 0 (length (match-string 1 s
)))
3669 hour
(string-to-number (match-string 2 s
))
3670 min
(string-to-number (match-string 3 s
)))
3672 (setq res
(- (+ (* hour
3600) (* min
60))))
3673 (setq res
(+ (* hour
3600) (* min
60)))))
3674 (t (setq res
(string-to-number s
))))
3675 (number-to-string res
))))
3677 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3678 "Convert a number of seconds to a time string.
3679 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3680 minutes or seconds."
3681 (let* ((secs0 (abs secs
))
3683 (cond ((eq output-format
'days
)
3684 (format "%.3f" (/ (float secs0
) 86400)))
3685 ((eq output-format
'hours
)
3686 (format "%.2f" (/ (float secs0
) 3600)))
3687 ((eq output-format
'minutes
)
3688 (format "%.1f" (/ (float secs0
) 60)))
3689 ((eq output-format
'seconds
)
3690 (format "%d" secs0
))
3691 (t (org-format-seconds "%.2h:%.2m:%.2s" secs0
)))))
3692 (if (< secs
0) (concat "-" res
) res
)))
3694 (defun org-table-fedit-convert-buffer (function)
3695 "Convert all references in this buffer, using FUNCTION."
3696 (let ((line (org-current-line)))
3697 (goto-char (point-min))
3699 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3700 (delete-region (point) (point-at-eol))
3701 (or (eobp) (forward-char 1)))
3702 (org-goto-line line
)))
3704 (defun org-table-fedit-toggle-ref-type ()
3705 "Convert all references in the buffer from B3 to @3$2 and back."
3707 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3708 (org-table-fedit-convert-buffer
3709 (if org-table-buffer-is-an
3710 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3711 (message "Reference type switched to %s"
3712 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3714 (defun org-table-fedit-ref-up ()
3715 "Shift the reference at point one row/hline up."
3717 (org-table-fedit-shift-reference 'up
))
3718 (defun org-table-fedit-ref-down ()
3719 "Shift the reference at point one row/hline down."
3721 (org-table-fedit-shift-reference 'down
))
3722 (defun org-table-fedit-ref-left ()
3723 "Shift the reference at point one field to the left."
3725 (org-table-fedit-shift-reference 'left
))
3726 (defun org-table-fedit-ref-right ()
3727 "Shift the reference at point one field to the right."
3729 (org-table-fedit-shift-reference 'right
))
3731 (defun org-table-fedit-shift-reference (dir)
3733 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
3734 (if (memq dir
'(left right
))
3735 (org-rematch-and-replace 1 (eq dir
'left
))
3736 (user-error "Cannot shift reference in this direction")))
3737 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3738 ;; A B3-like reference
3739 (if (memq dir
'(up down
))
3740 (org-rematch-and-replace 2 (eq dir
'up
))
3741 (org-rematch-and-replace 1 (eq dir
'left
))))
3743 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3744 ;; An internal reference
3745 (if (memq dir
'(up down
))
3746 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3747 (org-rematch-and-replace 5 (eq dir
'left
))))))
3749 (defun org-rematch-and-replace (n &optional decr hline
)
3750 "Re-match the group N, and replace it with the shifted reference."
3751 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
3752 (goto-char (match-beginning n
))
3753 (and (looking-at (regexp-quote (match-string n
)))
3754 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3757 (defun org-table-shift-refpart (ref &optional decr hline
)
3758 "Shift a reference part REF.
3759 If DECR is set, decrease the references row/column, else increase.
3760 If HLINE is set, this may be a hline reference, it certainly is not
3761 a translation reference."
3763 (let* ((sign (string-match "^[-+]" ref
)) n
)
3765 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3767 ((and hline
(string-match "^I+" ref
))
3768 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3769 (setq n
(+ n
(if decr -
1 1)))
3770 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3772 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3774 (concat sign
(make-string n ?I
)))
3776 ((string-match "^[0-9]+" ref
)
3777 (setq n
(string-to-number (concat sign ref
)))
3778 (setq n
(+ n
(if decr -
1 1)))
3780 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3781 (number-to-string (max 1 n
))))
3783 ((string-match "^[a-zA-Z]+" ref
)
3784 (org-number-to-letters
3785 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3787 (t (user-error "Cannot shift reference"))))))
3789 (defun org-table-fedit-toggle-coordinates ()
3790 "Toggle the display of coordinates in the referenced table."
3792 (let ((pos (marker-position org-pos
)))
3793 (with-current-buffer (marker-buffer org-pos
)
3796 (org-table-toggle-coordinate-overlays)))))
3798 (defun org-table-fedit-finish (&optional arg
)
3799 "Parse the buffer for formula definitions and install them.
3800 With prefix ARG, apply the new formulas to the table."
3802 (org-table-remove-rectangle-highlight)
3803 (if org-table-use-standard-references
3805 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3806 (setq org-table-buffer-is-an nil
)))
3807 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3808 (goto-char (point-min))
3809 (while (re-search-forward
3810 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3812 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3813 form
(match-string 3))
3814 (setq form
(org-trim form
))
3815 (when (not (equal form
""))
3816 (while (string-match "[ \t]*\n[ \t]*" form
)
3817 (setq form
(replace-match " " t t form
)))
3818 (when (assoc var eql
)
3819 (user-error "Double formulas for %s" var
))
3820 (push (cons var form
) eql
)))
3822 (set-window-configuration org-window-configuration
)
3823 (select-window sel-win
)
3825 (unless (org-at-table-p)
3826 (user-error "Lost table position - cannot install formulas"))
3827 (org-table-store-formulas eql
)
3828 (move-marker pos nil
)
3829 (kill-buffer "*Edit Formulas*")
3831 (org-table-recalculate 'all
)
3832 (message "New formulas installed - press C-u C-c C-c to apply."))))
3834 (defun org-table-fedit-abort ()
3835 "Abort editing formulas, without installing the changes."
3837 (org-table-remove-rectangle-highlight)
3838 (let ((pos org-pos
) (sel-win org-selected-window
))
3839 (set-window-configuration org-window-configuration
)
3840 (select-window sel-win
)
3842 (move-marker pos nil
)
3843 (message "Formula editing aborted without installing changes")))
3845 (defun org-table-fedit-lisp-indent ()
3846 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3848 (let ((pos (point)) beg end ind
)
3849 (beginning-of-line 1)
3851 ((looking-at "[ \t]")
3853 (call-interactively 'lisp-indent-line
))
3854 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3855 ((not (fboundp 'pp-buffer
))
3856 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3857 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3858 (goto-char (- (match-end 0) 2))
3860 (setq ind
(make-string (current-column) ?\
))
3861 (condition-case nil
(forward-sexp 1)
3863 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3866 (narrow-to-region beg end
)
3867 (if (eq last-command this-command
)
3869 (goto-char (point-min))
3870 (setq this-command nil
)
3871 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3872 (replace-match " ")))
3874 (untabify (point-min) (point-max))
3875 (goto-char (1+ (point-min)))
3876 (while (re-search-forward "^." nil t
)
3877 (beginning-of-line 1)
3879 (goto-char (point-max))
3880 (org-delete-backward-char 1)))
3884 (defvar org-show-positions nil
)
3886 (defun org-table-show-reference (&optional local
)
3887 "Show the location/value of the $ expression at point."
3889 (org-table-remove-rectangle-highlight)
3891 (let ((pos (if local
(point) org-pos
))
3893 (org-inhibit-highlight-removal t
)
3894 (win (selected-window))
3895 (org-show-positions nil
)
3896 var name e what match dest
)
3897 (if local
(org-table-get-specials))
3899 ((org-in-regexp "^@[0-9]+[ \t=]")
3900 (setq match
(concat (substring (match-string 0) 0 -
1)
3902 (substring (match-string 0) 0 -
1)
3905 ((or (org-in-regexp org-table-range-regexp2
)
3906 (org-in-regexp org-table-translate-regexp
)
3907 (org-in-regexp org-table-range-regexp
))
3910 (org-table-convert-refs-to-rc (match-string 0))))
3912 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3913 ((org-in-regexp "\\$[0-9]+") 'column
)
3915 (t (user-error "No reference at point")))
3916 match
(and what
(or match
(match-string 0))))
3917 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3918 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3919 'secondary-selection
))
3920 (org-add-hook 'before-change-functions
3921 'org-table-remove-rectangle-highlight
)
3922 (if (eq what
'name
) (setq var
(substring match
1)))
3923 (when (eq what
'range
)
3924 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3925 (setq match
(org-table-formula-substitute-names match
)))
3929 (re-search-backward "^\\S-" nil t
)
3930 (beginning-of-line 1)
3931 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3934 (org-table-convert-refs-to-rc (match-string 1))))
3935 (org-table-add-rectangle-overlay
3936 (match-beginning 1) (match-end 1) face2
))))
3937 (if (and (markerp pos
) (marker-buffer pos
))
3938 (if (get-buffer-window (marker-buffer pos
))
3939 (select-window (get-buffer-window (marker-buffer pos
)))
3940 (org-switch-to-buffer-other-window (get-buffer-window
3941 (marker-buffer pos
)))))
3943 (org-table-force-dataline)
3945 (setq name
(substring dest
1))
3947 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3948 (setq e
(assoc name org-table-named-field-locations
))
3949 (org-goto-line (nth 1 e
))
3950 (org-table-goto-column (nth 2 e
)))
3951 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3952 (let ((l (string-to-number (match-string 1 dest
)))
3953 (c (string-to-number (match-string 2 dest
))))
3954 (org-goto-line (aref org-table-dlines l
))
3955 (org-table-goto-column c
)))
3956 (t (org-table-goto-column (string-to-number name
))))
3957 (move-marker pos
(point))
3958 (org-table-highlight-rectangle nil nil face2
))
3960 ((equal dest match
))
3965 (org-table-get-range match nil nil
'highlight
))
3967 ((setq e
(assoc var org-table-named-field-locations
))
3968 (org-goto-line (nth 1 e
))
3969 (org-table-goto-column (nth 2 e
))
3970 (org-table-highlight-rectangle (point) (point))
3971 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3972 ((setq e
(assoc var org-table-column-names
))
3973 (org-table-goto-column (string-to-number (cdr e
)))
3974 (org-table-highlight-rectangle (point) (point))
3975 (goto-char (org-table-begin))
3976 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3979 (goto-char (match-beginning 1))
3980 (org-table-highlight-rectangle)
3981 (message "Named column (column %s)" (cdr e
)))
3982 (user-error "Column name not found")))
3985 (org-table-goto-column (string-to-number (substring match
1)))
3986 (org-table-highlight-rectangle (point) (point))
3987 (message "Column %s" (substring match
1)))
3988 ((setq e
(assoc var org-table-local-parameters
))
3989 (goto-char (org-table-begin))
3990 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3992 (goto-char (match-beginning 1))
3993 (org-table-highlight-rectangle)
3994 (message "Local parameter."))
3995 (user-error "Parameter not found")))
3998 ((not var
) (user-error "No reference at point"))
3999 ((setq e
(assoc var org-table-formula-constants-local
))
4000 (message "Local Constant: $%s=%s in #+CONSTANTS line."
4002 ((setq e
(assoc var org-table-formula-constants
))
4003 (message "Constant: $%s=%s in `org-table-formula-constants'."
4005 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
4006 (message "Constant: $%s=%s, from `constants.el'%s."
4007 var e
(format " (%s units)" constants-unit-system
)))
4008 (t (user-error "Undefined name $%s" var
)))))
4010 (when (and org-show-positions
4011 (not (memq this-command
'(org-table-fedit-scroll
4012 org-table-fedit-scroll-down
))))
4013 (push pos org-show-positions
)
4014 (push org-table-current-begin-pos org-show-positions
)
4015 (let ((min (apply 'min org-show-positions
))
4016 (max (apply 'max org-show-positions
)))
4017 (set-window-start (selected-window) min
)
4019 (or (pos-visible-in-window-p max
)
4020 (set-window-start (selected-window) max
))))
4021 (select-window win
))))
4023 (defun org-table-force-dataline ()
4024 "Make sure the cursor is in a dataline in a table."
4025 (unless (save-excursion
4026 (beginning-of-line 1)
4027 (looking-at org-table-dataline-regexp
))
4028 (let* ((re org-table-dataline-regexp
)
4029 (p1 (save-excursion (re-search-forward re nil
'move
)))
4030 (p2 (save-excursion (re-search-backward re nil
'move
))))
4032 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
4034 ((or p1 p2
) (goto-char (or p1 p2
)))
4035 (t (user-error "No table dataline around here"))))))
4037 (defun org-table-fedit-line-up ()
4038 "Move cursor one line up in the window showing the table."
4040 (org-table-fedit-move 'previous-line
))
4042 (defun org-table-fedit-line-down ()
4043 "Move cursor one line down in the window showing the table."
4045 (org-table-fedit-move 'next-line
))
4047 (defun org-table-fedit-move (command)
4048 "Move the cursor in the window showing the table.
4049 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
4050 (let ((org-table-allow-automatic-line-recalculation nil
)
4051 (pos org-pos
) (win (selected-window)) p
)
4052 (select-window (get-buffer-window (marker-buffer org-pos
)))
4054 (call-interactively command
)
4055 (while (and (org-at-table-p)
4056 (org-at-table-hline-p))
4057 (call-interactively command
))
4058 (or (org-at-table-p) (goto-char p
))
4059 (move-marker pos
(point))
4060 (select-window win
)))
4062 (defun org-table-fedit-scroll (N)
4064 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
4065 (scroll-other-window N
)))
4067 (defun org-table-fedit-scroll-down (N)
4069 (org-table-fedit-scroll (- N
)))
4071 (defvar org-table-rectangle-overlays nil
)
4073 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
4074 "Add a new overlay."
4075 (let ((ov (make-overlay beg end
)))
4076 (overlay-put ov
'face
(or face
'secondary-selection
))
4077 (push ov org-table-rectangle-overlays
)))
4079 (defun org-table-highlight-rectangle (&optional beg end face
)
4080 "Highlight rectangular region in a table."
4081 (setq beg
(or beg
(point)) end
(or end
(point)))
4082 (let ((b (min beg end
))
4085 (and (boundp 'org-show-positions
)
4086 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
4087 (goto-char (min beg end
))
4088 (setq l1
(org-current-line)
4089 c1
(org-table-current-column))
4090 (goto-char (max beg end
))
4091 (setq l2
(org-current-line)
4092 c2
(org-table-current-column))
4093 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
4095 (beginning-of-line 1)
4096 (loop for line from l1 to l2 do
4097 (when (looking-at org-table-dataline-regexp
)
4098 (org-table-goto-column c1
)
4099 (skip-chars-backward "^|\n") (setq beg
(point))
4100 (org-table-goto-column c2
)
4101 (skip-chars-forward "^|\n") (setq end
(point))
4102 (org-table-add-rectangle-overlay beg end face
))
4103 (beginning-of-line 2))
4105 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
4107 (defun org-table-remove-rectangle-highlight (&rest ignore
)
4108 "Remove the rectangle overlays."
4109 (unless org-inhibit-highlight-removal
4110 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
4111 (mapc 'delete-overlay org-table-rectangle-overlays
)
4112 (setq org-table-rectangle-overlays nil
)))
4114 (defvar org-table-coordinate-overlays nil
4115 "Collects the coordinate grid overlays, so that they can be removed.")
4116 (make-variable-buffer-local 'org-table-coordinate-overlays
)
4118 (defun org-table-overlay-coordinates ()
4119 "Add overlays to the table at point, to show row/column coordinates."
4121 (mapc 'delete-overlay org-table-coordinate-overlays
)
4122 (setq org-table-coordinate-overlays nil
)
4124 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
4125 (goto-char (org-table-begin))
4126 (while (org-at-table-p)
4127 (setq eol
(point-at-eol))
4128 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
4129 (push ov org-table-coordinate-overlays
)
4130 (setq hline
(looking-at org-table-hline-regexp
))
4131 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
4132 (format "%4d" (setq id
(1+ id
)))))
4133 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
4136 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
4137 (setq beg
(1+ (match-beginning 0))
4139 s1
(concat "$" (int-to-string ic
))
4140 s2
(org-number-to-letters ic
)
4141 str
(if (eq org-table-use-standard-references t
) s2 s1
))
4142 (setq ov
(make-overlay beg
(+ beg
(length str
))))
4143 (push ov org-table-coordinate-overlays
)
4144 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
4145 (beginning-of-line 2)))))
4148 (defun org-table-toggle-coordinate-overlays ()
4149 "Toggle the display of Row/Column numbers in tables."
4151 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
4152 (message "Tables Row/Column numbers display turned %s"
4153 (if org-table-overlay-coordinates
"on" "off"))
4154 (if (and (org-at-table-p) org-table-overlay-coordinates
)
4156 (unless org-table-overlay-coordinates
4157 (mapc 'delete-overlay org-table-coordinate-overlays
)
4158 (setq org-table-coordinate-overlays nil
)))
4161 (defun org-table-toggle-formula-debugger ()
4162 "Toggle the formula debugger in tables."
4164 (setq org-table-formula-debug
(not org-table-formula-debug
))
4165 (message "Formula debugging has been turned %s"
4166 (if org-table-formula-debug
"on" "off")))
4168 ;;; The orgtbl minor mode
4170 ;; Define a minor mode which can be used in other modes in order to
4171 ;; integrate the org-mode table editor.
4173 ;; This is really a hack, because the org-mode table editor uses several
4174 ;; keys which normally belong to the major mode, for example the TAB and
4175 ;; RET keys. Here is how it works: The minor mode defines all the keys
4176 ;; necessary to operate the table editor, but wraps the commands into a
4177 ;; function which tests if the cursor is currently inside a table. If that
4178 ;; is the case, the table editor command is executed. However, when any of
4179 ;; those keys is used outside a table, the function uses `key-binding' to
4180 ;; look up if the key has an associated command in another currently active
4181 ;; keymap (minor modes, major mode, global), and executes that command.
4182 ;; There might be problems if any of the keys used by the table editor is
4183 ;; otherwise used as a prefix key.
4185 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4186 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4187 ;; addresses this by checking explicitly for both bindings.
4189 ;; The optimized version (see variable `orgtbl-optimized') takes over
4190 ;; all keys which are bound to `self-insert-command' in the *global map*.
4191 ;; Some modes bind other commands to simple characters, for example
4192 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4193 ;; active, this binding is ignored inside tables and replaced with a
4194 ;; modified self-insert.
4197 (defvar orgtbl-mode-map
(make-keymap)
4198 "Keymap for `orgtbl-mode'.")
4200 (defvar org-old-auto-fill-inhibit-regexp nil
4201 "Local variable used by `orgtbl-mode'.")
4203 (defconst orgtbl-line-start-regexp
4204 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4205 "Matches a line belonging to an orgtbl.")
4207 (defconst orgtbl-extra-font-lock-keywords
4208 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4209 0 (quote 'org-table
) 'prepend
))
4210 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4212 ;; Install it as a minor mode.
4213 (put 'orgtbl-mode
:included t
)
4214 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4217 (define-minor-mode orgtbl-mode
4218 "The `org-mode' table editor as a minor mode for use in other modes."
4219 :lighter
" OrgTbl" :keymap orgtbl-mode-map
4220 (org-load-modules-maybe)
4222 ((derived-mode-p 'org-mode
)
4223 ;; Exit without error, in case some hook functions calls this
4224 ;; by accident in org-mode.
4225 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
4227 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
4228 ;; Make sure we are first in minor-mode-map-alist
4229 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
4230 ;; FIXME: maybe it should use emulation-mode-map-alists?
4231 (and c
(setq minor-mode-map-alist
4232 (cons c
(delq c minor-mode-map-alist
)))))
4233 (org-set-local (quote org-table-may-need-update
) t
)
4234 (org-add-hook 'before-change-functions
'org-before-change-function
4236 (org-set-local 'org-old-auto-fill-inhibit-regexp
4237 auto-fill-inhibit-regexp
)
4238 (org-set-local 'auto-fill-inhibit-regexp
4239 (if auto-fill-inhibit-regexp
4240 (concat orgtbl-line-start-regexp
"\\|"
4241 auto-fill-inhibit-regexp
)
4242 orgtbl-line-start-regexp
))
4243 (add-to-invisibility-spec '(org-cwidth))
4244 (when (fboundp 'font-lock-add-keywords
)
4245 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
4246 (org-restart-font-lock))
4247 (easy-menu-add orgtbl-mode-menu
))
4249 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
4250 (org-table-cleanup-narrow-column-properties)
4251 (org-remove-from-invisibility-spec '(org-cwidth))
4252 (remove-hook 'before-change-functions
'org-before-change-function t
)
4253 (when (fboundp 'font-lock-remove-keywords
)
4254 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
4255 (org-restart-font-lock))
4256 (easy-menu-remove orgtbl-mode-menu
)
4257 (force-mode-line-update 'all
))))
4259 (defun org-table-cleanup-narrow-column-properties ()
4260 "Remove all properties related to narrow-column invisibility."
4261 (let ((s (point-min)))
4262 (while (setq s
(text-property-any s
(point-max)
4263 'display org-narrow-column-arrow
))
4264 (remove-text-properties s
(1+ s
) '(display t
)))
4265 (setq s
(point-min))
4266 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
4267 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
4268 (setq s
(point-min))
4269 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
4270 (remove-text-properties s
(1+ s
) '(invisible t
)))))
4272 (defun orgtbl-make-binding (fun n
&rest keys
)
4273 "Create a function for binding in the table minor mode.
4274 FUN is the command to call inside a table. N is used to create a unique
4275 command name. KEYS are keys that should be checked in for a command
4276 to execute outside of tables."
4279 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
4281 (concat "In tables, run `" (symbol-name fun
) "'.\n"
4282 "Outside of tables, run the binding of `"
4283 (mapconcat #'key-description keys
"' or `")
4288 (list 'call-interactively
(list 'quote fun
))
4289 (list 'let
'(orgtbl-mode)
4290 (list 'call-interactively
4293 (list 'key-binding k
))
4295 '('orgtbl-error
))))))))
4297 (defun orgtbl-error ()
4298 "Error when there is no default binding for a table key."
4300 (user-error "This key has no function outside tables"))
4302 (defun orgtbl-setup ()
4303 "Setup orgtbl keymaps."
4306 '(([(meta shift left
)] org-table-delete-column
)
4307 ([(meta left
)] org-table-move-column-left
)
4308 ([(meta right
)] org-table-move-column-right
)
4309 ([(meta shift right
)] org-table-insert-column
)
4310 ([(meta shift up
)] org-table-kill-row
)
4311 ([(meta shift down
)] org-table-insert-row
)
4312 ([(meta up
)] org-table-move-row-up
)
4313 ([(meta down
)] org-table-move-row-down
)
4314 ("\C-c\C-w" org-table-cut-region
)
4315 ("\C-c\M-w" org-table-copy-region
)
4316 ("\C-c\C-y" org-table-paste-rectangle
)
4317 ("\C-c\C-w" org-table-wrap-region
)
4318 ("\C-c-" org-table-insert-hline
)
4319 ("\C-c}" org-table-toggle-coordinate-overlays
)
4320 ("\C-c{" org-table-toggle-formula-debugger
)
4321 ("\C-m" org-table-next-row
)
4322 ([(shift return
)] org-table-copy-down
)
4323 ("\C-c?" org-table-field-info
)
4324 ("\C-c " org-table-blank-field
)
4325 ("\C-c+" org-table-sum
)
4326 ("\C-c=" org-table-eval-formula
)
4327 ("\C-c'" org-table-edit-formulas
)
4328 ("\C-c`" org-table-edit-field
)
4329 ("\C-c*" org-table-recalculate
)
4330 ("\C-c^" org-table-sort-lines
)
4331 ("\M-a" org-table-beginning-of-field
)
4332 ("\M-e" org-table-end-of-field
)
4333 ([(control ?
#)] org-table-rotate-recalc-marks
)))
4335 (while (setq elt
(pop bindings
))
4336 (setq nfunc
(1+ nfunc
))
4337 (setq key
(org-key (car elt
))
4339 cmd
(orgtbl-make-binding fun nfunc key
))
4340 (org-defkey orgtbl-mode-map key cmd
))
4342 ;; Special treatment needed for TAB and RET
4343 (org-defkey orgtbl-mode-map
[(return)]
4344 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
4345 (org-defkey orgtbl-mode-map
"\C-m"
4346 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
4348 (org-defkey orgtbl-mode-map
[(tab)]
4349 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
4350 (org-defkey orgtbl-mode-map
"\C-i"
4351 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
4353 (org-defkey orgtbl-mode-map
[(shift tab
)]
4354 (orgtbl-make-binding 'org-table-previous-field
104
4355 [(shift tab
)] [(tab)] "\C-i"))
4358 (unless (featurep 'xemacs
)
4359 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
4360 (orgtbl-make-binding 'org-table-previous-field
107
4361 [S-iso-lefttab
] [backtab] [(shift tab)]
4364 (org-defkey orgtbl-mode-map [backtab]
4365 (orgtbl-make-binding 'org-table-previous-field
108
4366 [backtab] [S-iso-lefttab] [(shift tab)]
4369 (org-defkey orgtbl-mode-map "\M-\C-m"
4370 (orgtbl-make-binding 'org-table-wrap-region 105
4371 "\M-\C-m" [(meta return)]))
4372 (org-defkey orgtbl-mode-map [(meta return)]
4373 (orgtbl-make-binding 'org-table-wrap-region 106
4374 [(meta return)] "\M-\C-m"))
4376 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
4377 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
4379 (when orgtbl-optimized
4380 ;; If the user wants maximum table support, we need to hijack
4381 ;; some standard editing functions
4382 (org-remap orgtbl-mode-map
4383 'self-insert-command 'orgtbl-self-insert-command
4384 'delete-char 'org-delete-char
4385 'delete-backward-char 'org-delete-backward-char)
4386 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
4387 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
4389 ["Create or convert" org-table-create-or-convert-from-region
4390 :active (not (org-at-table-p)) :keys "C-c |" ]
4392 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
4393 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
4394 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
4395 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
4397 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
4398 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
4399 ["Copy Field from Above"
4400 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
4403 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
4404 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
4405 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
4406 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
4408 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
4409 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
4410 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
4411 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
4412 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
4414 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
4416 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
4417 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
4418 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
4419 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
4422 ["Insert table template" orgtbl-insert-radio-table
4423 (assq major-mode orgtbl-radio-table-templates)]
4424 ["Comment/uncomment table" orgtbl-toggle-comment t])
4426 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
4427 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
4428 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
4429 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
4430 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
4431 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
4432 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
4433 ["Sum Column/Rectangle" org-table-sum
4434 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
4435 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
4437 org-table-toggle-formula-debugger :active (org-at-table-p)
4439 :style toggle :selected org-table-formula-debug]
4440 ["Show Col/Row Numbers"
4441 org-table-toggle-coordinate-overlays :active (org-at-table-p)
4443 :style toggle :selected org-table-overlay-coordinates]
4446 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
4447 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
4450 (defun orgtbl-ctrl-c-ctrl-c (arg)
4451 "If the cursor is inside a table, realign the table.
4452 If it is a table to be sent away to a receiver, do it.
4453 With prefix arg, also recompute table."
4455 (let ((case-fold-search t) (pos (point)) action)
4457 (beginning-of-line 1)
4459 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
4460 ((looking-at "[ \t]*|") pos)
4461 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
4465 (org-table-maybe-eval-formula)
4467 (call-interactively 'org-table-recalculate)
4468 (org-table-maybe-recalculate-line))
4469 (call-interactively 'org-table-align)
4470 (when (orgtbl-send-table 'maybe)
4471 (run-hooks 'orgtbl-after-send-table-hook)))
4472 ((eq action 'recalc)
4474 (beginning-of-line 1)
4475 (skip-chars-backward " \r\n\t")
4476 (if (org-at-table-p)
4477 (org-call-with-arg 'org-table-recalculate t))))
4478 (t (let (orgtbl-mode)
4479 (call-interactively (key-binding "\C-c\C-c")))))))
4481 (defun orgtbl-create-or-convert-from-region (arg)
4482 "Create table or convert region to table, if no conflicting binding.
4483 This installs the table binding `C-c |', but only if there is no
4484 conflicting binding to this key outside orgtbl-mode."
4486 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
4488 (call-interactively cmd)
4489 (call-interactively 'org-table-create-or-convert-from-region))))
4491 (defun orgtbl-tab (arg)
4492 "Justification and field motion for `orgtbl-mode'."
4494 (if arg (org-table-edit-field t)
4495 (org-table-justify-field-maybe)
4496 (org-table-next-field)))
4498 (defun orgtbl-ret ()
4499 "Justification and field motion for `orgtbl-mode'."
4503 (org-table-justify-field-maybe)
4504 (org-table-next-row)))
4506 (defun orgtbl-self-insert-command (N)
4507 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
4508 If the cursor is in a table looking at whitespace, the whitespace is
4509 overwritten, and the table is not marked as requiring realignment."
4511 (if (and (org-at-table-p)
4513 (and org-table-auto-blank-field
4514 (member last-command
4515 '(orgtbl-hijacker-command-100
4516 orgtbl-hijacker-command-101
4517 orgtbl-hijacker-command-102
4518 orgtbl-hijacker-command-103
4519 orgtbl-hijacker-command-104
4520 orgtbl-hijacker-command-105
4522 (org-table-blank-field))
4525 (looking-at "[^|\n]* +|"))
4526 (let (org-table-may-need-update)
4527 (goto-char (1- (match-end 0)))
4528 (org-delete-backward-char 1)
4529 (goto-char (match-beginning 0))
4530 (self-insert-command N))
4531 (setq org-table-may-need-update t)
4534 (cmd (or (key-binding
4535 (or (and (listp function-key-map)
4536 (setq a (assoc last-input-event function-key-map))
4538 (vector last-input-event)))
4539 'self-insert-command)))
4540 (call-interactively cmd)
4541 (if (and org-self-insert-cluster-for-undo
4542 (eq cmd 'self-insert-command))
4543 (if (not (eq last-command 'orgtbl-self-insert-command))
4544 (setq org-self-insert-command-undo-counter 1)
4545 (if (>= org-self-insert-command-undo-counter 20)
4546 (setq org-self-insert-command-undo-counter 1)
4547 (and (> org-self-insert-command-undo-counter 0)
4549 (not (cadr buffer-undo-list)) ; remove nil entry
4550 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4551 (setq org-self-insert-command-undo-counter
4552 (1+ org-self-insert-command-undo-counter))))))))
4554 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4555 "Regular expression matching exponentials as produced by calc.")
4557 (defun orgtbl-gather-send-defs ()
4558 "Gather a plist of :name, :transform, :params for each destination before
4561 (goto-char (org-table-begin))
4563 (beginning-of-line 0)
4564 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4565 (let ((name (org-no-properties (match-string 1)))
4566 (transform (intern (match-string 2)))
4567 (params (if (match-end 3)
4568 (read (concat "(" (match-string 3) ")")))))
4569 (push (list :name name :transform transform :params params)
4571 (beginning-of-line 0)))
4574 (defun orgtbl-send-replace-tbl (name txt)
4575 "Find and replace table NAME with TXT."
4577 (goto-char (point-min))
4578 (unless (re-search-forward
4579 (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4580 (user-error "Don't know where to insert translated table"))
4581 (let ((beg (line-beginning-position 2)))
4582 (unless (re-search-forward
4583 (concat "END +RECEIVE +ORGTBL +" name) nil t)
4584 (user-error "Cannot find end of insertion region"))
4586 (delete-region beg (point)))
4590 (defun org-table-to-lisp (&optional txt)
4591 "Convert the table at point to a Lisp structure.
4592 The structure will be a list. Each item is either the symbol `hline'
4593 for a horizontal separator line, or a list of field values as strings.
4594 The table is taken from the parameter TXT, or from the buffer at point."
4595 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
4597 (buffer-substring-no-properties (org-table-begin)
4600 (if (string-match org-table-hline-regexp x) 'hline
4601 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4602 (org-split-string txt "[ \t]*\n[ \t]*"))))
4604 (defun orgtbl-send-table (&optional maybe)
4605 "Send a transformed version of table at point to the receiver position.
4606 With argument MAYBE, fail quietly if no transformation is defined
4610 (unless (org-at-table-p) (user-error "Not at a table"))
4611 ;; when non-interactive, we assume align has just happened.
4612 (when (org-called-interactively-p 'any) (org-table-align))
4613 (let ((dests (orgtbl-gather-send-defs))
4614 (table (org-table-to-lisp
4615 (buffer-substring-no-properties (org-table-begin)
4619 (if maybe (throw 'exit nil)
4620 (user-error "Don't know how to transform this table")))
4621 (dolist (dest dests)
4622 (let ((name (plist-get dest :name))
4623 (transform (plist-get dest :transform))
4624 (params (plist-get dest :params)))
4625 (unless (fboundp transform)
4626 (user-error "No such transformation function %s" transform))
4627 (orgtbl-send-replace-tbl name (funcall transform table params)))
4629 (message "Table converted and installed at %d receiver location%s"
4630 ntbl (if (> ntbl 1) "s" ""))
4631 (and (> ntbl 0) ntbl))))
4633 (defun org-remove-by-index (list indices &optional i0)
4634 "Remove the elements in LIST with indices in INDICES.
4635 First element has index 0, or I0 if given."
4638 (if (integerp indices) (setq indices (list indices)))
4639 (setq i0 (1- (or i0 0)))
4640 (delq :rm (mapcar (lambda (x)
4642 (if (memq i0 indices) :rm x))
4645 (defun orgtbl-toggle-comment ()
4646 "Comment or uncomment the orgtbl at point."
4648 (let* ((case-fold-search t)
4649 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4650 (re2 (concat "^" orgtbl-line-start-regexp))
4651 (commented (save-excursion (beginning-of-line 1)
4652 (cond ((looking-at re1) t)
4653 ((looking-at re2) nil)
4654 (t (user-error "Not at an org table")))))
4655 (re (if commented re1 re2))
4658 (beginning-of-line 1)
4659 (while (looking-at re) (beginning-of-line 0))
4660 (beginning-of-line 2)
4662 (while (looking-at re) (beginning-of-line 2))
4664 (comment-region beg end (if commented '(4) nil))))
4666 (defun orgtbl-insert-radio-table ()
4667 "Insert a radio table template appropriate for this major mode."
4669 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4672 (unless e (user-error "No radio table setup defined for %s" major-mode))
4673 (setq name (read-string "Table name: "))
4674 (while (string-match "%n" txt)
4675 (setq txt (replace-match name t t txt)))
4676 (or (bolp) (insert "\n"))
4682 (defun orgtbl-to-generic (table params)
4683 "Convert the orgtbl-mode TABLE to some other format.
4685 This generic routine can be used for many standard cases.
4687 TABLE is a list, each entry either the symbol `hline' for
4688 a horizontal separator line, or a list of fields for that
4689 line. PARAMS is a property list of parameters that can
4690 influence the conversion.
4692 Valid parameters are:
4696 Export back-end used as a basis to transcode elements of the
4697 table, when no specific parameter applies to it. It is also
4698 used to translate cells contents. You can prevent this by
4699 setting :raw property to a non-nil value.
4703 When non-nil, only convert rows, not the table itself. This is
4704 equivalent to setting to the empty string both :tstart
4705 and :tend, which see.
4709 When set to an integer N, skip the first N lines of the table.
4710 Horizontal separation lines do count for this parameter!
4714 List of columns that should be skipped. If the table has
4715 a column with calculation marks, that column is automatically
4716 discarded beforehand.
4720 String to be inserted on horizontal separation lines. May be
4721 nil to ignore these lines altogether.
4725 Separator between two fields, as a string.
4727 Each in the following group may be either a string or a function
4728 of no arguments returning a string:
4732 Strings to start and end the table. Ignored when :splice is t.
4736 Strings to start and end a new table line.
4740 Strings to start and end the last table line. Default,
4741 respectively, to :lstart and :lend.
4743 Each in the following group may be a string or a function of one
4744 argument (either the cells in the current row, as a list of
4745 strings, or the current cell) returning a string:
4749 Format string for an entire row, with enough %s to capture all
4750 fields. When non-nil, :lstart, :lend, and :sep are ignored.
4754 Format for the entire last line, defaults to :lfmt.
4758 A format to be used to wrap the field, should contain %s for
4759 the original field value. For example, to wrap everything in
4760 dollars, you could use :fmt \"$%s$\". This may also be
4761 a property list with column numbers and format strings, or
4764 \(:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
4766 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
4768 Same as above, specific for the header lines in the table.
4769 All lines before the first hline are treated as header. If
4770 any of these is not present, the data line value is used.
4772 This may be either a string or a function of two arguments:
4776 Use this format to print numbers with exponential. The format
4777 should have %s twice for inserting mantissa and exponent, for
4778 example \"%s\\\\times10^{%s}\". This may also be a property
4779 list with column numbers and format strings or functions.
4780 :fmt will still be applied after :efmt."
4781 (let ((backend (plist-get params :backend))
4782 ;; Disable user-defined export filters and hooks.
4783 (org-export-filters-alist nil)
4784 (org-export-before-parsing-hook nil)
4785 (org-export-before-processing-hook nil))
4786 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
4787 (user-error "Unknown :backend value"))
4788 (when (or (not backend) (plist-get params :raw)) (require 'ox-org))
4790 (org-export-string-as
4791 ;; Return TABLE as Org syntax. Tolerate non-string cells.
4792 (with-output-to-string
4794 (cond ((eq e 'hline) (princ "|--\n"))
4796 (princ "| ") (dolist (c e) (princ c) (princ " |"))
4798 ;; Build a custom back-end according to PARAMS. Before defining
4799 ;; a translator, check if there is anything to do. When there
4800 ;; isn't, let BACKEND handle the element.
4801 (org-export-create-backend
4802 :parent (or backend 'org)
4804 '((:filter-parse-tree
4805 ;; Handle :skip parameter.
4806 (lambda (tree backend info)
4807 (let ((skip (plist-get info :skip)))
4809 (unless (wholenump skip) (user-error "Wrong :skip value"))
4811 (org-element-map tree 'table-row
4814 (org-element-extract-element row)
4819 ;; Handle :skipcols parameter.
4820 (lambda (tree backend info)
4821 (let ((skipcols (plist-get info :skipcols)))
4823 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
4824 (org-element-map tree 'table
4827 (org-export-table-has-special-column-p table)))
4828 (dolist (row (org-element-contents table))
4829 (when (eq (org-element-property :type row) 'standard)
4831 (dolist (cell (nthcdr (if specialp 1 0)
4832 (org-element-contents row)))
4833 (when (memq c skipcols)
4834 (org-element-extract-element cell))
4839 `((table . ,(org-table--to-generic-table params))
4840 (table-row . ,(org-table--to-generic-row params))
4841 (table-cell . ,(org-table--to-generic-cell params))
4842 ;; Section. Return contents to avoid garbage around table.
4843 (section . (lambda (s c i) c))))
4844 'body-only (org-combine-plists params '(:with-tables t))))))
4846 (defun org-table--generic-apply (value name &optional with-cons &rest args)
4847 (cond ((null value) nil)
4848 ((functionp value) `(funcall ',value ,@args))
4850 (cond ((consp (car args)) `(apply #'format ,value ,@args))
4851 (args `(format ,value ,@args))
4853 ((and with-cons (consp value))
4854 `(let ((val (cadr (memq column ',value))))
4855 (cond ((null val) contents)
4856 ((stringp val) (format val ,@args))
4857 ((functionp val) (funcall val ,@args))
4858 (t (user-error "Wrong %s value" ,name)))))
4859 (t (user-error "Wrong %s value" name))))
4861 (defun org-table--to-generic-table (params)
4862 "Return custom table transcoder according to PARAMS.
4863 PARAMS is a plist. See `orgtbl-to-generic' for more
4865 (let ((backend (plist-get params :backend))
4866 (splice (plist-get params :splice))
4867 (tstart (plist-get params :tstart))
4868 (tend (plist-get params :tend)))
4869 `(lambda (table contents info)
4871 ,(and tstart (not splice)
4872 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
4873 ,(if (or (not backend) tstart tend splice) 'contents
4874 `(org-export-with-backend ',backend table contents info))
4875 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
4877 (defun org-table--to-generic-row (params)
4878 "Return custom table row transcoder according to PARAMS.
4879 PARAMS is a plist. See `orgtbl-to-generic' for more
4881 (let* ((backend (plist-get params :backend))
4882 (lstart (plist-get params :lstart))
4883 (llstart (plist-get params :llstart))
4884 (hlstart (plist-get params :hlstart))
4885 (hllstart (plist-get params :hllstart))
4886 (lend (plist-get params :lend))
4887 (llend (plist-get params :llend))
4888 (hlend (plist-get params :hlend))
4889 (hllend (plist-get params :hllend))
4890 (lfmt (plist-get params :lfmt))
4891 (llfmt (plist-get params :llfmt))
4892 (hlfmt (plist-get params :hlfmt))
4893 (hllfmt (plist-get params :hllfmt)))
4894 `(lambda (row contents info)
4895 (if (eq (org-element-property :type row) 'rule)
4897 ((plist-member params :hline)
4898 (org-table--generic-apply (plist-get params :hline) ":hline"))
4899 (backend `(org-export-with-backend ',backend row nil info)))
4900 (let ((headerp (org-export-table-row-in-header-p row info))
4901 (lastp (not (org-export-get-next-element row info)))
4902 (last-header-p (org-export-table-row-ends-header-p row info)))
4904 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
4905 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
4906 ;; `:lstart', `:lend' and their relatives.
4908 '(org-element-map row 'table-cell
4910 ;; Export all cells, without separators.
4912 ;; Use `org-export-data-with-backend'
4913 ;; instead of `org-export-data' to eschew
4914 ;; cached values, which
4915 ;; ignore :orgtbl-ignore-sep parameter.
4916 (org-export-data-with-backend
4918 (plist-get info :back-end)
4919 (org-combine-plists info '(:orgtbl-ignore-sep t))))
4923 `(last-header-p ,(org-table--generic-apply
4924 hllfmt ":hllfmt" nil cells)))
4926 `(headerp ,(org-table--generic-apply
4927 hlfmt ":hlfmt" nil cells)))
4929 `(lastp ,(org-table--generic-apply
4930 llfmt ":llfmt" nil cells)))
4932 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
4936 (or hllstart hllend)
4939 ,(org-table--generic-apply hllstart ":hllstart")
4941 ,(org-table--generic-apply hllend ":hllend"))))
4946 ,(org-table--generic-apply hlstart ":hlstart")
4948 ,(org-table--generic-apply hlend ":hlend"))))
4953 ,(org-table--generic-apply llstart ":llstart")
4955 ,(org-table--generic-apply llend ":llend"))))
4960 ,(org-table--generic-apply lstart ":lstart")
4962 ,(org-table--generic-apply lend ":lend")))
4964 `(org-export-with-backend
4965 ',backend row contents info))
4966 (t 'contents)))))))))))))))
4968 (defun org-table--to-generic-cell (params)
4969 "Return custom table cell transcoder according to PARAMS.
4970 PARAMS is a plist. See `orgtbl-to-generic' for more
4972 (let* ((backend (plist-get params :backend))
4973 (efmt (plist-get params :efmt))
4974 (fmt (plist-get params :fmt))
4975 (hfmt (plist-get params :hfmt))
4976 (sep (plist-get params :sep))
4977 (hsep (plist-get params :hsep)))
4978 `(lambda (cell contents info)
4979 (let ((headerp (org-export-table-row-in-header-p
4980 (org-export-get-parent-element cell) info))
4981 (column (1+ (cdr (org-export-table-cell-address cell info)))))
4982 ;; Make sure that contents are exported as Org data when :raw
4983 ;; parameter is non-nil.
4984 ,(when (and backend (plist-get params :raw))
4986 ;; Since we don't know what are the pseudo object
4987 ;; types defined in backend, we cannot pass them to
4988 ;; `org-element-interpret-data'. As a consequence,
4989 ;; they will be treated as pseudo elements, and
4990 ;; will have newlines appended instead of spaces.
4991 ;; Therefore, we must make sure :post-blank value
4992 ;; is really turned into spaces.
4993 (replace-regexp-in-string
4996 (org-element-interpret-data
4997 (org-element-contents cell))))))
4999 ;; Check if we can apply `:efmt' on CONTENTS.
5001 `(when (string-match orgtbl-exp-regexp contents)
5002 (let ((mantissa (match-string 1 contents))
5003 (exponent (match-string 2 contents)))
5004 (setq contents ,(org-table--generic-apply
5005 efmt ":efmt" t 'mantissa 'exponent)))))
5006 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5008 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5009 hfmt ":hfmt" t 'contents))))
5010 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5011 fmt ":fmt" t 'contents))))))
5012 ;; If a separator is provided, use it instead of BACKEND's.
5013 ;; Separators are ignored when LFMT (or equivalent) is
5017 `(if (or ,(and (not sep) '(not headerp))
5018 (plist-get info :orgtbl-ignore-sep)
5019 (not (org-export-get-next-element cell info)))
5020 ,(if (not backend) 'contents
5021 `(org-export-with-backend ',backend cell contents info))
5023 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5025 (backend `(org-export-with-backend ',backend cell contents info))
5029 (defun orgtbl-to-tsv (table params)
5030 "Convert the orgtbl-mode table to TAB separated material."
5031 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5034 (defun orgtbl-to-csv (table params)
5035 "Convert the orgtbl-mode table to CSV material.
5036 This does take care of the proper quoting of fields with comma or quotes."
5037 (orgtbl-to-generic table
5038 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5042 (defun orgtbl-to-latex (table params)
5043 "Convert the orgtbl-mode TABLE to LaTeX.
5045 TABLE is a list, each entry either the symbol `hline' for
5046 a horizontal separator line, or a list of fields for that line.
5047 PARAMS is a property list of parameters that can influence the
5048 conversion. All parameters from `orgtbl-to-generic' are
5049 supported. It is also possible to use the following ones:
5053 When non-nil, use formal \"booktabs\" style.
5057 Specify environment to use, as a string. If you use
5058 \"longtable\", you may also want to specify :language property,
5059 as a string, to get proper continuation strings."
5064 ;; Provide sane default values.
5065 (list :backend 'latex
5066 :latex-default-table-mode 'table
5067 :latex-tables-centered nil
5068 :latex-tables-booktabs (plist-get params :booktabs)
5069 :latex-table-scientific-notation nil
5070 :latex-default-table-environment
5071 (or (plist-get params :environment) "tabular"))
5075 (defun orgtbl-to-html (table params)
5076 "Convert the orgtbl-mode TABLE to HTML.
5078 TABLE is a list, each entry either the symbol `hline' for
5079 a horizontal separator line, or a list of fields for that line.
5080 PARAMS is a property list of parameters that can influence the
5081 conversion. All parameters from `orgtbl-to-generic' are
5082 supported. It is also possible to use the following one:
5086 Attributes and values, as a plist, which will be used in
5092 ;; Provide sane default values.
5093 (list :backend 'html
5094 :html-table-data-tags '("<td%s>" . "</td>")
5095 :html-table-use-header-tags-for-first-column nil
5096 :html-table-align-individual-fields t
5097 :html-table-row-tags '("<tr>" . "</tr>")
5098 :html-table-attributes
5099 (if (plist-member params :attributes)
5100 (plist-get params :attributes)
5101 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5106 (defun orgtbl-to-texinfo (table params)
5107 "Convert the orgtbl-mode TABLE to Texinfo.
5109 TABLE is a list, each entry either the symbol `hline' for
5110 a horizontal separator line, or a list of fields for that line.
5111 PARAMS is a property list of parameters that can influence the
5112 conversion. All parameters from `orgtbl-to-generic' are
5113 supported. It is also possible to use the following one:
5117 Column widths, as a string. When providing column fractions,
5118 \"@columnfractions\" command can be omitted."
5119 (require 'ox-texinfo)
5124 (list :backend 'texinfo
5125 :texinfo-tables-verbatim nil
5126 :texinfo-table-scientific-notation nil)
5128 (columns (let ((w (plist-get params :columns)))
5130 ((org-string-match-p "{\\|@columnfractions " w) w)
5131 (t (concat "@columnfractions " w))))))
5132 (if (not columns) output
5133 (replace-regexp-in-string
5134 "@multitable \\(.*\\)" columns output t nil 1))))
5137 (defun orgtbl-to-orgtbl (table params)
5138 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5140 TABLE is a list, each entry either the symbol `hline' for
5141 a horizontal separator line, or a list of fields for that line.
5142 PARAMS is a property list of parameters that can influence the
5143 conversion. All parameters from `orgtbl-to-generic' are
5146 Useful when slicing one table into many. The :hline, :sep,
5147 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5148 be set to provide ORGTBL directives for the generated table."
5150 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5152 (defun orgtbl-to-table.el (table params)
5153 "Convert the orgtbl-mode TABLE into a table.el table.
5154 TABLE is a list, each entry either the symbol `hline' for
5155 a horizontal separator line, or a list of fields for that line.
5156 PARAMS is a property list of parameters that can influence the
5157 conversion. All parameters from `orgtbl-to-generic' are
5160 (insert (orgtbl-to-orgtbl table params))
5162 (replace-regexp-in-string
5164 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5166 (defun orgtbl-to-unicode (table params)
5167 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5169 TABLE is a list, each entry either the symbol `hline' for
5170 a horizontal separator line, or a list of fields for that line.
5171 PARAMS is a property list of parameters that can influence the
5172 conversion. All parameters from `orgtbl-to-generic' are
5173 supported. It is also possible to use the following ones:
5177 When non-nil, use \"ascii-art-to-unicode\" package to translate
5178 the table. You can download it here:
5179 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5183 When non-nil, narrow columns width than provided width cookie,
5184 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5189 (list :backend 'ascii
5190 :ascii-charset 'utf-8
5191 :ascii-table-widen-columns (not (plist-get params :narrow))
5192 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5195 ;; Put the cursor in a column containing numerical values
5196 ;; of an Org-Mode table,
5198 ;; A new column is added with a bar plot.
5199 ;; When the table is refreshed (C-u C-c *),
5200 ;; the plot is updated to reflect the new values.
5202 (defun orgtbl-ascii-draw (value min max &optional width characters)
5203 "Draw an ascii bar in a table.
5204 VALUE is a the value to plot, the width of the bar to draw. A
5205 value equal to MIN will be displayed as empty (zero width bar).
5206 A value equal to MAX will draw a bar filling all the WIDTH.
5207 WIDTH is the expected width in characters of the column.
5208 CHARACTERS is a string that will compose the bar, with shades of
5209 grey from pure white to pure black. It defaults to a 10
5210 characters string of regular ascii characters."
5211 (let* ((characters (or characters " .:;c!lhVHW"))
5212 (width (or width 12))
5213 (value (if (numberp value) value (string-to-number value)))
5214 (value (* (/ (- (+ value 0.0) min) (- max min)) width)))
5216 ((< value 0) "too small")
5217 ((> value width) "too large")
5219 (let ((len (1- (length characters))))
5221 (make-string (floor value) (elt characters len))
5222 (string (elt characters
5223 (floor (* (- value (floor value)) len))))))))))
5226 (defun orgtbl-ascii-plot (&optional ask)
5227 "Draw an ascii bar plot in a column.
5228 With cursor in a column containing numerical values, this
5229 function will draw a plot in a new column.
5230 ASK, if given, is a numeric prefix to override the default 12
5231 characters width of the plot. ASK may also be the
5232 \\[universal-argument] prefix, which will prompt for the width."
5234 (let ((col (org-table-current-column))
5235 (min 1e999) ; 1e999 will be converted to infinity
5236 (max -1e999) ; which is the desired result
5237 (table (org-table-to-lisp))
5240 (read-number "Length of column " 12))
5243 ;; Skip any hline a the top of table.
5244 (while (eq (car table) 'hline) (setq table (cdr table)))
5245 ;; Skip table header if any.
5246 (dolist (x (or (cdr (memq 'hline table)) table))
5248 (setq x (nth (1- col) x))
5250 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
5252 (setq x (string-to-number x))
5253 (when (> min x) (setq min x))
5254 (when (< max x) (setq max x)))))
5255 (org-table-insert-column)
5256 (org-table-move-column-right)
5257 (org-table-store-formulas
5260 (number-to-string (1+ col))
5261 (format "'(%s $%s %s %s %s)"
5262 "orgtbl-ascii-draw" col min max length))
5263 (org-table-get-stored-formulas)))
5264 (org-table-recalculate t)))
5266 ;; Example of extension: unicode characters
5267 ;; Here are two examples of different styles.
5269 ;; Unicode block characters are used to give a smooth effect.
5270 ;; See http://en.wikipedia.org/wiki/Block_Elements
5271 ;; Use one of those drawing functions
5272 ;; - orgtbl-ascii-draw (the default ascii)
5273 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
5274 ;; - orgtbl-uc-draw-cont (smooth unicode)
5276 ;; This is best viewed with the "DejaVu Sans Mono" font
5277 ;; (use M-x set-default-font).
5279 (defun orgtbl-uc-draw-grid (value min max &optional width)
5280 "Draw a bar in a table using block unicode characters.
5281 It is a variant of orgtbl-ascii-draw with Unicode block
5282 characters, for a smooth display. Bars appear as grids (to the
5283 extent the font allows)."
5284 ;; http://en.wikipedia.org/wiki/Block_Elements
5285 ;; best viewed with the "DejaVu Sans Mono" font.
5286 (orgtbl-ascii-draw value min max width
5287 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
5289 (defun orgtbl-uc-draw-cont (value min max &optional width)
5290 "Draw a bar in a table using block unicode characters.
5291 It is a variant of orgtbl-ascii-draw with Unicode block
5292 characters, for a smooth display. Bars are solid (to the extent
5294 (orgtbl-ascii-draw value min max width
5295 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
5297 (defun org-table-get-remote-range (name-or-id form)
5298 "Get a field value or a list of values in a range from table at ID.
5300 NAME-OR-ID may be the name of a table in the current file as set
5301 by a \"#+NAME:\" directive. The first table following this line
5302 will then be used. Alternatively, it may be an ID referring to
5303 any entry, also in a different file. In this case, the first
5304 table in that entry will be referenced.
5305 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
5306 \"@I$2..@II$2\". All the references must be absolute, not relative.
5308 The return value is either a single string for a single field, or a
5309 list of the fields in the rectangle."
5311 (let ((case-fold-search t) (id-loc nil)
5312 ;; Protect a bunch of variables from being overwritten
5313 ;; by the context of the remote table
5314 org-table-column-names org-table-column-name-regexp
5315 org-table-local-parameters org-table-named-field-locations
5316 org-table-current-line-types org-table-current-begin-line
5317 org-table-current-begin-pos org-table-dlines
5318 org-table-current-ncol
5319 org-table-hlines org-table-last-alignment
5320 org-table-last-column-widths org-table-last-alignment
5321 org-table-last-column-widths tbeg
5323 (setq form (org-table-convert-refs-to-rc form))
5328 (goto-char (point-min))
5329 (if (re-search-forward
5330 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
5331 (regexp-quote name-or-id) "[ \t]*$")
5333 (setq buffer (current-buffer) loc (match-beginning 0))
5334 (setq id-loc (org-id-find name-or-id 'marker))
5335 (unless (and id-loc (markerp id-loc))
5336 (user-error "Can't find remote table \"%s\"" name-or-id))
5337 (setq buffer (marker-buffer id-loc)
5338 loc (marker-position id-loc))
5339 (move-marker id-loc nil)))
5340 (with-current-buffer buffer
5346 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
5347 (not (match-beginning 1)))
5348 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
5349 (setq tbeg (point-at-bol))
5350 (org-table-get-specials)
5351 (setq form (org-table-formula-substitute-names
5352 (org-table-formula-handle-first/last-rc form)))
5353 (if (and (string-match org-table-range-regexp form)
5354 (> (length (match-string 0 form)) 1))
5356 (org-table-get-range (match-string 0 form) tbeg 1))
5359 (defun org-table-remote-reference-indirection (form)
5360 "Return formula with table remote references substituted by indirection.
5361 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
5362 This indirection works only with the format @ROW$COLUMN. The
5363 format \"B3\" is not supported because it can not be
5364 distinguished from a plain table name or ID."
5366 (while (string-match (concat
5367 ;; Same as in `org-table-eval-formula'.
5368 "\\<remote([ \t]*\\("
5369 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
5371 ;; Same as in `org-table-eval-formula'.
5372 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")
5375 ;; The position of the character as far as possible to the right
5376 ;; that will not be replaced and particularly not be shifted by
5378 (setq start (match-beginning 1))
5379 ;; Substitute the remote reference with the value found in the
5384 (org-table-get-range (org-table-formula-handle-first/last-rc
5385 (match-string 1 form))))
5389 (defmacro org-define-lookup-function (mode)
5390 (let ((mode-str (symbol-name mode))
5391 (first-p (equal mode 'first))
5392 (all-p (equal mode 'all)))
5393 (let ((plural-str (if all-p "s" "")))
5394 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
5395 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
5396 If R-LIST is nil, return matching element%s of S-LIST.
5397 If PREDICATE is not nil, use it instead of `equal' to match VAL.
5398 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
5399 This function is generated by a call to the macro `org-define-lookup-function'."
5400 mode-str plural-str plural-str plural-str)
5401 (let ,(let ((lvars '((p (or predicate 'equal))
5403 (rl (or r-list s-list))
5405 (if first-p (add-to-list 'lvars '(match-p nil)))
5407 (while ,(if first-p '(and (not match-p) sl) 'sl)
5409 (if (funcall p val (car sl))
5411 ,(if first-p '(setq match-p t))
5412 (let ((rval (car rl)))
5413 (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
5414 (setq sl (cdr sl) rl (cdr rl))))
5417 (org-define-lookup-function first)
5418 (org-define-lookup-function last)
5419 (org-define-lookup-function all)
5421 (provide 'org-table)
5424 ;; generated-autoload-file: "org-loaddefs.el"
5427 ;;; org-table.el ends here