1 ;;; org-table.el --- The Table Editor for Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2004-2019 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: https://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 <https://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.
42 (declare-function calc-eval
"calc" (str &optional separator
&rest args
))
43 (declare-function org-at-timestamp-p
"org" (&optional extended
))
44 (declare-function org-delete-backward-char
"org" (N))
45 (declare-function org-element-at-point
"org-element" ())
46 (declare-function org-element-contents
"org-element" (element))
47 (declare-function org-element-extract-element
"org-element" (element))
48 (declare-function org-element-interpret-data
"org-element" (data))
49 (declare-function org-element-lineage
"org-element" (blob &optional types with-self
))
50 (declare-function org-element-map
"org-element" (data types fun
&optional info first-match no-recursion with-affiliated
))
51 (declare-function org-element-parse-buffer
"org-element" (&optional granularity visible-only
))
52 (declare-function org-element-property
"org-element" (property element
))
53 (declare-function org-element-type
"org-element" (element))
54 (declare-function org-entry-get
"org" (pom property
&optional inherit literal-nil
))
55 (declare-function org-export-create-backend
"ox" (&rest rest
) t
)
56 (declare-function org-export-data-with-backend
"ox" (data backend info
))
57 (declare-function org-export-filter-apply-functions
"ox" (filters value info
))
58 (declare-function org-export-first-sibling-p
"ox" (blob info
))
59 (declare-function org-export-get-backend
"ox" (name))
60 (declare-function org-export-get-environment
"ox" (&optional backend subtreep ext-plist
))
61 (declare-function org-export-install-filters
"ox" (info))
62 (declare-function org-export-table-has-special-column-p
"ox" (table))
63 (declare-function org-export-table-row-is-special-p
"ox" (table-row info
))
64 (declare-function org-id-find
"org-id" (id &optional markerp
))
65 (declare-function org-indent-line
"org" ())
66 (declare-function org-load-modules-maybe
"org" (&optional force
))
67 (declare-function org-restart-font-lock
"org" ())
68 (declare-function org-sort-remove-invisible
"org" (s))
69 (declare-function org-time-stamp-format
"org" (&optional long inactive
))
70 (declare-function org-time-string-to-absolute
"org" (s &optional daynr prefer buffer pos
))
71 (declare-function org-time-string-to-time
"org" (s))
72 (declare-function org-timestamp-up-day
"org" (&optional arg
))
74 (defvar constants-unit-system
)
75 (defvar org-M-RET-may-split-line
)
76 (defvar org-element-use-cache
)
77 (defvar org-export-filters-alist
)
78 (defvar org-finish-function
)
79 (defvar org-inhibit-highlight-removal
)
80 (defvar org-inhibit-startup
)
81 (defvar org-selected-window
)
82 (defvar org-self-insert-cluster-for-undo
)
83 (defvar org-self-insert-command-undo-counter
)
84 (defvar org-ts-regexp
)
85 (defvar org-ts-regexp-both
)
86 (defvar org-ts-regexp-inactive
)
87 (defvar org-ts-regexp3
)
88 (defvar org-window-configuration
)
89 (defvar sort-fold-case
)
94 (defgroup org-table nil
95 "Options concerning tables in Org mode."
99 (defcustom orgtbl-optimized t
100 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
102 In the optimized version, the table editor takes over all simple keys that
103 normally just insert a character. In tables, the characters are inserted
104 in a way to minimize disturbing the table structure (i.e. in overwrite mode
105 for empty fields). Outside tables, the correct binding of the keys is
108 Changing this variable requires a restart of Emacs to become
113 (defcustom orgtbl-radio-table-templates
114 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
115 % END RECEIVE ORGTBL %n
117 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
120 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
121 @c END RECEIVE ORGTBL %n
123 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
126 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
127 <!-- END RECEIVE ORGTBL %n -->
129 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
132 (org-mode "#+ BEGIN RECEIVE ORGTBL %n
133 #+ END RECEIVE ORGTBL %n
135 #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
138 "Templates for radio tables in different major modes.
139 Each template must define lines that will be treated as a comment and that
140 must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
141 lines where \"%n\" will be replaced with the name of the table during
142 insertion of the template. The transformed table will later be inserted
145 The template should also contain a minimal table in a multiline comment.
146 If multiline comments are not possible in the buffer language,
147 you can pack it into a string that will not be used when the code
148 is compiled or executed. Above the table will you need a line with
149 the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
150 convert the table into a data structure useful in the
151 language of the buffer. Check the manual for the section on
152 \"Translator functions\", and more generally check out
153 the Info node `(org)Tables in arbitrary syntax'.
155 All occurrences of %n in a template will be replaced with the name of the
156 table, obtained by prompting the user."
159 (list (symbol :tag
"Major mode")
160 (string :tag
"Format"))))
162 (defgroup org-table-settings nil
163 "Settings for tables in Org mode."
164 :tag
"Org Table Settings"
167 (defcustom org-table-default-size
"5x2"
168 "The default size for newly created tables, Columns x Rows."
169 :group
'org-table-settings
172 (defcustom org-table-number-regexp
173 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
174 "Regular expression for recognizing numbers in table columns.
175 If a table column contains mostly numbers, it will be aligned to the
176 right. If not, it will be aligned to the left.
178 The default value of this option is a regular expression which allows
179 anything which looks remotely like a number as used in scientific
180 context. For example, all of the following will be considered a
182 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
184 Other options offered by the customize interface are more restrictive."
185 :group
'org-table-settings
187 (const :tag
"Positive Integers"
189 (const :tag
"Integers"
191 (const :tag
"Floating Point Numbers"
192 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
193 (const :tag
"Floating Point Number or Integer"
194 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
195 (const :tag
"Exponential, Floating point, Integer"
196 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
197 (const :tag
"Very General Number-Like, including hex and Calc radix"
198 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
199 (const :tag
"Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
200 "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
201 (string :tag
"Regexp:")))
203 (defcustom org-table-number-fraction
0.5
204 "Fraction of numbers in a column required to make the column align right.
205 In a column all non-white fields are considered. If at least
206 this fraction of fields is matched by `org-table-number-regexp',
207 alignment to the right border applies."
208 :group
'org-table-settings
211 (defcustom org-table-formula-field-format
"%s"
212 "Format for fields which contain the result of a formula.
213 For example, using \"~%s~\" will display the result within tilde
214 characters. Beware that modifying the display can prevent the
215 field from being used in another formula."
216 :group
'org-table-settings
220 (defgroup org-table-editing nil
221 "Behavior of tables during editing in Org mode."
222 :tag
"Org Table Editing"
225 (defcustom org-table-automatic-realign t
226 "Non-nil means automatically re-align table when pressing TAB or RETURN.
227 When nil, aligning is only done with `\\[org-table-align]', or after column
229 :group
'org-table-editing
232 (defcustom org-table-auto-blank-field t
233 "Non-nil means automatically blank table field when starting to type into it.
234 This only happens when typing immediately after a field motion
235 command (TAB, S-TAB or RET)."
236 :group
'org-table-editing
239 (defcustom org-table-exit-follow-field-mode-when-leaving-table t
240 "Non-nil means automatically exit the follow mode.
241 When nil, the follow mode will stay on and be active in any table
242 the cursor enters. Since the table follow filed mode messes with the
243 window configuration, it is not recommended to set this variable to nil,
244 except maybe locally in a special file that has mostly tables with long
250 (defcustom org-table-fix-formulas-confirm nil
251 "Whether the user should confirm when Org fixes formulas."
252 :group
'org-table-editing
255 (const :tag
"with yes-or-no" yes-or-no-p
)
256 (const :tag
"with y-or-n" y-or-n-p
)
257 (const :tag
"no confirmation" nil
)))
259 (defcustom org-table-tab-jumps-over-hlines t
260 "Non-nil means tab in the last column of a table with jump over a hline.
261 If a horizontal separator line is following the current line,
262 `org-table-next-field' can either create a new row before that line, or jump
263 over the line. When this option is nil, a new line will be created before
265 :group
'org-table-editing
268 (defcustom org-table-shrunk-column-indicator
"…"
269 "String to be displayed in a shrunk column."
270 :group
'org-table-editing
272 :package-version
'(Org .
"9.2")
273 :safe
(lambda (v) (and (stringp v
) (not (equal v
"")))))
275 (defgroup org-table-calculation nil
276 "Options concerning tables in Org mode."
277 :tag
"Org Table Calculation"
280 (defcustom org-table-use-standard-references
'from
281 "Non-nil means using table references like B3 instead of @3$2.
284 from accept as input, do not present for editing
285 t accept as input and present for editing"
286 :group
'org-table-calculation
288 (const :tag
"Never, don't even check user input for them" nil
)
289 (const :tag
"Always, both as user input, and when editing" t
)
290 (const :tag
"Convert user input, don't offer during editing" from
)))
292 (defcustom org-table-copy-increment t
293 "Non-nil means increment when copying current field with \
294 `\\[org-table-copy-down]'."
295 :group
'org-table-calculation
297 :package-version
'(Org .
"8.3")
299 (const :tag
"Use the difference between the current and the above fields" t
)
300 (integer :tag
"Use a number" 1)
301 (const :tag
"Don't increment the value when copying a field" nil
)))
303 (defcustom org-calc-default-modes
304 '(calc-internal-prec 12
305 calc-float-format
(float 8)
308 calc-symbolic-mode nil
309 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
310 calc-display-working-message t
)
311 "List with Calc mode settings for use in `calc-eval' for table formulas.
312 The list must contain alternating symbols (Calc modes variables and values).
313 Don't remove any of the default settings, just change the values. Org mode
314 relies on the variables to be present in the list."
315 :group
'org-table-calculation
318 (defcustom org-table-duration-custom-format
'hours
319 "Format for the output of calc computations like $1+$2;t.
320 The default value is `hours', and will output the results as a
321 number of hours. Other allowed values are `seconds', `minutes' and
322 `days', and the output will be a fraction of seconds, minutes or
323 days. `hh:mm' selects to use hours and minutes, ignoring seconds.
324 The `U' flag in a table formula will select this specific format for
326 :group
'org-table-calculation
328 :type
'(choice (symbol :tag
"Seconds" 'seconds
)
329 (symbol :tag
"Minutes" 'minutes
)
330 (symbol :tag
"Hours " 'hours
)
331 (symbol :tag
"Days " 'days
)
332 (symbol :tag
"HH:MM " 'hh
:mm
)))
334 (defcustom org-table-duration-hour-zero-padding t
335 "Non-nil means hours in table duration computations should be zero-padded.
336 So this is about 08:32:34 versus 8:33:34."
337 :group
'org-table-calculation
339 :package-version
'(Org .
"9.1")
343 (defcustom org-table-formula-evaluate-inline t
344 "Non-nil means TAB and RET evaluate a formula in current table field.
345 If the current field starts with an equal sign, it is assumed to be a formula
346 which should be evaluated as described in the manual and in the documentation
347 string of the command `org-table-eval-formula'. This feature requires the
349 When this variable is nil, formula calculation is only available through
350 the command `\\[org-table-eval-formula]'."
351 :group
'org-table-calculation
354 (defcustom org-table-formula-use-constants t
355 "Non-nil means interpret constants in formulas in tables.
356 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
357 by the value given in `org-table-formula-constants', or by a value obtained
358 from the `constants.el' package."
359 :group
'org-table-calculation
362 (defcustom org-table-formula-constants nil
363 "Alist with constant names and values, for use in table formulas.
364 The car of each element is a name of a constant, without the `$' before it.
365 The cdr is the value as a string. For example, if you'd like to use the
366 speed of light in a formula, you would configure
368 (setq org-table-formula-constants \\='((\"c\" . \"299792458.\")))
370 and then use it in an equation like `$1*$c'.
372 Constants can also be defined on a per-file basis using a line like
374 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
375 :group
'org-table-calculation
377 (cons (string :tag
"name")
378 (string :tag
"value"))))
380 (defcustom org-table-allow-automatic-line-recalculation t
381 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
383 Automatically means when `TAB' or `RET' or `\\[org-ctrl-c-ctrl-c]' \
384 are pressed in the line."
385 :group
'org-table-calculation
388 (defcustom org-table-relative-ref-may-cross-hline t
389 "Non-nil means relative formula references may cross hlines.
390 Here are the allowed values:
392 nil Relative references may not cross hlines. They will reference the
393 field next to the hline instead. Coming from below, the reference
394 will be to the field below the hline. Coming from above, it will be
396 t Relative references may cross hlines.
397 error An attempt to cross a hline will throw an error.
399 It is probably good to never set this variable to nil, for the sake of
400 portability of tables."
401 :group
'org-table-calculation
403 (const :tag
"Allow to cross" t
)
404 (const :tag
"Stick to hline" nil
)
405 (const :tag
"Error on attempt to cross" error
)))
407 (defcustom org-table-formula-create-columns nil
408 "Non-nil means evaluation of formula can add new columns.
409 When non-nil, evaluating an out-of-bounds field can insert as
410 many columns as needed. When set to `warn', issue a warning when
411 doing so. When set to `prompt', ask user before creating a new
412 column. Otherwise, throw an error."
413 :group
'org-table-calculation
414 :package-version
'(Org .
"8.3")
416 (const :tag
"Out-of-bounds field generates an error (default)" nil
)
417 (const :tag
"Out-of-bounds field silently adds columns as needed" t
)
418 (const :tag
"Out-of-bounds field adds columns, but issues a warning" warn
)
419 (const :tag
"Prompt user when setting an out-of-bounds field" prompt
)))
421 (defgroup org-table-import-export nil
422 "Options concerning table import and export in Org mode."
423 :tag
"Org Table Import Export"
426 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
427 "Default export parameters for `org-table-export'.
428 These can be overridden for a specific table by setting the
429 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
430 radio tables for the different export transformations and
431 available parameters."
432 :group
'org-table-import-export
435 (defcustom org-table-convert-region-max-lines
999
436 "Max lines that `org-table-convert-region' will attempt to process.
438 The function can be slow on larger regions; this safety feature
439 prevents it from hanging Emacs."
440 :group
'org-table-import-export
442 :package-version
'(Org .
"8.3"))
445 ;;; Regexps Constants
447 (defconst org-table-any-line-regexp
"^[ \t]*\\(|\\|\\+-[-+]\\)"
448 "Detect an org-type or table-type table.")
450 (defconst org-table-line-regexp
"^[ \t]*|"
451 "Detect an org-type table line.")
453 (defconst org-table-dataline-regexp
"^[ \t]*|[^-]"
454 "Detect an org-type table line.")
456 (defconst org-table-hline-regexp
"^[ \t]*|-"
457 "Detect an org-type table hline.")
459 (defconst org-table1-hline-regexp
"^[ \t]*\\+-[-+]"
460 "Detect a table-type table hline.")
462 (defconst org-table-any-border-regexp
"^[ \t]*[^|+ \t]"
463 "Detect the first line outside a table when searching from within it.
464 This works for both table types.")
466 (defconst org-TBLFM-regexp
"^[ \t]*#\\+TBLFM: "
467 "Detect a #+TBLFM line.")
469 (defvar org-table-TBLFM-begin-regexp
"^[ \t]*|.*\n[ \t]*#\\+TBLFM: ")
471 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
472 "Regexp matching a line marked for automatic recalculation.")
474 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
475 "Regexp matching a line marked for recalculation.")
477 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
478 "Regexp matching a line marked for calculation.")
480 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
481 "Regexp matching any line outside an Org table.")
483 (defconst org-table-range-regexp
484 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
486 "Regular expression for matching ranges in formulas.")
488 (defconst org-table-range-regexp2
490 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
492 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
493 "Match a range for reference display.")
495 (defconst org-table-translate-regexp
496 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
497 "Match a reference that needs translation, for reference display.")
499 (defconst org-table-separator-space
500 (propertize " " 'display
'(space :relative-width
1))
501 "Space used around fields when aligning the table.
502 This space serves as a segment separator for the purposes of the
503 bidirectional reordering.")
506 ;;; Internal Variables
508 (defvar org-table-last-highlighted-reference nil
)
510 (defvar org-table-formula-history nil
)
512 (defvar org-field-marker nil
)
513 (defvar org-table-buffer-is-an nil
)
515 (defvar-local org-table-formula-constants-local nil
516 "Local version of `org-table-formula-constants'.")
518 (defvar org-table-may-need-update t
519 "Indicates that a table might need an update.
520 This variable is set by `org-before-change-function'.
521 `org-table-align' sets it back to nil.")
523 (defvar orgtbl-after-send-table-hook nil
524 "Hook for functions attaching to `C-c C-c', if the table is sent.
525 This can be used to add additional functionality after the table is sent
526 to the receiver position, otherwise, if table is not sent, the functions
529 (defvar org-table-column-names nil
530 "Alist with column names, derived from the `!' line.
531 This variable is initialized with `org-table-analyze'.")
533 (defvar org-table-column-name-regexp nil
534 "Regular expression matching the current column names.
535 This variable is initialized with `org-table-analyze'.")
537 (defvar org-table-local-parameters nil
538 "Alist with parameter names, derived from the `$' line.
539 This variable is initialized with `org-table-analyze'.")
541 (defvar org-table-named-field-locations nil
542 "Alist with locations of named fields.
543 Associations follow the pattern (NAME LINE COLUMN) where
544 NAME is the name of the field as a string,
545 LINE is the number of lines from the beginning of the table,
546 COLUMN is the column of the field, as an integer.
547 This variable is initialized with `org-table-analyze'.")
549 (defvar org-table-current-line-types nil
550 "Table row types in current table.
551 This variable is initialized with `org-table-analyze'.")
553 (defvar org-table-current-begin-pos nil
554 "Current table begin position, as a marker.
555 This variable is initialized with `org-table-analyze'.")
557 (defvar org-table-current-ncol nil
558 "Number of columns in current table.
559 This variable is initialized with `org-table-analyze'.")
561 (defvar org-table-dlines nil
562 "Vector of data line line numbers in the current table.
563 Line numbers are counted from the beginning of the table. This
564 variable is initialized with `org-table-analyze'.")
566 (defvar org-table-hlines nil
567 "Vector of hline line numbers in the current table.
568 Line numbers are counted from the beginning of the table. This
569 variable is initialized with `org-table-analyze'.")
571 (defvar org-table-aligned-begin-marker
(make-marker)
572 "Marker at the beginning of the table last aligned.
573 Used to check if cursor still is in that table, to minimize realignment.")
575 (defvar org-table-aligned-end-marker
(make-marker)
576 "Marker at the end of the table last aligned.
577 Used to check if cursor still is in that table, to minimize realignment.")
579 (defvar org-table-last-alignment nil
580 "List of flags for flushright alignment, from the last re-alignment.
581 This is being used to correctly align a single field after TAB or RET.")
583 (defvar org-table-last-column-widths nil
584 "List of max width of fields in each column.
585 This is being used to correctly align a single field after TAB or RET.")
587 (defvar-local org-table-formula-debug nil
588 "Non-nil means debug table formulas.
589 When nil, simply write \"#ERROR\" in corrupted fields.")
591 (defvar-local org-table-overlay-coordinates nil
592 "Overlay coordinates after each align of a table.")
594 (defvar org-last-recalc-line nil
)
596 (defvar org-show-positions nil
)
598 (defvar org-table-rectangle-overlays nil
)
600 (defvar org-table-clip nil
601 "Clipboard for table regions.")
603 (defvar org-timecnt nil
)
605 (defvar org-recalc-commands nil
606 "List of commands triggering the recalculation of a line.
607 Will be filled automatically during use.")
609 (defvar org-recalc-marks
610 '((" " .
"Unmarked: no special line, no automatic recalculation")
611 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
612 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
613 ("!" .
"Column name definition line. Reference in formula as $name.")
614 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
615 ("_" .
"Names for values in row below this one.")
616 ("^" .
"Names for values in row above this one.")))
618 (defvar org-tbl-calc-modes nil
)
623 ;;; Macros and Inlined Functions
625 (defmacro org-table-with-shrunk-columns
(&rest body
)
626 "Expand all columns before executing BODY, then shrink them again."
627 (declare (debug (body)))
628 (org-with-gensyms (shrunk-columns begin end
)
629 `(let ((,begin
(copy-marker (org-table-begin)))
630 (,end
(copy-marker (org-table-end) t
))
631 (,shrunk-columns
(org-table--list-shrunk-columns)))
632 (org-with-point-at ,begin
(org-table-expand ,begin
,end
))
635 (org-table--shrink-columns ,shrunk-columns
,begin
,end
)
636 (set-marker ,begin nil
)
637 (set-marker ,end nil
)))))
639 (defmacro org-table-with-shrunk-field
(&rest body
)
640 "Save field shrunk state, execute BODY and restore state."
641 (declare (debug (body)))
642 (org-with-gensyms (end shrunk size
)
643 `(let* ((,shrunk
(save-match-data (org-table--shrunk-field)))
644 (,end
(and ,shrunk
(copy-marker (overlay-end ,shrunk
) t
)))
645 (,size
(and ,shrunk
(- ,end
(overlay-start ,shrunk
)))))
646 (when ,shrunk
(delete-overlay ,shrunk
))
647 (unwind-protect (progn ,@body
)
648 (when ,shrunk
(move-overlay ,shrunk
(- ,end
,size
) ,end
))))))
650 (defmacro org-table-save-field
(&rest body
)
651 "Save current field; execute BODY; restore field.
652 Field is restored even in case of abnormal exit."
653 (declare (debug (body)))
654 (org-with-gensyms (line column
)
655 `(let ((,line
(copy-marker (line-beginning-position)))
656 (,column
(org-table-current-column)))
660 (org-table-goto-column ,column
)
661 (set-marker ,line nil
)))))
663 (defsubst org-table--set-calc-mode
(var &optional value
)
665 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
666 ("R" calc-angle-mode rad
)
667 ("F" calc-prefer-frac t
)
668 ("S" calc-symbolic-mode t
)))
669 value
(nth 2 var
) var
(nth 1 var
)))
670 (if (memq var org-tbl-calc-modes
)
671 (setcar (cdr (memq var org-tbl-calc-modes
)) value
)
672 (cons var
(cons value org-tbl-calc-modes
)))
678 (defun org-at-TBLFM-p (&optional pos
)
679 "Non-nil when point (or POS) is in #+TBLFM line."
681 (goto-char (or pos
(point)))
683 (and (let ((case-fold-search t
)) (looking-at org-TBLFM-regexp
))
684 (eq (org-element-type (org-element-at-point)) 'table
))))
686 (defun org-at-table-p (&optional table-type
)
687 "Non-nil if the cursor is inside an Org table.
688 If TABLE-TYPE is non-nil, also check for table.el-type tables."
689 (and (org-match-line (if table-type
"[ \t]*[|+]" "[ \t]*|"))
690 (or (not (derived-mode-p 'org-mode
))
691 (let ((e (org-element-lineage (org-element-at-point) '(table) t
)))
692 (and e
(or table-type
693 (eq 'org
(org-element-property :type e
))))))))
695 (defun org-at-table.el-p
()
696 "Non-nil when point is at a table.el table."
697 (and (org-match-line "[ \t]*[|+]")
698 (let ((element (org-element-at-point)))
699 (and (eq (org-element-type element
) 'table
)
700 (eq (org-element-property :type element
) 'table.el
)))))
702 (defun org-at-table-hline-p ()
703 "Non-nil when point is inside a hline in a table.
704 Assume point is already in a table."
705 (org-match-line org-table-hline-regexp
))
707 (defun org-table-check-inside-data-field (&optional noerror assume-table
)
708 "Non-nil when point is inside a table data field.
709 Raise an error otherwise, unless NOERROR is non-nil. In that
710 case, return nil if point is not inside a data field. When
711 optional argument ASSUME-TABLE is non-nil, assume point is within
713 (cond ((and (or assume-table
(org-at-table-p))
714 (not (save-excursion (skip-chars-backward " \t") (bolp)))
715 (not (org-at-table-hline-p))
716 (not (looking-at-p "[ \t]*$"))))
718 (t (user-error "Not in table data field"))))
721 ;;; Create, Import, and Convert Tables
724 (defun org-table-create-with-table.el
()
725 "Use the table.el package to insert a new table.
726 If there is already a table at point, convert between Org tables
727 and table.el tables."
731 ((and (org-at-table.el-p
)
732 (y-or-n-p "Convert table to Org table? "))
734 ((and (org-at-table-p)
735 (y-or-n-p "Convert table to table.el table? "))
738 (t (call-interactively 'table-insert
))))
741 (defun org-table-create-or-convert-from-region (arg)
742 "Convert region to table, or create an empty table.
743 If there is an active region, convert it to a table, using the function
744 `org-table-convert-region'. See the documentation of that function
745 to learn how the prefix argument is interpreted to determine the field
747 If there is no such region, create an empty table with `org-table-create'."
749 (if (org-region-active-p)
750 (org-table-convert-region (region-beginning) (region-end) arg
)
751 (org-table-create arg
)))
754 (defun org-table-create (&optional size
)
755 "Query for a size and insert a table skeleton.
756 SIZE is a string Columns x Rows like for example \"3x2\"."
759 (setq size
(read-string
760 (concat "Table size Columns x Rows [e.g. "
761 org-table-default-size
"]: ")
762 "" nil org-table-default-size
)))
765 (indent (make-string (current-column) ?\
))
766 (split (org-split-string size
" *x *"))
767 (rows (string-to-number (nth 1 split
)))
768 (columns (string-to-number (car split
)))
769 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
771 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
772 (point-at-bol) (point)))
773 (beginning-of-line 1)
775 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
776 (dotimes (_ rows
) (insert line
))
779 ;; Insert a hline after the first row.
786 (defun org-table-convert-region (beg0 end0
&optional separator
)
787 "Convert region to a table.
789 The region goes from BEG0 to END0, but these borders will be moved
790 slightly, to make sure a beginning of line in the first line is included.
792 SEPARATOR specifies the field separator in the lines. It can have the
795 (4) Use the comma as a field separator
796 (16) Use a TAB as field separator
797 (64) Prompt for a regular expression as field separator
798 integer When a number, use that many spaces, or a TAB, as field separator
799 regexp When a regular expression, use it to match the separator
800 nil When nil, the command tries to be smart and figure out the
801 separator in the following way:
802 - when each line contains a TAB, assume TAB-separated material
803 - when each line contains a comma, assume CSV material
804 - else, assume one or more SPACE characters as separator."
806 (let* ((beg (min beg0 end0
))
807 (end (max beg0 end0
))
809 (if (> (count-lines beg end
) org-table-convert-region-max-lines
)
810 (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
811 org-table-convert-region-max-lines
)
812 (when (equal separator
'(64))
813 (setq separator
(read-regexp "Regexp for field separator")))
815 (beginning-of-line 1)
816 (setq beg
(point-marker))
818 (if (bolp) (backward-char 1) (end-of-line 1))
819 (setq end
(point-marker))
820 ;; Get the right field separator
825 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
826 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
829 (if (equal separator
'(4))
830 (while (< (point) end
)
831 ;; parse the csv stuff
833 ((looking-at "^") (insert "| "))
834 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
835 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
836 (replace-match "\\1")
837 (if (looking-at "\"") (insert "\"")))
838 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
839 ((looking-at "[ \t]*,") (replace-match " | "))
840 (t (beginning-of-line 2))))
842 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
843 ((equal separator
'(16)) "^\\|\t")
844 ((integerp separator
)
846 (user-error "Number of spaces in separator must be >= 1")
847 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
849 (format "^ *\\|%s" separator
))
850 (t (error "This should not happen"))))
851 (while (re-search-forward re end t
)
852 (replace-match "| " t t
)))
857 (defun org-table-import (file separator
)
858 "Import FILE as a table.
860 The command tries to be smart and figure out the separator in the
863 - when each line contains a TAB, assume TAB-separated material
864 - when each line contains a comma, assume CSV material
865 - else, assume one or more SPACE characters as separator.
867 When non-nil, SEPARATOR specifies the field separator in the
868 lines. It can have the following values:
870 (4) Use the comma as a field separator
871 (16) Use a TAB as field separator
872 (64) Prompt for a regular expression as field separator
873 integer When a number, use that many spaces, or a TAB, as field separator
874 regexp When a regular expression, use it to match the separator."
876 (unless (bolp) (insert "\n"))
879 (insert-file-contents file
)
880 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) separator
)))
882 (defun org-table-convert ()
883 "Convert from Org table to table.el and back.
884 Obviously, this only works within limits. When an Org table is converted
885 to table.el, all horizontal separator lines get lost, because table.el uses
886 these as cell boundaries and has no notion of horizontal lines. A table.el
887 table can be converted to an Org table only if it does not do row or column
888 spanning. Multiline cells will become multiple cells. Beware, Org mode
889 does not test if the table can be successfully converted - it blindly
890 applies a recipe that works for simple tables."
893 (if (org-at-table.el-p
)
894 ;; convert to Org table
895 (let ((beg (copy-marker (org-table-begin t
)))
896 (end (copy-marker (org-table-end t
))))
897 (table-unrecognize-region beg end
)
899 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
903 ;; convert to table.el table
904 (let ((beg (copy-marker (org-table-begin)))
905 (end (copy-marker (org-table-end))))
906 ;; first, get rid of all horizontal lines
908 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
910 ;; insert a hline before first
912 (org-table-insert-hline 'above
)
913 (beginning-of-line -
1)
914 ;; insert a hline after each line
915 (while (progn (beginning-of-line 3) (< (point) end
))
916 (org-table-insert-hline))
918 (setq end
(move-marker end
(org-table-end)))
919 ;; replace "+" at beginning and ending of hlines
920 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
921 (replace-match "\\1+-"))
923 (while (re-search-forward "-|[ \t]*$" end t
)
924 (replace-match "-+"))
928 ;;; Navigation and Structure Editing
931 (defun org-table-begin (&optional table-type
)
932 "Find the beginning of the table and return its position.
933 With a non-nil optional argument TABLE-TYPE, return the beginning
934 of a table.el-type table. This function assumes point is on
937 (org-element-property :post-affiliated
(org-element-at-point)))
939 (and (re-search-backward org-table-border-regexp nil t
)
940 (line-beginning-position 2))))
944 (defun org-table-end (&optional table-type
)
945 "Find the end of the table and return its position.
946 With a non-nil optional argument TABLE-TYPE, return the end of
947 a table.el-type table. This function assumes point is on
951 (goto-char (org-element-property :end
(org-element-at-point)))
952 (skip-chars-backward " \t\n")
953 (line-beginning-position 2))
954 ((re-search-forward org-table-border-regexp nil t
)
956 ;; When the line right after the table is the last line in
957 ;; the buffer with trailing spaces but no final newline
958 ;; character, be sure to catch the correct ending at its
959 ;; beginning. In any other case, ending is expected to be
961 (t (goto-char (point-max))
962 (skip-chars-backward " \t")
963 (if (bolp) (point) (line-end-position))))))
966 (defun org-table-next-field ()
967 "Go to the next field in the current table, creating new lines as needed.
968 Before doing so, re-align the table if necessary."
970 (org-table-maybe-eval-formula)
971 (org-table-maybe-recalculate-line)
972 (when (and org-table-automatic-realign
973 org-table-may-need-update
)
975 (let ((end (org-table-end)))
976 (if (org-at-table-hline-p)
980 (re-search-forward "|" end
)
981 (if (looking-at "[ \t]*$")
982 (re-search-forward "|" end
))
983 (if (and (looking-at "-")
984 org-table-tab-jumps-over-hlines
985 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
986 (goto-char (match-beginning 1)))
989 (beginning-of-line 0)
990 (org-table-insert-row 'below
))
991 (if (looking-at " ") (forward-char 1))))
993 (org-table-insert-row 'below
)))))
996 (defun org-table-previous-field ()
997 "Go to the previous field in the table.
998 Before doing so, re-align the table if necessary."
1000 (org-table-justify-field-maybe)
1001 (org-table-maybe-recalculate-line)
1002 (when (and org-table-automatic-realign
1003 org-table-may-need-update
)
1005 (when (org-at-table-hline-p)
1007 (let ((start (org-table-begin))
1011 (search-backward "|" start nil
2)
1012 (while (looking-at-p "|\\(?:-\\|[ \t]*$\\)")
1013 (search-backward "|" start
)))
1016 (user-error "Cannot move to previous table field"))))
1017 (when (looking-at "| ?")
1018 (goto-char (match-end 0))))
1020 (defun org-table-beginning-of-field (&optional n
)
1021 "Move to the beginning of the current table field.
1022 If already at or before the beginning, move to the beginning of the
1024 With numeric argument N, move N-1 fields backward first."
1026 (let ((pos (point)))
1029 (org-table-previous-field))
1030 (if (not (re-search-backward "|" (point-at-bol 0) t
))
1031 (user-error "No more table fields before the current")
1032 (goto-char (match-end 0))
1033 (and (looking-at " ") (forward-char 1)))
1034 (when (>= (point) pos
) (org-table-beginning-of-field 2))))
1036 (defun org-table-end-of-field (&optional n
)
1037 "Move to the end of the current table field.
1038 If already at or after the end, move to the end of the next table field.
1039 With numeric argument N, move N-1 fields forward first."
1041 (let ((pos (point)))
1044 (org-table-next-field))
1045 (when (re-search-forward "|" (point-at-eol 1) t
)
1047 (skip-chars-backward " ")
1048 (when (and (equal (char-before (point)) ?|
) (equal (char-after (point)) ?\s
))
1050 (when (<= (point) pos
) (org-table-end-of-field 2))))
1053 (defun org-table-next-row ()
1054 "Go to the next row (same column) in the current table.
1055 Before doing so, re-align the table if necessary."
1057 (org-table-maybe-eval-formula)
1058 (org-table-maybe-recalculate-line)
1059 (if (and org-table-automatic-realign
1060 org-table-may-need-update
)
1062 (let ((col (org-table-current-column)))
1063 (beginning-of-line 2)
1064 (when (or (not (org-at-table-p))
1065 (org-at-table-hline-p))
1066 (beginning-of-line 0)
1067 (org-table-insert-row 'below
))
1068 (org-table-goto-column col
)
1069 (skip-chars-backward "^|\n\r")
1070 (when (looking-at " ") (forward-char))))
1072 (defun org-table-get (line column
)
1073 "Get the field in table line LINE, column COLUMN.
1074 If LINE is larger than the number of data lines in the table, the function
1075 returns nil. However, if COLUMN is too large, we will simply return an
1077 If LINE is nil, use the current line.
1078 If COLUMN is nil, use the current column."
1079 (setq column
(or column
(org-table-current-column)))
1081 (and (or (not line
) (org-table-goto-line line
))
1082 (org-trim (org-table-get-field column
)))))
1084 (defun org-table-put (line column value
&optional align
)
1085 "Put VALUE into line LINE, column COLUMN.
1086 When ALIGN is set, also realign the table."
1087 (setq column
(or column
(org-table-current-column)))
1088 (prog1 (save-excursion
1089 (and (or (not line
) (org-table-goto-line line
))
1090 (progn (org-table-goto-column column nil
'force
) t
)
1091 (org-table-get-field column value
)))
1092 (and align
(org-table-align))))
1094 (defun org-table-current-line ()
1095 "Return the index of the current data line."
1096 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1098 (goto-char (org-table-begin))
1099 (while (and (re-search-forward org-table-dataline-regexp end t
)
1101 (< (point-at-eol) pos
))))
1104 (defun org-table-current-column ()
1105 "Return current column number."
1108 (let ((pos (point)))
1110 (if (not (search-forward "|" pos t
)) 0
1112 (separator (if (org-at-table-hline-p) "[+|]" "|")))
1113 (while (re-search-forward separator pos t
) (cl-incf column
))
1116 (defun org-table-current-dline ()
1117 "Find out what table data line we are in.
1118 Only data lines count for this."
1121 (pos (line-beginning-position)))
1122 (goto-char (org-table-begin))
1123 (while (<= (point) pos
)
1124 (when (looking-at org-table-dataline-regexp
) (cl-incf c
))
1128 (defun org-table-goto-line (N)
1129 "Go to the Nth data line in the current table.
1130 Return t when the line exists, nil if it does not exist."
1131 (goto-char (org-table-begin))
1132 (let ((end (org-table-end)) (cnt 0))
1133 (while (and (re-search-forward org-table-dataline-regexp end t
)
1134 (< (setq cnt
(1+ cnt
)) N
)))
1138 (defun org-table-blank-field ()
1139 "Blank the current table field or active region."
1141 (org-table-check-inside-data-field)
1142 (if (and (called-interactively-p 'any
) (org-region-active-p))
1143 (let (org-table-clip)
1144 (org-table-cut-region (region-beginning) (region-end)))
1145 (skip-chars-backward "^|")
1147 (if (looking-at "|[^|\n]+")
1148 (let* ((pos (match-beginning 0))
1149 (match (match-string 0))
1150 (len (org-string-width match
)))
1151 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1152 (goto-char (+ 2 pos
))
1153 (substring match
1)))))
1155 (defun org-table-get-field (&optional n replace
)
1156 "Return the value of the field in column N of current row.
1157 N defaults to current column. If REPLACE is a string, replace
1158 field with this value. The return value is always the old
1160 (when n
(org-table-goto-column n
))
1161 (skip-chars-backward "^|\n")
1162 (if (or (bolp) (looking-at-p "[ \t]*$"))
1163 ;; Before first column or after last one.
1165 (looking-at "[^|\r\n]*")
1166 (let* ((pos (match-beginning 0))
1167 (val (buffer-substring pos
(match-end 0))))
1169 (org-table-with-shrunk-field
1170 (replace-match (if (equal replace
"") " " replace
) t t
)))
1171 (goto-char (min (line-end-position) (1+ pos
)))
1175 (defun org-table-field-info (_arg)
1176 "Show info about the current field, and highlight any reference at point."
1178 (unless (org-at-table-p) (user-error "Not at a table"))
1181 (let* ((pos (point))
1182 (col (org-table-current-column))
1183 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1184 (name (car (rassoc (list (count-lines org-table-current-begin-pos
1185 (line-beginning-position))
1187 org-table-named-field-locations
)))
1188 (eql (org-table-expand-lhs-ranges
1191 (cons (org-table-formula-handle-first/last-rc
(car e
))
1193 (org-table-get-stored-formulas))))
1194 (dline (org-table-current-dline))
1195 (ref (format "@%d$%d" dline col
))
1196 (ref1 (org-table-convert-refs-to-an ref
))
1197 ;; Prioritize field formulas over column formulas.
1198 (fequation (or (assoc name eql
) (assoc ref eql
)))
1199 (cequation (assoc (format "$%d" col
) eql
))
1200 (eqn (or fequation cequation
)))
1201 (let ((p (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))))
1202 (when p
(setq eqn p
)))
1204 (ignore-errors (org-table-show-reference 'local
))
1205 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1207 (if cname
(concat " or $" cname
) "")
1209 (if name
(concat " or $" name
) "")
1210 ;; FIXME: formula info not correct if special table line
1212 (concat ", formula: "
1213 (org-table-formula-to-user
1215 (if (or (string-prefix-p "$" (car eqn
))
1216 (string-prefix-p "@" (car eqn
)))
1219 (car eqn
) "=" (cdr eqn
))))
1222 (defun org-table-goto-field (ref &optional create-column-p
)
1223 "Move point to a specific field in the current table.
1225 REF is either the name of a field its absolute reference, as
1226 a string. No column is created unless CREATE-COLUMN-P is
1227 non-nil. If it is a function, it is called with the column
1228 number as its argument as is used as a predicate to know if the
1229 column can be created.
1231 This function assumes the table is already analyzed (i.e., using
1232 `org-table-analyze')."
1235 ((cdr (assoc ref org-table-named-field-locations
)))
1236 ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref
)
1237 (list (condition-case nil
1238 (aref org-table-dlines
1239 (string-to-number (match-string 1 ref
)))
1240 (error (user-error "Invalid row number in %s" ref
)))
1241 (string-to-number (match-string 2 ref
))))
1242 (t (user-error "Unknown field: %s" ref
))))
1243 (line (car coordinates
))
1244 (column (nth 1 coordinates
))
1245 (create-new-column (if (functionp create-column-p
)
1246 (funcall create-column-p column
)
1249 (goto-char org-table-current-begin-pos
)
1251 (org-table-goto-column column nil create-new-column
))))
1254 (defun org-table-goto-column (n &optional on-delim force
)
1255 "Move the cursor to the Nth column in the current table line.
1256 With optional argument ON-DELIM, stop with point before the left delimiter
1258 If there are less than N fields, just go to after the last delimiter.
1259 However, when FORCE is non-nil, create new columns if necessary."
1261 (beginning-of-line 1)
1263 (while (and (> (setq n
(1- n
)) -
1)
1264 (or (search-forward "|" (point-at-eol) t
)
1266 (progn (end-of-line 1)
1267 (skip-chars-backward "^|")
1270 (when (and force
(not (looking-at ".*|")))
1271 (save-excursion (end-of-line 1) (insert " | ")))
1274 (if (looking-at " ") (forward-char 1)))))
1277 (defun org-table-insert-column ()
1278 "Insert a new column into the table."
1280 (unless (org-at-table-p) (user-error "Not at a table"))
1281 (org-table-find-dataline)
1282 (let ((col (max 1 (org-table-current-column)))
1283 (beg (org-table-begin))
1284 (end (copy-marker (org-table-end)))
1285 (shrunk-columns (org-table--list-shrunk-columns)))
1286 (org-table-expand beg end
)
1289 (while (< (point) end
)
1290 (unless (org-at-table-hline-p)
1291 (org-table-goto-column col t
)
1292 (unless (search-forward "|" (line-end-position) t
2)
1293 ;; Add missing vertical bar at the end of the row.
1298 (org-table-goto-column (1+ col
))
1300 ;; Shift appropriately stored shrunk column numbers, then hide the
1302 (org-table--shrink-columns (mapcar (lambda (c) (if (<= c col
) c
(1+ c
)))
1305 (set-marker end nil
)
1306 ;; Fix TBLFM formulas, if desirable.
1307 (when (or (not org-table-fix-formulas-confirm
)
1308 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1309 (org-table-fix-formulas "$" nil
(1- col
) 1)
1310 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1312 (defun org-table-find-dataline ()
1313 "Find a data line in the current table, which is needed for column commands.
1314 This function assumes point is in a table. Raise an error when
1315 there is no data row below."
1316 (or (not (org-at-table-hline-p))
1317 (let ((col (current-column))
1318 (end (org-table-end)))
1320 (while (and (< (point) end
) (org-at-table-hline-p))
1322 (when (>= (point) end
)
1323 (user-error "Cannot find data row for column operation"))
1324 (org-move-to-column col
)
1327 (defun org-table-line-to-dline (line &optional above
)
1328 "Turn a buffer line number into a data line number.
1330 If there is no data line in this line, return nil.
1332 If there is no matching dline (most likely the reference was
1333 a hline), the first dline below it is used. When ABOVE is
1334 non-nil, the one above is used."
1336 (max (1- (length org-table-dlines
))))
1337 (cond ((or (> (aref org-table-dlines min
) line
)
1338 (< (aref org-table-dlines max
) line
))
1340 ((= line
(aref org-table-dlines max
)) max
)
1342 (while (> (- max min
) 1)
1343 (let* ((mean (/ (+ max min
) 2))
1344 (v (aref org-table-dlines mean
)))
1345 (cond ((= v line
) (throw 'exit mean
))
1346 ((> v line
) (setq max mean
))
1347 (t (setq min mean
)))))
1348 (cond ((= line
(aref org-table-dlines max
)) max
)
1349 ((= line
(aref org-table-dlines min
)) min
)
1353 (defun org-table--swap-cells (row1 col1 row2 col2
)
1354 "Swap two cells indicated by the coordinates provided.
1355 ROW1, COL1, ROW2, COL2 are integers indicating the row/column
1356 position of the two cells that will be swapped in the table."
1357 (let ((content1 (org-table-get row1 col1
))
1358 (content2 (org-table-get row2 col2
)))
1359 (org-table-put row1 col1 content2
)
1360 (org-table-put row2 col2 content1
)))
1362 (defun org-table--move-cell (direction)
1363 "Move the current cell in a cardinal direction.
1364 DIRECTION is a symbol among `up', `down', `left', and `right'.
1365 The contents the current cell are swapped with cell in the
1366 indicated direction. Raise an error if the move cannot be done."
1367 (let ((row-shift (pcase direction
(`up -
1) (`down
1) (_ 0)))
1368 (column-shift (pcase direction
(`left -
1) (`right
1) (_ 0))))
1369 (when (and (= 0 row-shift
) (= 0 column-shift
))
1370 (error "Invalid direction: %S" direction
))
1371 ;; Initialize `org-table-current-ncol' and `org-table-dlines'.
1373 (let* ((row (org-table-current-line))
1374 (column (org-table-current-column))
1375 (target-row (+ row row-shift
))
1376 (target-column (+ column column-shift
))
1377 (org-table-current-nrow (1- (length org-table-dlines
))))
1378 (when (or (< target-column
1)
1380 (> target-column org-table-current-ncol
)
1381 (> target-row org-table-current-nrow
))
1382 (user-error "Cannot move cell further"))
1383 (org-table--swap-cells row column target-row target-column
)
1384 (org-table-goto-line target-row
)
1385 (org-table-goto-column target-column
))))
1388 (defun org-table-move-cell-up ()
1389 "Move a single cell up in a table.
1390 Swap with anything in target cell."
1392 (unless (org-table-check-inside-data-field)
1393 (error "No table at point"))
1394 (org-table--move-cell 'up
)
1398 (defun org-table-move-cell-down ()
1399 "Move a single cell down in a table.
1400 Swap with anything in target cell."
1402 (unless (org-table-check-inside-data-field)
1403 (error "No table at point"))
1404 (org-table--move-cell 'down
)
1408 (defun org-table-move-cell-left ()
1409 "Move a single cell left in a table.
1410 Swap with anything in target cell."
1412 (unless (org-table-check-inside-data-field)
1413 (error "No table at point"))
1414 (org-table--move-cell 'left
)
1418 (defun org-table-move-cell-right ()
1419 "Move a single cell right in a table.
1420 Swap with anything in target cell."
1422 (unless (org-table-check-inside-data-field)
1423 (error "No table at point"))
1424 (org-table--move-cell 'right
)
1428 (defun org-table-delete-column ()
1429 "Delete a column from the table."
1431 (unless (org-at-table-p) (user-error "Not at a table"))
1432 (org-table-find-dataline)
1433 (org-table-check-inside-data-field nil t
)
1434 (let* ((col (org-table-current-column))
1435 (beg (org-table-begin))
1436 (end (copy-marker (org-table-end)))
1437 (shrunk-columns (remq col
(org-table--list-shrunk-columns))))
1438 (org-table-expand beg end
)
1439 (org-table-save-field
1441 (while (< (point) end
)
1442 (if (org-at-table-hline-p)
1444 (org-table-goto-column col t
)
1445 (and (looking-at "|[^|\n]+|")
1446 (replace-match "|")))
1448 (org-table-goto-column (max 1 (1- col
)))
1450 ;; Shift appropriately stored shrunk column numbers, then hide the
1452 (org-table--shrink-columns (mapcar (lambda (c) (if (< c col
) c
(1- c
)))
1455 (set-marker end nil
)
1456 ;; Fix TBLFM formulas, if desirable.
1457 (when (or (not org-table-fix-formulas-confirm
)
1458 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1459 (org-table-fix-formulas
1460 "$" (list (cons (number-to-string col
) "INVALID")) col -
1 col
)
1461 (org-table-fix-formulas
1462 "$LR" (list (cons (number-to-string col
) "INVALID")) col -
1 col
))))
1465 (defun org-table-move-column-right ()
1466 "Move column to the right."
1468 (org-table-move-column nil
))
1471 (defun org-table-move-column-left ()
1472 "Move column to the left."
1474 (org-table-move-column 'left
))
1477 (defun org-table-move-column (&optional left
)
1478 "Move the current column to the right. With arg LEFT, move to the left."
1480 (unless (org-at-table-p) (user-error "Not at a table"))
1481 (org-table-find-dataline)
1482 (org-table-check-inside-data-field nil t
)
1483 (let* ((col (org-table-current-column))
1484 (col1 (if left
(1- col
) col
))
1485 (colpos (if left
(1- col
) (1+ col
)))
1486 (beg (org-table-begin))
1487 (end (copy-marker (org-table-end))))
1488 (when (and left
(= col
1))
1489 (user-error "Cannot move column further left"))
1490 (when (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1491 (user-error "Cannot move column further right"))
1492 (let ((shrunk-columns (org-table--list-shrunk-columns)))
1493 (org-table-expand beg end
)
1494 (org-table-save-field
1496 (while (< (point) end
)
1497 (unless (org-at-table-hline-p)
1498 (org-table-goto-column col1 t
)
1499 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1501 (match-beginning 1) (match-end 1)
1502 (match-beginning 2) (match-end 2))))
1504 (org-table-goto-column colpos
)
1506 ;; Shift appropriately stored shrunk column numbers, then shrink
1507 ;; the columns again.
1508 (org-table--shrink-columns
1510 (cond ((and (= col c
) left
) (1- c
))
1512 ((and (= col
(1+ c
)) left
) (1+ c
))
1513 ((and (= col
(1- c
)) (not left
) (1- c
)))
1517 (set-marker end nil
)
1518 ;; Fix TBLFM formulas, if desirable.
1519 (when (or (not org-table-fix-formulas-confirm
)
1520 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1521 (org-table-fix-formulas
1522 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1523 (cons (number-to-string colpos
) (number-to-string col
))))
1524 (org-table-fix-formulas
1526 (cons (number-to-string col
) (number-to-string colpos
))
1527 (cons (number-to-string colpos
) (number-to-string col
))))))))
1530 (defun org-table-move-row-down ()
1531 "Move table row down."
1533 (org-table-move-row nil
))
1536 (defun org-table-move-row-up ()
1537 "Move table row up."
1539 (org-table-move-row 'up
))
1542 (defun org-table-move-row (&optional up
)
1543 "Move the current table line down. With arg UP, move it up."
1545 (let* ((col (current-column))
1547 (hline1p (save-excursion (beginning-of-line 1)
1548 (looking-at org-table-hline-regexp
)))
1549 (dline1 (org-table-current-dline))
1550 (dline2 (+ dline1
(if up -
1 1)))
1553 (when (and up
(= (point-min) (line-beginning-position)))
1554 (user-error "Cannot move row further"))
1555 (beginning-of-line tonew
)
1556 (when (or (and (not up
) (eobp)) (not (org-at-table-p)))
1558 (user-error "Cannot move row further"))
1559 (org-table-with-shrunk-columns
1560 (setq hline2p
(looking-at org-table-hline-regexp
))
1562 (let ((row (delete-and-extract-region (line-beginning-position)
1563 (line-beginning-position 2))))
1564 (beginning-of-line tonew
)
1565 (unless (bolp) (insert "\n")) ;at eob without a newline
1567 (unless (bolp) (insert "\n")) ;missing final newline in ROW
1568 (beginning-of-line 0)
1569 (org-move-to-column col
)
1570 (unless (or hline1p hline2p
1571 (not (or (not org-table-fix-formulas-confirm
)
1572 (funcall org-table-fix-formulas-confirm
1573 "Fix formulas? "))))
1574 (org-table-fix-formulas
1576 (cons (number-to-string dline1
) (number-to-string dline2
))
1577 (cons (number-to-string dline2
) (number-to-string dline1
)))))))))
1580 (defun org-table-insert-row (&optional arg
)
1581 "Insert a new row above the current line into the table.
1582 With prefix ARG, insert below the current line."
1584 (unless (org-at-table-p) (user-error "Not at a table"))
1585 (org-table-with-shrunk-columns
1586 (let* ((line (buffer-substring (line-beginning-position) (line-end-position)))
1587 (new (org-table-clean-line line
)))
1588 ;; Fix the first field if necessary
1589 (when (string-match "^[ \t]*| *[#*$] *|" line
)
1590 (setq new
(replace-match (match-string 0 line
) t t new
)))
1591 (beginning-of-line (if arg
2 1))
1592 ;; Buffer may not end of a newline character, so ensure
1593 ;; (beginning-of-line 2) moves point to a new line.
1594 (unless (bolp) (insert "\n"))
1595 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1596 (beginning-of-line 0)
1597 (re-search-forward "| ?" (line-end-position) t
)
1598 (when (or org-table-may-need-update org-table-overlay-coordinates
)
1600 (when (or (not org-table-fix-formulas-confirm
)
1601 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1602 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1)))))
1605 (defun org-table-insert-hline (&optional above
)
1606 "Insert a horizontal-line below the current line into the table.
1607 With prefix ABOVE, insert above the current line."
1609 (unless (org-at-table-p) (user-error "Not at a table"))
1610 (when (eobp) (save-excursion (insert "\n")))
1611 (unless (string-match-p "|[ \t]*$" (org-current-line-string))
1613 (org-table-with-shrunk-columns
1614 (let ((line (org-table-clean-line
1615 (buffer-substring (point-at-bol) (point-at-eol))))
1616 (col (current-column)))
1617 (while (string-match "|\\( +\\)|" line
)
1618 (setq line
(replace-match
1619 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1620 ?-
) "|") t t line
)))
1621 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1622 (beginning-of-line (if above
1 2))
1624 (beginning-of-line (if above
1 -
1))
1625 (org-move-to-column col
)
1626 (when org-table-overlay-coordinates
(org-table-align)))))
1629 (defun org-table-hline-and-move (&optional same-column
)
1630 "Insert a hline and move to the row below that line."
1632 (let ((col (org-table-current-column)))
1633 (org-table-maybe-eval-formula)
1634 (org-table-maybe-recalculate-line)
1635 (org-table-insert-hline)
1637 (if (looking-at "\n[ \t]*|-")
1638 (progn (insert "\n|") (org-table-align))
1639 (org-table-next-field))
1640 (if same-column
(org-table-goto-column col
))))
1642 (defun org-table-clean-line (s)
1643 "Convert a table line S into a string with only \"|\" and space.
1644 In particular, this does handle wide and invisible characters."
1645 (if (string-match "^[ \t]*|-" s
)
1646 ;; It's a hline, just map the characters
1647 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1648 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1649 (setq s
(replace-match
1650 (concat "|" (make-string (org-string-width (match-string 1 s
))
1656 (defun org-table-kill-row ()
1657 "Delete the current row or horizontal line from the table."
1659 (unless (org-at-table-p) (user-error "Not at a table"))
1660 (let ((col (current-column))
1661 (dline (and (not (org-match-line org-table-hline-regexp
))
1662 (org-table-current-dline))))
1663 (org-table-with-shrunk-columns
1664 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1665 (if (not (org-at-table-p)) (beginning-of-line 0))
1666 (org-move-to-column col
)
1668 (or (not org-table-fix-formulas-confirm
)
1669 (funcall org-table-fix-formulas-confirm
"Fix formulas? ")))
1670 (org-table-fix-formulas
1671 "@" (list (cons (number-to-string dline
) "INVALID")) dline -
1 dline
)))))
1674 (defun org-table-cut-region (beg end
)
1675 "Copy region in table to the clipboard and blank all relevant fields.
1676 If there is no active region, use just the field at point."
1678 (if (org-region-active-p) (region-beginning) (point))
1679 (if (org-region-active-p) (region-end) (point))))
1680 (org-table-copy-region beg end
'cut
))
1683 (defun org-table-copy-down (n)
1684 "Copy the value of the current field one row below.
1686 If the field at the cursor is empty, copy the content of the
1687 nearest non-empty field above. With argument N, use the Nth
1690 If the current field is not empty, it is copied down to the next
1691 row, and the cursor is moved with it. Therefore, repeating this
1692 command causes the column to be filled row-by-row.
1694 If the variable `org-table-copy-increment' is non-nil and the
1695 field is an integer or a timestamp, it will be incremented while
1696 copying. By default, increment by the difference between the
1697 value in the current field and the one in the field above. To
1698 increment using a fixed integer, set `org-table-copy-increment'
1699 to a number. In the case of a timestamp, increment by days."
1701 (let* ((colpos (org-table-current-column))
1702 (col (current-column))
1703 (field (save-excursion (org-table-get-field)))
1704 (field-up (or (save-excursion
1705 (org-table-get (1- (org-table-current-line))
1706 (org-table-current-column))) ""))
1707 (non-empty (string-match "[^ \t]" field
))
1708 (non-empty-up (string-match "[^ \t]" field-up
))
1709 (beg (org-table-begin))
1712 (org-table-check-inside-data-field)
1717 (while (progn (beginning-of-line 1)
1718 (re-search-backward org-table-dataline-regexp
1720 (org-table-goto-column colpos t
)
1721 (if (and (looking-at
1722 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1723 (<= (setq n
(1- n
)) 0))
1724 (throw 'exit
(match-string 1))))))
1727 (while (progn (beginning-of-line 1)
1728 (re-search-backward org-table-dataline-regexp
1730 (org-table-goto-column colpos t
)
1731 (if (and (looking-at
1732 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1733 (<= (setq n
(1- n
)) 0))
1734 (throw 'exit
(match-string 1))))))
1735 (setq non-empty-up
(and field-up
(string-match "[^ \t]" field-up
))))
1736 ;; Above field was not empty, go down to the next row. Skip
1737 ;; alignment since we do it at the end of the process anyway.
1738 (setq txt
(org-trim field
))
1739 (let ((org-table-may-need-update nil
)) (org-table-next-row))
1740 (org-table-blank-field))
1741 (if non-empty-up
(setq txt-up
(org-trim field-up
)))
1743 ((numberp org-table-copy-increment
) org-table-copy-increment
)
1744 (txt-up (cond ((and (string-match org-ts-regexp3 txt-up
)
1745 (string-match org-ts-regexp3 txt
))
1746 (- (org-time-string-to-absolute txt
)
1747 (org-time-string-to-absolute txt-up
)))
1748 ((string-match org-ts-regexp3 txt
) 1)
1749 ((string-match "\\([-+]\\)?[0-9]*\\(?:\\.[0-9]+\\)?" txt-up
)
1750 (- (string-to-number txt
)
1751 (string-to-number (match-string 0 txt-up
))))
1755 (user-error "No non-empty field found")
1756 (if (and org-table-copy-increment
1757 (not (equal orig-n
0))
1758 (string-match-p "^[-+^/*0-9eE.]+$" txt
)
1759 (< (string-to-number txt
) 100000000))
1760 (setq txt
(calc-eval (concat txt
"+" (number-to-string inc
)))))
1762 (org-move-to-column col
)
1763 (if (and org-table-copy-increment
(org-at-timestamp-p 'lax
))
1764 (org-timestamp-up-day inc
)
1765 (org-table-maybe-recalculate-line))
1767 (org-move-to-column col
))))
1770 (defun org-table-copy-region (beg end
&optional cut
)
1771 "Copy rectangular region in table to clipboard.
1772 A special clipboard is used which can only be accessed with
1773 `org-table-paste-rectangle'. Return the region copied, as a list
1774 of lists of fields."
1776 (if (org-region-active-p) (region-beginning) (point))
1777 (if (org-region-active-p) (region-end) (point))
1778 current-prefix-arg
))
1779 (goto-char (min beg end
))
1780 (org-table-check-inside-data-field)
1781 (let ((beg (line-beginning-position))
1782 (c01 (org-table-current-column))
1784 (goto-char (max beg end
))
1785 (org-table-check-inside-data-field nil t
)
1786 (let* ((end (copy-marker (line-end-position)))
1787 (c02 (org-table-current-column))
1788 (column-start (min c01 c02
))
1789 (column-end (max c01 c02
))
1790 (column-number (1+ (- column-end column-start
)))
1791 (rpl (and cut
" ")))
1793 (while (< (point) end
)
1794 (unless (org-at-table-hline-p)
1795 ;; Collect every cell between COLUMN-START and COLUMN-END.
1797 (dotimes (c column-number
)
1798 (push (org-table-get-field (+ c column-start
) rpl
) cols
))
1799 (push (nreverse cols
) region
)))
1801 (set-marker end nil
))
1802 (when cut
(org-table-align))
1803 (message (substitute-command-keys "Cells in the region copied, use \
1804 \\[org-table-paste-rectangle] to paste them in a table."))
1805 (setq org-table-clip
(nreverse region
))))
1808 (defun org-table-paste-rectangle ()
1809 "Paste a rectangular region into a table.
1810 The upper right corner ends up in the current field. All involved fields
1811 will be overwritten. If the rectangle does not fit into the present table,
1812 the table is enlarged as needed. The process ignores horizontal separator
1815 (unless (consp org-table-clip
)
1816 (user-error "First cut/copy a region to paste!"))
1817 (org-table-check-inside-data-field)
1818 (let* ((column (org-table-current-column))
1819 (org-table-automatic-realign nil
))
1820 (org-table-save-field
1821 (dolist (row org-table-clip
)
1822 (while (org-at-table-hline-p) (forward-line))
1823 ;; If we left the table, create a new row.
1824 (when (and (bolp) (not (looking-at "[ \t]*|")))
1826 (org-table-next-field))
1829 (org-table-goto-column c nil
'force
)
1830 (org-table-get-field nil field
)
1836 ;;; Follow Field minor mode
1838 (define-minor-mode org-table-follow-field-mode
1839 "Minor mode to make the table field editor window follow the cursor.
1840 When this mode is active, the field editor window will always show the
1841 current field. The mode exits automatically when the cursor leaves the
1842 table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
1843 nil
" TblFollow" nil
1844 (if org-table-follow-field-mode
1845 (add-hook 'post-command-hook
'org-table-follow-fields-with-editor
1847 (remove-hook 'post-command-hook
'org-table-follow-fields-with-editor
'local
)
1848 (let* ((buf (get-buffer "*Org Table Edit Field*"))
1849 (win (and buf
(get-buffer-window buf
))))
1850 (when win
(delete-window win
))
1852 (with-current-buffer buf
1853 (move-marker org-field-marker nil
))
1854 (kill-buffer buf
)))))
1857 (defun org-table-edit-field (arg)
1858 "Edit table field in a different window.
1859 This is mainly useful for fields that contain hidden parts.
1861 When called with a `\\[universal-argument]' prefix, just make the full field
1862 visible so that it can be edited in place.
1864 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
1865 toggle `org-table-follow-field-mode'."
1867 (unless (org-at-table-p) (user-error "Not at a table"))
1870 (org-table-follow-field-mode (if org-table-follow-field-mode -
1 1)))
1872 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1873 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1874 (remove-text-properties b e
'(invisible t intangible t
))
1875 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1876 (font-lock-fontify-block))))
1878 (let ((pos (point-marker))
1880 (if (eq org-table-use-standard-references t
)
1881 (concat (org-number-to-letters (org-table-current-column))
1882 (int-to-string (org-table-current-dline)))
1883 (concat "@" (int-to-string (org-table-current-dline))
1884 "$" (int-to-string (org-table-current-column)))))
1885 (field (org-table-get-field))
1886 (cw (current-window-configuration))
1889 (org-switch-to-buffer-other-window "*Org Table Edit Field*")
1890 (when (and (local-variable-p 'org-field-marker
)
1891 (markerp org-field-marker
))
1892 (move-marker org-field-marker nil
))
1894 (insert "#\n# Edit field " coord
" and finish with C-c C-c\n#\n")
1895 (let ((org-inhibit-startup t
)) (org-mode))
1897 (setq truncate-lines nil
)
1899 (goto-char (setq p
(point-max)))
1900 (insert (org-trim field
))
1901 (remove-text-properties p
(point-max) '(invisible t intangible t
))
1903 (setq-local org-finish-function
'org-table-finish-edit-field
)
1904 (setq-local org-window-configuration cw
)
1905 (setq-local org-field-marker pos
)
1906 (message "Edit and finish with C-c C-c")))))
1908 (defun org-table-follow-fields-with-editor ()
1909 (if (and org-table-exit-follow-field-mode-when-leaving-table
1910 (not (org-at-table-p)))
1911 ;; We have left the table, exit the follow mode
1912 (org-table-follow-field-mode -
1)
1913 (when (org-table-check-inside-data-field 'noerror
)
1914 (let ((win (selected-window)))
1915 (org-table-edit-field nil
)
1916 (org-fit-window-to-buffer)
1917 (select-window win
)))))
1919 (defun org-table-finish-edit-field ()
1920 "Finish editing a table data field.
1921 Remove all newline characters, insert the result into the table, realign
1922 the table and kill the editing buffer."
1923 (let ((pos org-field-marker
)
1924 (cw org-window-configuration
)
1925 (cb (current-buffer))
1927 (goto-char (point-min))
1928 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1929 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1930 (replace-match " "))
1931 (setq text
(org-trim (buffer-string)))
1932 (set-window-configuration cw
)
1934 (select-window (get-buffer-window (marker-buffer pos
)))
1936 (move-marker pos nil
)
1937 (org-table-check-inside-data-field)
1938 (org-table-get-field nil text
)
1940 (message "New field value inserted")))
1945 (defun org-table-current-field-formula (&optional key noerror
)
1946 "Return the formula active for the current field.
1948 Assumes that table is already analyzed. If KEY is given, return
1949 the key to this formula. Otherwise return the formula preceded
1950 with \"=\" or \":=\"."
1951 (let* ((line (count-lines org-table-current-begin-pos
1952 (line-beginning-position)))
1953 (row (org-table-line-to-dline line
)))
1956 (let* ((col (org-table-current-column))
1957 (name (car (rassoc (list line col
)
1958 org-table-named-field-locations
)))
1959 (scol (format "$%d" col
))
1960 (ref (format "@%d$%d" (org-table-current-dline) col
))
1961 (stored-list (org-table-get-stored-formulas noerror
))
1962 (ass (or (assoc name stored-list
)
1963 (assoc ref stored-list
)
1964 (assoc scol stored-list
))))
1965 (cond (key (car ass
))
1966 (ass (concat (if (string-match-p "^[0-9]+$" (car ass
)) "=" ":=")
1969 (t (error "No formula active for the current field")))))
1971 (defun org-table-get-formula (&optional equation named
)
1972 "Read a formula from the minibuffer, offer stored formula as default.
1973 When NAMED is non-nil, look for a named equation."
1974 (let* ((stored-list (org-table-get-stored-formulas))
1975 (name (car (rassoc (list (count-lines org-table-current-begin-pos
1976 (line-beginning-position))
1977 (org-table-current-column))
1978 org-table-named-field-locations
)))
1979 (ref (format "@%d$%d"
1980 (org-table-current-dline)
1981 (org-table-current-column)))
1983 ((not named
) (format "$%d" (org-table-current-column)))
1984 ((and name
(not (string-match "\\`LR[0-9]+\\'" name
))) name
)
1986 (name (or name ref
))
1987 (org-table-may-need-update nil
)
1988 (stored (cdr (assoc scol stored-list
)))
1990 ((and stored equation
(string-match-p "^ *=? *$" equation
))
1992 ((stringp equation
) equation
)
1994 (org-table-formula-from-user
1996 (org-table-formula-to-user
1997 (format "%s formula %s=" (if named
"Field" "Column") scol
))
1998 (if stored
(org-table-formula-to-user stored
) "")
1999 'org-table-formula-history
)))))
2001 (unless (org-string-nw-p eq
)
2003 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
2004 (org-table-store-formulas stored-list
)
2005 (user-error "Formula removed"))
2006 (when (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
2007 (when (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
2008 (when (and name
(not named
))
2009 ;; We set the column equation, delete the named one.
2010 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
2013 (setcdr (assoc scol stored-list
) eq
)
2014 (setq stored-list
(cons (cons scol eq
) stored-list
)))
2015 (when (or mustsave
(not (equal stored eq
)))
2016 (org-table-store-formulas stored-list
))
2019 (defun org-table-store-formulas (alist &optional location
)
2020 "Store the list of formulas below the current table.
2021 If optional argument LOCATION is a buffer position, insert it at
2025 (progn (goto-char location
) (beginning-of-line))
2026 (goto-char (org-table-end)))
2027 (let ((case-fold-search t
))
2028 (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+TBLFM:\\)\\(.*\n?\\)")
2030 ;; Don't overwrite TBLFM, we might use text properties to
2032 (goto-char (match-beginning 3))
2033 (delete-region (match-beginning 3) (match-end 0)))
2035 (insert (or (match-string 2) "#+TBLFM:")))
2037 (mapconcat (lambda (x) (concat (car x
) "=" (cdr x
)))
2038 (sort alist
#'org-table-formula-less-p
)
2042 (defsubst org-table-formula-make-cmp-string
(a)
2043 (when (string-match "\\`\\$[<>]" a
)
2044 (let ((arrow (string-to-char (substring a
1))))
2045 ;; Fake a high number to make sure this is sorted at the end.
2046 (setq a
(org-table-formula-handle-first/last-rc a
))
2047 (setq a
(format "$%d" (+ 10000
2048 (if (= arrow ?
<) -
1000 0)
2049 (string-to-number (substring a
1)))))))
2051 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2055 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2057 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2059 (concat "@@" (match-string 5 a
))))))
2061 (defun org-table-formula-less-p (a b
)
2062 "Compare two formulas for sorting."
2063 (let ((as (org-table-formula-make-cmp-string (car a
)))
2064 (bs (org-table-formula-make-cmp-string (car b
))))
2065 (and as bs
(string< as bs
))))
2068 (defun org-table-get-stored-formulas (&optional noerror location
)
2069 "Return an alist with the stored formulas directly after current table.
2070 By default, only return active formulas, i.e., formulas located
2071 on the first line after the table. However, if optional argument
2072 LOCATION is a buffer position, consider the formulas there."
2075 (progn (goto-char location
) (beginning-of-line))
2076 (goto-char (org-table-end)))
2077 (let ((case-fold-search t
))
2078 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
2079 (let ((strings (org-split-string (match-string-no-properties 2)
2082 (dolist (string strings
(nreverse eq-alist
))
2083 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|\\$\\([_a-zA-Z0-9]+\\|\
2084 \[<>]+\\)\\) *= *\\(.*[^ \t]\\)"
2087 (let ((m (match-string 1 string
)))
2089 ((not (match-end 2)) m
)
2090 ;; Is it a column reference?
2091 ((string-match-p "\\`\\$\\([0-9]+\\|[<>]+\\)\\'" m
) m
)
2092 ;; Since named columns are not possible in
2093 ;; LHS, assume this is a named field.
2094 (t (match-string 2 string
)))))
2095 (rhs (match-string 3 string
)))
2096 (push (cons lhs rhs
) eq-alist
)
2098 ((not (member lhs seen
)) (push lhs seen
))
2101 "Double definition `%s=' in TBLFM line, please fix by hand"
2107 "Double definition `%s=' in TBLFM line, please fix by hand"
2110 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2111 "Modify the equations after the table structure has been edited.
2112 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2113 For all numbers larger than LIMIT, shift them by DELTA."
2115 (goto-char (org-table-end))
2116 (while (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:"))
2117 (let ((msg "The formulas in #+TBLFM have been updated")
2118 (re (concat key
"\\([0-9]+\\)"))
2121 (if (or (equal key
"$") (equal key
"$LR"))
2122 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2123 (regexp-quote key
) remove
)
2124 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2127 (while (re-search-forward re2
(point-at-eol) t
)
2128 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2129 (if (equal (char-before (match-beginning 0)) ?.
)
2131 "Change makes TBLFM term %s invalid, use undo to recover"
2133 (replace-match "")))))
2134 (while (re-search-forward re
(point-at-eol) t
)
2135 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2136 (setq s
(match-string 1) n
(string-to-number s
))
2138 ((setq a
(assoc s replace
))
2139 (replace-match (concat key
(cdr a
)) t t
)
2141 ((and limit
(> n limit
))
2142 (replace-match (concat key
(int-to-string (+ n delta
))) t t
)
2147 (defun org-table-maybe-eval-formula ()
2148 "Check if the current field starts with \"=\" or \":=\".
2149 If yes, store the formula and apply it."
2150 ;; We already know we are in a table. Get field will only return a formula
2151 ;; when appropriate. It might return a separator line, but no problem.
2152 (when org-table-formula-evaluate-inline
2153 (let* ((field (org-trim (or (org-table-get-field) "")))
2155 (when (string-match "^:?=\\(.*[^=]\\)$" field
)
2156 (setq named
(equal (string-to-char field
) ?
:)
2157 eq
(match-string 1 field
))
2158 (org-table-eval-formula (and named
'(4))
2159 (org-table-formula-from-user eq
))))))
2162 (defun org-table-rotate-recalc-marks (&optional newchar
)
2163 "Rotate the recalculation mark in the first column.
2164 If in any row, the first field is not consistent with a mark,
2165 insert a new column for the markers.
2166 When there is an active region, change all the lines in the region,
2167 after prompting for the marking character.
2168 After each change, a message will be displayed indicating the meaning
2171 (unless (org-at-table-p) (user-error "Not at a table"))
2172 (let* ((region (org-region-active-p))
2174 (save-excursion (goto-char (region-beginning))
2175 (copy-marker (line-beginning-position)))))
2177 (save-excursion (goto-char (region-end))
2178 (copy-marker (line-beginning-position)))))
2179 (l (copy-marker (line-beginning-position)))
2180 (col (org-table-current-column))
2183 (read-char-exclusive
2184 "Change region to what mark? Type # * ! $ or SPC: "))
2188 (goto-char (org-table-begin))
2190 "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t
))))
2191 (when (and newchar
(not (assoc newchar org-recalc-marks
)))
2192 (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
2194 (when l1
(goto-char l1
))
2197 (unless (looking-at org-table-dataline-regexp
)
2198 (user-error "Not at a table data line")))
2199 (when no-special-column
2200 (org-table-goto-column 1)
2201 (org-table-insert-column))
2202 (let ((previous-line-end (line-end-position))
2206 (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
2208 (t (cadr (member (match-string 1)
2209 (append (mapcar #'car org-recalc-marks
)
2211 ;; Rotate mark in first row.
2212 (org-table-get-field 1 (format " %s " newchar
))
2213 ;; Rotate marks in additional rows if a region is active.
2217 (while (<= (point) l2
)
2218 (when (looking-at org-table-dataline-regexp
)
2219 (org-table-get-field 1 (format " %s " newchar
)))
2221 ;; Only align if rotation actually changed lines' length.
2222 (when (/= previous-line-end
(line-end-position)) (org-table-align)))
2224 (org-table-goto-column (if no-special-column
(1+ col
) col
))
2225 (when l1
(set-marker l1 nil
))
2226 (when l2
(set-marker l2 nil
))
2228 (when (called-interactively-p 'interactive
)
2229 (message "%s" (cdr (assoc newchar org-recalc-marks
))))))
2232 (defun org-table-maybe-recalculate-line ()
2233 "Recompute the current line if marked for it, and if we haven't just done it."
2235 (and org-table-allow-automatic-line-recalculation
2236 (not (and (memq last-command org-recalc-commands
)
2237 (eq org-last-recalc-line
(line-beginning-position))))
2238 (save-excursion (beginning-of-line 1)
2239 (looking-at org-table-auto-recalculate-regexp
))
2240 (org-table-recalculate) t
))
2243 (defun org-table-eval-formula (&optional arg equation
2244 suppress-align suppress-const
2245 suppress-store suppress-analysis
)
2246 "Replace the table field value at the cursor by the result of a calculation.
2248 In a table, this command replaces the value in the current field with the
2249 result of a formula. It also installs the formula as the \"current\" column
2250 formula, by storing it in a special line below the table. When called
2251 with a `\\[universal-argument]' prefix the formula is installed as a \
2254 When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
2255 insert the active equation for the field
2256 back into the current field, so that it can be edited there. This is \
2258 in order to use \\<org-table-fedit-map>`\\[org-table-show-reference]' to \
2259 check the referenced fields.
2261 When called, the command first prompts for a formula, which is read in
2262 the minibuffer. Previously entered formulas are available through the
2263 history list, and the last used formula is offered as a default.
2264 These stored formulas are adapted correctly when moving, inserting, or
2265 deleting columns with the corresponding commands.
2267 The formula can be any algebraic expression understood by the Calc package.
2268 For details, see the Org mode manual.
2270 This function can also be called from Lisp programs and offers
2271 additional arguments: EQUATION can be the formula to apply. If this
2272 argument is given, the user will not be prompted.
2274 SUPPRESS-ALIGN is used to speed-up recursive calls by by-passing
2277 SUPPRESS-CONST suppresses the interpretation of constants in the
2278 formula, assuming that this has been done already outside the
2281 SUPPRESS-STORE means the formula should not be stored, either
2282 because it is already stored, or because it is a modified
2283 equation that should not overwrite the stored one.
2285 SUPPRESS-ANALYSIS prevents analyzing the table and checking
2288 (unless suppress-analysis
2289 (org-table-check-inside-data-field nil t
)
2290 (org-table-analyze))
2291 (if (equal arg
'(16))
2292 (let ((eq (org-table-current-field-formula)))
2293 (org-table-get-field nil eq
)
2295 (setq org-table-may-need-update t
))
2297 (ndown (if (integerp arg
) arg
1))
2298 (org-table-automatic-realign nil
)
2299 (case-fold-search nil
)
2301 (formula (if (and equation suppress-store
)
2303 (org-table-get-formula equation
(equal arg
'(4)))))
2304 (n0 (org-table-current-column))
2305 (org-tbl-calc-modes (copy-sequence org-calc-default-modes
))
2306 (numbers nil
) ; was a variable, now fixed default
2308 n form form0 formrpl formrg bw fmt x ev orig c lispp literal
2309 duration duration-output-format
)
2310 ;; Parse the format string. Since we have a lot of modes, this is
2311 ;; a lot of work. However, I think calc still uses most of the time.
2312 (if (string-match ";" formula
)
2313 (let ((tmp (org-split-string formula
";")))
2314 (setq formula
(car tmp
)
2315 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2317 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2318 (setq c
(string-to-char (match-string 1 fmt
))
2319 n
(string-to-number (match-string 2 fmt
)))
2321 (setq org-tbl-calc-modes
2322 (org-table--set-calc-mode 'calc-internal-prec n
))
2323 (setq org-tbl-calc-modes
2324 (org-table--set-calc-mode
2326 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2327 (?s . sci
) (?e . eng
))))
2329 (setq fmt
(replace-match "" t t fmt
)))
2330 (if (string-match "[tTU]" fmt
)
2331 (let ((ff (match-string 0 fmt
)))
2332 (setq duration t numbers t
2333 duration-output-format
2334 (cond ((equal ff
"T") nil
)
2335 ((equal ff
"t") org-table-duration-custom-format
)
2336 ((equal ff
"U") 'hh
:mm
))
2337 fmt
(replace-match "" t t fmt
))))
2338 (if (string-match "N" fmt
)
2340 fmt
(replace-match "" t t fmt
)))
2341 (if (string-match "L" fmt
)
2343 fmt
(replace-match "" t t fmt
)))
2344 (if (string-match "E" fmt
)
2346 fmt
(replace-match "" t t fmt
)))
2347 (while (string-match "[DRFS]" fmt
)
2348 (setq org-tbl-calc-modes
2349 (org-table--set-calc-mode (match-string 0 fmt
)))
2350 (setq fmt
(replace-match "" t t fmt
)))
2351 (unless (string-match "\\S-" fmt
)
2353 (when (and (not suppress-const
) org-table-formula-use-constants
)
2354 (setq formula
(org-table-formula-substitute-names formula
)))
2355 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2356 (setq formula
(org-table-formula-handle-first/last-rc formula
))
2358 (setq fields
(org-split-string
2360 (buffer-substring-no-properties
2361 (line-beginning-position) (line-end-position)))
2363 ;; replace fields with duration values if relevant
2366 (mapcar (lambda (x) (org-table-time-string-to-seconds x
))
2369 (setq fields
(mapcar
2371 (if (string-match "\\S-" x
)
2372 (number-to-string (string-to-number x
))
2375 (setq ndown
(1- ndown
))
2376 (setq form
(copy-sequence formula
)
2377 lispp
(and (> (length form
) 2) (equal (substring form
0 2) "'(")))
2378 (if (and lispp literal
) (setq lispp
'literal
))
2380 ;; Insert row and column number of formula result field
2381 (while (string-match "[@$]#" form
)
2386 (if (equal (substring form
(match-beginning 0)
2387 (1+ (match-beginning 0)))
2389 (org-table-current-dline)
2390 (org-table-current-column))))
2393 ;; Check for old vertical references
2394 (org-table--error-on-old-row-references form
)
2395 ;; Insert remote references
2396 (setq form
(org-table-remote-reference-indirection form
))
2397 (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2401 (org-table-make-reference
2402 (let ((rmtrng (org-table-get-remote-range
2403 (match-string 1 form
) (match-string 2 form
))))
2406 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) rmtrng
)
2407 (org-table-time-string-to-seconds rmtrng
))
2409 keep-empty numbers lispp
))
2411 ;; Insert complex ranges
2412 (while (and (string-match org-table-range-regexp form
)
2413 (> (length (match-string 0 form
)) 1))
2416 (org-table-get-range
2417 (match-string 0 form
) org-table-current-begin-pos n0
)))
2420 (org-table-make-reference
2421 ;; possibly handle durations
2424 (mapcar (lambda(x) (org-table-time-string-to-seconds x
)) formrg
)
2425 (org-table-time-string-to-seconds formrg
))
2427 keep-empty numbers lispp
)))
2428 (if (not (save-match-data
2429 (string-match (regexp-quote form
) formrpl
)))
2430 (setq form
(replace-match formrpl t t form
))
2431 (user-error "Spreadsheet error: invalid reference \"%s\"" form
)))
2432 ;; Insert simple ranges, i.e. included in the current row.
2433 (while (string-match
2434 "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
2439 (org-table-make-reference
2441 (+ (if (match-end 2) n0
0)
2442 (string-to-number (match-string 1 form
))
2444 (+ (if (match-end 4) n0
0)
2445 (string-to-number (match-string 3 form
))))
2446 keep-empty numbers lispp
))
2449 ;; Insert the references to fields in same row
2450 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2451 (setq n
(+ (string-to-number (match-string 1 form
))
2452 (if (match-end 2) n0
0))
2453 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
)
2454 formrpl
(save-match-data
2455 (org-table-make-reference
2456 x keep-empty numbers lispp
)))
2459 (string-match (regexp-quote formula
) formrpl
)))
2460 (user-error "Invalid field specifier \"%s\""
2461 (match-string 0 form
)))
2462 (setq form
(replace-match formrpl t t form
)))
2465 (setq ev
(condition-case nil
2466 (eval (eval (read form
)))
2468 ev
(if (numberp ev
) (number-to-string ev
) ev
)
2469 ev
(if duration
(org-table-time-seconds-to-string
2470 (string-to-number ev
)
2471 duration-output-format
) ev
))
2473 ;; Use <...> time-stamps so that Calc can handle them.
2475 (replace-regexp-in-string org-ts-regexp-inactive
"<\\1>" form
))
2476 ;; Internationalize local time-stamps by setting locale to
2479 (replace-regexp-in-string
2482 (let ((system-time-locale "C"))
2484 (org-time-stamp-format
2485 (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts
))
2486 (apply #'encode-time
2487 (save-match-data (org-parse-time-string ts
))))))
2490 (setq ev
(if (and duration
(string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form
))
2492 (calc-eval (cons form org-tbl-calc-modes
)
2493 (when (and (not keep-empty
) numbers
) 'num
)))
2494 ev
(if duration
(org-table-time-seconds-to-string
2495 (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev
)
2496 (string-to-number (org-table-time-string-to-seconds ev
))
2497 (string-to-number ev
))
2498 duration-output-format
)
2501 (when org-table-formula-debug
2502 (with-output-to-temp-buffer "*Substitution History*"
2503 (princ (format "Substitution history of formula
2507 $1-> %s\n" orig formula form0 form
))
2509 (princ (format " %s^\nError: %s"
2510 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2511 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2513 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2514 (setq bw
(get-buffer-window "*Substitution History*"))
2515 (org-fit-window-to-buffer bw
)
2516 (unless (and (called-interactively-p 'any
) (not ndown
))
2517 (unless (let (inhibit-redisplay)
2518 (y-or-n-p "Debugging Formula. Continue to next? "))
2520 (user-error "Abort"))
2523 (when (consp ev
) (setq fmt nil ev
"#ERROR"))
2524 (org-table-justify-field-maybe
2525 (format org-table-formula-field-format
2527 ((not (stringp ev
)) ev
)
2528 (fmt (format fmt
(string-to-number ev
)))
2529 ;; Replace any active time stamp in the result with
2530 ;; an inactive one. Dates in tables are likely
2531 ;; piece of regular data, not meant to appear in the
2533 (t (replace-regexp-in-string org-ts-regexp
"[\\1]" ev
)))))
2534 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2535 (call-interactively 'org-return
)
2537 (and down
(org-table-maybe-recalculate-line))
2538 (or suppress-align
(and org-table-may-need-update
2539 (org-table-align))))))
2541 (defun org-table-put-field-property (prop value
)
2543 (put-text-property (progn (skip-chars-backward "^|") (point))
2544 (progn (skip-chars-forward "^|") (point))
2547 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2548 "Get a calc vector from a column, according to descriptor DESC.
2550 Optional arguments TBEG and COL can give the beginning of the table and
2551 the current column, to avoid unnecessary parsing.
2553 HIGHLIGHT means just highlight the range.
2555 When CORNERS-ONLY is set, only return the corners of the range as
2556 a list (line1 column1 line2 column2) where line1 and line2 are
2557 line numbers relative to beginning of table, or TBEG, and column1
2558 and column2 are table column numbers."
2559 (let* ((desc (if (string-match-p "\\`\\$[0-9]+\\.\\.\\$[0-9]+\\'" desc
)
2560 (replace-regexp-in-string "\\$" "@0$" desc
)
2562 (col (or col
(org-table-current-column)))
2563 (tbeg (or tbeg
(org-table-begin)))
2564 (thisline (count-lines tbeg
(line-beginning-position))))
2565 (unless (string-match org-table-range-regexp desc
)
2566 (user-error "Invalid table range specifier `%s'" desc
))
2567 (let ((rangep (match-end 3))
2568 (r1 (let ((r (and (match-end 1) (match-string 1 desc
))))
2569 (or (save-match-data
2570 (and (org-string-nw-p r
)
2571 (org-table--descriptor-line r thisline
)))
2573 (r2 (let ((r (and (match-end 4) (match-string 4 desc
))))
2574 (or (save-match-data
2575 (and (org-string-nw-p r
)
2576 (org-table--descriptor-line r thisline
)))
2578 (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc
) 1))))
2579 (if (or (not c
) (= (string-to-number c
) 0)) col
2580 (+ (string-to-number c
)
2581 (if (memq (string-to-char c
) '(?- ?
+)) col
0)))))
2582 (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc
) 1))))
2583 (if (or (not c
) (= (string-to-number c
) 0)) col
2584 (+ (string-to-number c
)
2585 (if (memq (string-to-char c
) '(?- ?
+)) col
0))))))
2587 (if (and (not corners-only
)
2588 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2591 (forward-line (- r1 thisline
))
2592 (while (not (looking-at org-table-dataline-regexp
))
2594 (prog1 (org-trim (org-table-get-field c1
))
2595 (when highlight
(org-table-highlight-rectangle))))
2596 ;; A range, return a vector. First sort the numbers to get
2597 ;; a regular rectangle.
2598 (let ((first-row (min r1 r2
))
2599 (last-row (max r1 r2
))
2600 (first-column (min c1 c2
))
2601 (last-column (max c1 c2
)))
2602 (if corners-only
(list first-row first-column last-row last-column
)
2603 ;; Copy the range values into a list.
2604 (forward-line (- first-row thisline
))
2605 (while (not (looking-at org-table-dataline-regexp
))
2607 (cl-incf first-row
))
2608 (org-table-goto-column first-column
)
2609 (let ((beg (point)))
2610 (forward-line (- last-row first-row
))
2611 (while (not (looking-at org-table-dataline-regexp
))
2613 (org-table-goto-column last-column
)
2614 (let ((end (point)))
2616 (org-table-highlight-rectangle
2617 beg
(progn (skip-chars-forward "^|\n") (point))))
2618 ;; Return string representation of calc vector.
2621 (org-table-copy-region beg end
))))))))))))
2623 (defun org-table--descriptor-line (desc cline
)
2624 "Return relative line number corresponding to descriptor DESC.
2625 The cursor is currently in relative line number CLINE."
2626 (if (string-match "\\`[0-9]+\\'" desc
)
2627 (aref org-table-dlines
(string-to-number desc
))
2628 (when (or (not (string-match
2629 "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
2632 (and (not (match-end 3)) (not (match-end 6)))
2633 (and (match-end 3) (match-end 6) (not (match-end 5))))
2634 (user-error "Invalid row descriptor `%s'" desc
))
2635 (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
2636 (hdir (match-string 2 desc
))
2637 (odir (match-string 5 desc
))
2638 (on (and (match-end 6) (string-to-number (match-string 6 desc
))))
2639 (rel (and (match-end 6)
2640 (or (and (match-end 1) (not (match-end 3)))
2642 (when (and hn
(not hdir
))
2645 (when (eq (aref org-table-current-line-types
0) 'hline
) (cl-decf hn
)))
2646 (when (and (not hn
) on
(not odir
)) (user-error "Should never happen"))
2649 (org-table--row-type 'hline hn cline
(equal hdir
"-") nil desc
)))
2652 (org-table--row-type 'dline on cline
(equal odir
"-") rel desc
)))
2655 (defun org-table--row-type (type n i backwards relative desc
)
2656 "Return relative line of Nth row with type TYPE.
2657 Search starts from relative line I. When BACKWARDS in non-nil,
2658 look before I. When RELATIVE is non-nil, the reference is
2659 relative. DESC is the original descriptor that started the
2660 search, as a string."
2661 (let ((l (length org-table-current-line-types
)))
2664 (while (and (cl-incf i
(if backwards -
1 1))
2667 (not (eq (aref org-table-current-line-types i
) type
))
2668 ;; We are going to cross a hline. Check if this is
2669 ;; an authorized move.
2672 ((not (eq (aref org-table-current-line-types i
) 'hline
)))
2673 ((eq org-table-relative-ref-may-cross-hline t
))
2674 ((eq org-table-relative-ref-may-cross-hline
'error
)
2675 (user-error "Row descriptor %s crosses hline" desc
))
2676 (t (cl-decf i
(if backwards -
1 1)) ; Step back.
2677 (throw :exit nil
)))))))
2678 (cond ((or (< i
0) (>= i l
))
2679 (user-error "Row descriptor %s leads outside table" desc
))
2680 ;; The last hline doesn't exist. Instead, point to last row
2682 ((= i
(1- l
)) (1- i
))
2685 (defun org-table--error-on-old-row-references (s)
2686 (when (string-match "&[-+0-9I]" s
)
2687 (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
2689 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2690 "Convert list ELEMENTS to something appropriate to insert into formula.
2691 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2692 NUMBERS indicates that everything should be converted to numbers.
2693 LISPP non-nil means to return something appropriate for a Lisp
2694 list, `literal' is for the format specifier L."
2695 ;; Calc nan (not a number) is used for the conversion of the empty
2696 ;; field to a reference for several reasons: (i) It is accepted in a
2697 ;; Calc formula (e. g. "" or "()" would result in a Calc error).
2698 ;; (ii) In a single field (not in range) it can be distinguished
2699 ;; from "(nan)" which is the reference made from a single field
2700 ;; containing "nan".
2701 (if (stringp elements
)
2704 (if (eq lispp
'literal
)
2706 (if (and (eq elements
"") (not keep-empty
))
2709 (if numbers
(string-to-number elements
) elements
))))
2710 (if (string-match "\\S-" elements
)
2712 (when numbers
(setq elements
(number-to-string
2713 (string-to-number elements
))))
2714 (concat "(" elements
")"))
2715 (if (or (not keep-empty
) numbers
) "(0)" "nan")))
2720 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2722 (setq elements
(or elements
'())) ; if delq returns nil then we need '()
2726 (if (eq lispp
'literal
)
2728 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2730 (concat "[" (mapconcat
2732 (if (string-match "\\S-" x
)
2734 (number-to-string (string-to-number x
))
2736 (if (or (not keep-empty
) numbers
) "0" "nan")))
2740 (defun org-table-message-once-per-second (t1 &rest args
)
2741 "If there has been more than one second since T1, display message.
2742 ARGS are passed as arguments to the `message' function. Returns
2743 current time if a message is printed, otherwise returns T1. If
2744 T1 is nil, always messages."
2745 (let ((curtime (current-time)))
2746 (if (or (not t1
) (< 0 (nth 1 (time-subtract curtime t1
))))
2747 (progn (apply 'message args
)
2752 (defun org-table-recalculate (&optional all noalign
)
2753 "Recalculate the current table line by applying all stored formulas.
2755 With prefix arg ALL, do this for all lines in the table.
2757 When called with a `\\[universal-argument] \\[universal-argument]' prefix, or \
2758 if ALL is the symbol `iterate',
2759 recompute the table until it no longer changes.
2761 If NOALIGN is not nil, do not re-align the table after the computations
2762 are done. This is typically used internally to save time, if it is
2763 known that the table will be realigned a little later anyway."
2765 (unless (memq this-command org-recalc-commands
)
2766 (push this-command org-recalc-commands
))
2767 (unless (org-at-table-p) (user-error "Not at a table"))
2768 (if (or (eq all
'iterate
) (equal all
'(16)))
2771 (let* ((eqlist (sort (org-table-get-stored-formulas)
2772 (lambda (a b
) (string< (car a
) (car b
)))))
2773 (inhibit-redisplay (not debug-on-error
))
2774 (line-re org-table-dataline-regexp
)
2775 (log-first-time (current-time))
2776 (log-last-time log-first-time
)
2778 beg end eqlcol eqlfield
)
2779 ;; Insert constants in all formulas.
2781 (org-table-save-field
2782 ;; Expand equations, then split the equation list between
2783 ;; column formulas and field formulas.
2785 (let* ((rhs (org-table-formula-substitute-names
2786 (org-table-formula-handle-first/last-rc
(cdr eq
))))
2789 (org-table-formula-handle-first/last-rc
2791 ((string-match "\\`@-?I+" old-lhs
)
2792 (user-error "Can't assign to hline relative reference"))
2793 ((string-match "\\`\\$[<>]" old-lhs
)
2794 (let ((new (org-table-formula-handle-first/last-rc
2796 (when (assoc new eqlist
)
2797 (user-error "\"%s=\" formula tries to overwrite \
2798 existing formula for column %s"
2803 (if (string-match-p "\\`\\$[0-9]+\\'" lhs
)
2804 (push (cons lhs rhs
) eqlcol
)
2805 (push (cons lhs rhs
) eqlfield
))))
2806 (setq eqlcol
(nreverse eqlcol
))
2807 ;; Expand ranges in lhs of formulas
2808 (setq eqlfield
(org-table-expand-lhs-ranges (nreverse eqlfield
)))
2809 ;; Get the correct line range to process.
2812 (setq end
(copy-marker (org-table-end)))
2813 (goto-char (setq beg org-table-current-begin-pos
))
2815 ((re-search-forward org-table-calculate-mark-regexp end t
)
2816 ;; This is a table with marked lines, compute selected
2818 (setq line-re org-table-recalculate-regexp
))
2819 ;; Move forward to the first non-header line.
2820 ((and (re-search-forward org-table-dataline-regexp end t
)
2821 (re-search-forward org-table-hline-regexp end t
)
2822 (re-search-forward org-table-dataline-regexp end t
))
2823 (setq beg
(match-beginning 0)))
2824 ;; Just leave BEG at the start of the table.
2826 (setq beg
(line-beginning-position)
2827 end
(copy-marker (line-beginning-position 2))))
2829 ;; Mark named fields untouchable. Also check if several
2830 ;; field/range formulas try to set the same field.
2831 (remove-text-properties beg end
'(:org-untouchable t
))
2832 (let ((current-line (count-lines org-table-current-begin-pos
2833 (line-beginning-position)))
2835 (dolist (eq eqlfield
)
2836 (let* ((name (car eq
))
2837 (location (assoc name org-table-named-field-locations
))
2838 (eq-line (or (nth 1 location
)
2839 (and (string-match "\\`@\\([0-9]+\\)" name
)
2840 (aref org-table-dlines
2842 (match-string 1 name
))))))
2845 ;; Turn field coordinates associated to NAME
2846 ;; into an absolute reference.
2848 (org-table-line-to-dline eq-line
)
2851 (when (member reference seen-fields
)
2852 (user-error "Several field/range formulas try to set %s"
2854 (push reference seen-fields
)
2855 (when (or all
(eq eq-line current-line
))
2856 (org-table-goto-field name
)
2857 (org-table-put-field-property :org-untouchable t
)))))
2858 ;; Evaluate the column formulas, but skip fields covered by
2861 (while (re-search-forward line-re end t
)
2862 (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
2863 ;; Unprotected line, recalculate.
2867 (org-table-message-once-per-second
2869 "Re-applying formulas to full table...(line %d)" cnt
)))
2870 (if (markerp org-last-recalc-line
)
2871 (move-marker org-last-recalc-line
(line-beginning-position))
2872 (setq org-last-recalc-line
2873 (copy-marker (line-beginning-position))))
2874 (dolist (entry eqlcol
)
2875 (goto-char org-last-recalc-line
)
2876 (org-table-goto-column
2877 (string-to-number (substring (car entry
) 1)) nil
'force
)
2878 (unless (get-text-property (point) :org-untouchable
)
2879 (org-table-eval-formula
2880 nil
(cdr entry
) 'noalign
'nocst
'nostore
'noanalysis
)))))
2881 ;; Evaluate the field formulas.
2882 (dolist (eq eqlfield
)
2883 (let ((reference (car eq
))
2886 (org-table-message-once-per-second
2887 (and all log-last-time
)
2888 "Re-applying formula to field: %s" (car eq
)))
2889 (org-table-goto-field
2891 ;; Possibly create a new column, as long as
2892 ;; `org-table-formula-create-columns' allows it.
2893 (let ((column-count (progn (end-of-line)
2894 (1- (org-table-current-column)))))
2896 (when (> column
1000)
2897 (user-error "Formula column target too large"))
2898 (and (> column column-count
)
2899 (or (eq org-table-formula-create-columns t
)
2900 (and (eq org-table-formula-create-columns
'warn
)
2902 (org-display-warning
2903 "Out-of-bounds formula added columns")
2905 (and (eq org-table-formula-create-columns
'prompt
)
2907 "Out-of-bounds formula. Add columns? "))
2909 "Missing columns in the table. Aborting"))))))
2910 (org-table-eval-formula nil formula t t t t
))))
2911 ;; Clean up markers and internal text property.
2912 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
2913 (set-marker end nil
)
2915 (when org-table-may-need-update
(org-table-align))
2917 (org-table-message-once-per-second
2918 log-first-time
"Re-applying formulas to %d lines... done" cnt
)))
2919 (org-table-message-once-per-second
2920 (and all log-first-time
) "Re-applying formulas... done")))))
2923 (defun org-table-iterate (&optional arg
)
2924 "Recalculate the table until it does not change anymore.
2925 The maximum number of iterations is 10, but you can choose a different value
2926 with the prefix ARG."
2928 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
2930 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2935 (org-table-recalculate 'all
)
2936 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
2937 (if (not (string= lasttbl thistbl
))
2938 (setq lasttbl thistbl
)
2940 (message "Convergence after %d iterations" i
)
2941 (message "Table was already stable"))
2943 (user-error "No convergence after %d iterations" i
))))
2946 (defun org-table-recalculate-buffer-tables ()
2947 "Recalculate all tables in the current buffer."
2949 (org-with-wide-buffer
2950 (org-table-map-tables
2952 ;; Reason for separate `org-table-align': When repeating
2953 ;; (org-table-recalculate t) `org-table-may-need-update' gets in
2955 (org-table-recalculate t t
)
2960 (defun org-table-iterate-buffer-tables ()
2961 "Iterate all tables in the buffer, to converge inter-table dependencies."
2965 (checksum (md5 (buffer-string)))
2967 (org-with-wide-buffer
2971 (org-table-map-tables (lambda () (org-table-recalculate t t
)) t
)
2972 (if (equal checksum
(setq c1
(md5 (buffer-string))))
2974 (org-table-map-tables #'org-table-align t
)
2975 (message "Convergence after %d iterations" (- imax i
))
2977 (setq checksum c1
)))
2978 (org-table-map-tables #'org-table-align t
)
2979 (user-error "No convergence after %d iterations" imax
)))))
2981 (defun org-table-calc-current-TBLFM (&optional arg
)
2982 "Apply the #+TBLFM in the line at point to the table."
2984 (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
2985 (let ((formula (buffer-substring
2986 (line-beginning-position)
2987 (line-end-position))))
2989 ;; Insert a temporary formula at right after the table
2990 (goto-char (org-table-TBLFM-begin))
2991 (let ((s (point-marker)))
2992 (insert formula
"\n")
2993 (let ((e (point-marker)))
2994 ;; Recalculate the table.
2995 (beginning-of-line 0) ; move to the inserted line
2996 (skip-chars-backward " \r\n\t")
2998 (org-call-with-arg #'org-table-recalculate
(or arg t
))
2999 ;; Delete the formula inserted temporarily.
3002 (set-marker e nil
)))))))
3004 (defun org-table-TBLFM-begin ()
3005 "Find the beginning of the TBLFM lines and return its position.
3006 Return nil when the beginning of TBLFM line was not found."
3008 (when (progn (forward-line 1)
3009 (re-search-backward org-table-TBLFM-begin-regexp nil t
))
3010 (line-beginning-position 2))))
3012 (defun org-table-expand-lhs-ranges (equations)
3013 "Expand list of formulas.
3014 If some of the RHS in the formulas are ranges or a row reference,
3015 expand them to individual field equations for each field. This
3016 function assumes the table is already analyzed (i.e., using
3017 `org-table-analyze')."
3019 (dolist (e equations
(nreverse res
))
3023 ((string-match-p "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs
)
3024 ;; This just refers to one fixed field.
3026 ((string-match-p "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs
)
3027 ;; This just refers to one fixed named field.
3029 ((string-match-p "\\`\\$[0-9]+\\'" lhs
)
3030 ;; Column formulas are treated specially and are not
3033 ((string-match "\\`@[0-9]+\\'" lhs
)
3034 (dotimes (ic org-table-current-ncol
)
3035 (push (cons (propertize (format "%s$%d" lhs
(1+ ic
)) :orig-eqn e
)
3039 (let* ((range (org-table-get-range
3040 lhs org-table-current-begin-pos
1 nil
'corners
))
3041 (r1 (org-table-line-to-dline (nth 0 range
)))
3043 (r2 (org-table-line-to-dline (nth 2 range
) 'above
))
3045 (cl-loop for ir from r1 to r2 do
3046 (cl-loop for ic from c1 to c2 do
3047 (push (cons (propertize
3048 (format "@%d$%d" ir ic
) :orig-eqn e
)
3052 (defun org-table-formula-handle-first/last-rc
(s)
3053 "Replace @<, @>, $<, $> with first/last row/column of the table.
3054 So @< and $< will always be replaced with @1 and $1, respectively.
3055 The advantage of these special markers are that structure editing of
3056 the table will not change them, while @1 and $1 will be modified
3057 when a line/row is swapped out of that privileged position. So for
3058 formulas that use a range of rows or columns, it may often be better
3059 to anchor the formula with \"I\" row markers, or to offset from the
3060 borders of the table using the @< @> $< $> makers."
3061 (let (n nmax len char
(start 0))
3062 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
3065 (setq start
(match-end 3))
3066 (setq nmax
(if (equal (match-string 1 s
) "@")
3067 (1- (length org-table-dlines
))
3068 org-table-current-ncol
)
3069 len
(- (match-end 2) (match-beginning 2))
3070 char
(string-to-char (match-string 2 s
))
3074 (if (or (< n
1) (> n nmax
))
3075 (user-error "Reference \"%s\" in expression \"%s\" points outside table"
3076 (match-string 0 s
) s
))
3077 (setq start
(match-beginning 0))
3078 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
)))))
3081 (defun org-table-formula-substitute-names (f)
3082 "Replace $const with values in string F."
3084 (pp (/= (string-to-char f
) ?
'))
3085 (duration (string-match-p ";.*[Tt].*\\'" f
))
3086 (new (replace-regexp-in-string ; Check for column names.
3087 org-table-column-name-regexp
3089 (concat "$" (cdr (assoc (match-string 1 m
)
3090 org-table-column-names
))))
3092 ;; Parameters and constants.
3095 "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
3097 (if (match-end 2) (setq start
(match-end 2))
3099 ;; When a duration is expected, convert value on the fly.
3102 (let ((v (org-table-get-constant (match-string 1 new
))))
3103 (if (and (org-string-nw-p v
) duration
)
3104 (org-table-time-string-to-seconds v
)
3107 (setq new
(replace-match
3108 (concat (and pp
"(") value
(and pp
")")) t t new
))))))
3109 (if org-table-formula-debug
(propertize new
:orig-formula f
) new
)))
3111 (defun org-table-get-constant (const)
3112 "Find the value for a parameter or constant in a formula.
3113 Parameters get priority."
3114 (or (cdr (assoc const org-table-local-parameters
))
3115 (cdr (assoc const org-table-formula-constants-local
))
3116 (cdr (assoc const org-table-formula-constants
))
3117 (and (fboundp 'constants-get
) (constants-get const
))
3118 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
3119 (org-entry-get nil
(substring const
5) 'inherit
))
3122 (defvar org-table-fedit-map
3123 (let ((map (make-sparse-keymap)))
3124 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
3125 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
3126 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
3127 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
3128 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
3129 (org-defkey map
"\C-c?" 'org-table-show-reference
)
3130 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
3131 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
3132 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
3133 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
3134 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
3135 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
3136 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
3137 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
3138 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
3139 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
3140 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
3141 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
3142 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
3143 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
3146 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
3148 ["Finish and Install" org-table-fedit-finish t
]
3149 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
3150 ["Abort" org-table-fedit-abort t
]
3152 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
3153 ["Complete Lisp Symbol" lisp-complete-symbol t
]
3155 "Shift Reference at Point"
3156 ["Up" org-table-fedit-ref-up t
]
3157 ["Down" org-table-fedit-ref-down t
]
3158 ["Left" org-table-fedit-ref-left t
]
3159 ["Right" org-table-fedit-ref-right t
]
3161 "Change Test Row for Column Formulas"
3162 ["Up" org-table-fedit-line-up t
]
3163 ["Down" org-table-fedit-line-down t
]
3165 ["Scroll Table Window" org-table-fedit-scroll t
]
3166 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
3167 ["Show Table Grid" org-table-fedit-toggle-coordinates
3168 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
3169 org-table-overlay-coordinates
)]
3171 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
3172 :style toggle
:selected org-table-buffer-is-an
]))
3174 (defvar org-table--fedit-source nil
3175 "Position of the TBLFM line being edited.")
3178 (defun org-table-edit-formulas ()
3179 "Edit the formulas of the current table in a separate buffer."
3181 (let ((at-tblfm (org-at-TBLFM-p)))
3182 (unless (or at-tblfm
(org-at-table-p))
3183 (user-error "Not at a table"))
3185 ;; Move point within the table before analyzing it.
3186 (when at-tblfm
(re-search-backward "^[ \t]*|"))
3187 (org-table-analyze))
3188 (let ((key (org-table-current-field-formula 'key
'noerror
))
3189 (eql (sort (org-table-get-stored-formulas t
(and at-tblfm
(point)))
3190 #'org-table-formula-less-p
))
3191 (pos (point-marker))
3192 (source (copy-marker (line-beginning-position)))
3194 (wc (current-window-configuration))
3195 (sel-win (selected-window))
3196 (titles '((column .
"# Column Formulas\n")
3197 (field .
"# Field and Range Formulas\n")
3198 (named .
"# Named Field Formulas\n"))))
3199 (org-switch-to-buffer-other-window "*Edit Formulas*")
3201 ;; Keep global-font-lock-mode from turning on font-lock-mode
3202 (let ((font-lock-global-modes '(not fundamental-mode
)))
3204 (setq-local font-lock-global-modes
(list 'not major-mode
))
3205 (setq-local org-pos pos
)
3206 (setq-local org-table--fedit-source source
)
3207 (setq-local org-window-configuration wc
)
3208 (setq-local org-selected-window sel-win
)
3209 (use-local-map org-table-fedit-map
)
3210 (add-hook 'post-command-hook
#'org-table-fedit-post-command t t
)
3211 (easy-menu-add org-table-fedit-menu
)
3212 (setq startline
(org-current-line))
3215 ((string-match "\\`\\$\\([0-9]+\\|[<>]+\\)\\'"
3218 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3220 (title (assq type titles
)))
3222 (unless (bobp) (insert "\n"))
3224 (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3225 (setq titles
(remove title titles
)))
3226 (when (equal key
(car entry
)) (setq startline
(org-current-line)))
3228 (if (memq (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3229 (car entry
) " = " (cdr entry
) "\n")))
3230 (remove-text-properties 0 (length s
) '(face nil
) s
)
3232 (when (eq org-table-use-standard-references t
)
3233 (org-table-fedit-toggle-ref-type))
3234 (org-goto-line startline
)
3235 (message "%s" (substitute-command-keys "\\<org-mode-map>\
3236 Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
3237 See menu for more commands.")))))
3239 (defun org-table-fedit-post-command ()
3240 (when (not (memq this-command
'(lisp-complete-symbol)))
3241 (let ((win (selected-window)))
3243 (ignore-errors (org-table-show-reference))
3244 (select-window win
)))))
3246 (defun org-table-formula-to-user (s)
3247 "Convert a formula from internal to user representation."
3248 (if (eq org-table-use-standard-references t
)
3249 (org-table-convert-refs-to-an s
)
3252 (defun org-table-formula-from-user (s)
3253 "Convert a formula from user to internal representation."
3254 (if org-table-use-standard-references
3255 (org-table-convert-refs-to-rc s
)
3258 (defun org-table-convert-refs-to-rc (s)
3259 "Convert spreadsheet references from A7 to @7$28.
3260 Works for single references, but also for entire formulas and even the
3263 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start
)
3266 ;; format match, just advance
3267 (setq start
(match-end 0)))
3268 ((and (> (match-beginning 0) 0)
3269 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3270 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3271 ;; 3.e5 or something like this.
3272 (setq start
(match-end 0)))
3273 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3274 ;; (member (match-string 1 s)
3275 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3277 ;; function name, just advance
3278 (setq start
(match-end 0)))
3280 (setq start
(match-beginning 0)
3282 (if (equal (match-string 2 s
) "&")
3283 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3285 (string-to-number (match-string 2 s
))
3286 (org-letters-to-number (match-string 1 s
))))
3290 (defun org-table-convert-refs-to-an (s)
3291 "Convert spreadsheet references from to @7$28 to AB7.
3292 Works for single references, but also for entire formulas and even the
3294 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3295 (setq s
(replace-match
3297 (org-number-to-letters
3298 (string-to-number (match-string 2 s
)))
3299 (string-to-number (match-string 1 s
)))
3301 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3302 (setq s
(replace-match (concat "\\1"
3303 (org-number-to-letters
3304 (string-to-number (match-string 2 s
))) "&")
3308 (defun org-letters-to-number (s)
3309 "Convert a base 26 number represented by letters into an integer.
3310 For example: AB -> 28."
3313 (while (> (length s
) 0)
3314 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3318 (defun org-number-to-letters (n)
3319 "Convert an integer into a base 26 number represented by letters.
3320 For example: 28 -> AB."
3323 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3327 (defun org-table-time-string-to-seconds (s)
3328 "Convert a time string into numerical duration in seconds.
3329 S can be a string matching either -?HH:MM:SS or -?HH:MM.
3330 If S is a string representing a number, keep this number."
3333 (let (hour minus min sec res
)
3335 ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s
))
3336 (setq minus
(< 0 (length (match-string 1 s
)))
3337 hour
(string-to-number (match-string 2 s
))
3338 min
(string-to-number (match-string 3 s
))
3339 sec
(string-to-number (match-string 4 s
)))
3341 (setq res
(- (+ (* hour
3600) (* min
60) sec
)))
3342 (setq res
(+ (* hour
3600) (* min
60) sec
))))
3343 ((and (not (string-match org-ts-regexp-both s
))
3344 (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s
))
3345 (setq minus
(< 0 (length (match-string 1 s
)))
3346 hour
(string-to-number (match-string 2 s
))
3347 min
(string-to-number (match-string 3 s
)))
3349 (setq res
(- (+ (* hour
3600) (* min
60))))
3350 (setq res
(+ (* hour
3600) (* min
60)))))
3351 (t (setq res
(string-to-number s
))))
3352 (number-to-string res
))))
3354 (defun org-table-time-seconds-to-string (secs &optional output-format
)
3355 "Convert a number of seconds to a time string.
3356 If OUTPUT-FORMAT is non-nil, return a number of days, hours,
3357 minutes or seconds."
3358 (let* ((secs0 (abs secs
))
3360 (cond ((eq output-format
'days
)
3361 (format "%.3f" (/ (float secs0
) 86400)))
3362 ((eq output-format
'hours
)
3363 (format "%.2f" (/ (float secs0
) 3600)))
3364 ((eq output-format
'minutes
)
3365 (format "%.1f" (/ (float secs0
) 60)))
3366 ((eq output-format
'seconds
)
3367 (format "%d" secs0
))
3368 ((eq output-format
'hh
:mm
)
3370 (substring (format-seconds
3371 (if org-table-duration-hour-zero-padding
3372 "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
3376 (if org-table-duration-hour-zero-padding
3377 "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
3379 (if (< secs
0) (concat "-" res
) res
)))
3381 (defun org-table-fedit-convert-buffer (function)
3382 "Convert all references in this buffer, using FUNCTION."
3383 (let ((origin (copy-marker (line-beginning-position))))
3384 (goto-char (point-min))
3386 (insert (funcall function
(buffer-substring (point) (line-end-position))))
3387 (delete-region (point) (line-end-position))
3390 (set-marker origin nil
)))
3392 (defun org-table-fedit-toggle-ref-type ()
3393 "Convert all references in the buffer from B3 to @3$2 and back."
3395 (setq-local org-table-buffer-is-an
(not org-table-buffer-is-an
))
3396 (org-table-fedit-convert-buffer
3397 (if org-table-buffer-is-an
3398 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3399 (message "Reference type switched to %s"
3400 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3402 (defun org-table-fedit-ref-up ()
3403 "Shift the reference at point one row/hline up."
3405 (org-table-fedit-shift-reference 'up
))
3407 (defun org-table-fedit-ref-down ()
3408 "Shift the reference at point one row/hline down."
3410 (org-table-fedit-shift-reference 'down
))
3412 (defun org-table-fedit-ref-left ()
3413 "Shift the reference at point one field to the left."
3415 (org-table-fedit-shift-reference 'left
))
3417 (defun org-table-fedit-ref-right ()
3418 "Shift the reference at point one field to the right."
3420 (org-table-fedit-shift-reference 'right
))
3422 (defun org-table--rematch-and-replace (n &optional decr hline
)
3423 "Re-match the group N, and replace it with the shifted reference."
3424 (or (match-end n
) (user-error "Cannot shift reference in this direction"))
3425 (goto-char (match-beginning n
))
3426 (and (looking-at (regexp-quote (match-string n
)))
3427 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3430 (defun org-table-fedit-shift-reference (dir)
3432 ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
3433 (if (memq dir
'(left right
))
3434 (org-table--rematch-and-replace 1 (eq dir
'left
))
3435 (user-error "Cannot shift reference in this direction")))
3436 ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3437 ;; A B3-like reference
3438 (if (memq dir
'(up down
))
3439 (org-table--rematch-and-replace 2 (eq dir
'up
))
3440 (org-table--rematch-and-replace 1 (eq dir
'left
))))
3442 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3443 ;; An internal reference
3444 (if (memq dir
'(up down
))
3445 (org-table--rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3446 (org-table--rematch-and-replace 5 (eq dir
'left
))))))
3448 (defun org-table-shift-refpart (ref &optional decr hline
)
3449 "Shift a reference part REF.
3450 If DECR is set, decrease the references row/column, else increase.
3451 If HLINE is set, this may be a hline reference, it certainly is not
3452 a translation reference."
3454 (let* ((sign (string-match "^[-+]" ref
)) n
)
3456 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3458 ((and hline
(string-match "^I+" ref
))
3459 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3460 (setq n
(+ n
(if decr -
1 1)))
3461 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3463 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3465 (concat sign
(make-string n ?I
)))
3467 ((string-match "^[0-9]+" ref
)
3468 (setq n
(string-to-number (concat sign ref
)))
3469 (setq n
(+ n
(if decr -
1 1)))
3471 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3472 (number-to-string (max 1 n
))))
3474 ((string-match "^[a-zA-Z]+" ref
)
3475 (org-number-to-letters
3476 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3478 (t (user-error "Cannot shift reference"))))))
3480 (defun org-table-fedit-toggle-coordinates ()
3481 "Toggle the display of coordinates in the referenced table."
3483 (let ((pos (marker-position org-pos
)))
3484 (with-current-buffer (marker-buffer org-pos
)
3487 (org-table-toggle-coordinate-overlays)))))
3489 (defun org-table-fedit-finish (&optional arg
)
3490 "Parse the buffer for formula definitions and install them.
3491 With prefix ARG, apply the new formulas to the table."
3493 (org-table-remove-rectangle-highlight)
3494 (when org-table-use-standard-references
3495 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3496 (setq org-table-buffer-is-an nil
))
3498 (sel-win org-selected-window
)
3499 (source org-table--fedit-source
)
3501 (goto-char (point-min))
3502 (while (re-search-forward
3503 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3505 (let ((var (match-string 1))
3506 (form (org-trim (match-string 3))))
3507 (unless (equal form
"")
3508 (while (string-match "[ \t]*\n[ \t]*" form
)
3509 (setq form
(replace-match " " t t form
)))
3510 (when (assoc var eql
)
3511 (user-error "Double formulas for %s" var
))
3512 (push (cons var form
) eql
))))
3513 (set-window-configuration org-window-configuration
)
3514 (select-window sel-win
)
3516 (org-table-store-formulas eql
)
3517 (set-marker pos nil
)
3518 (set-marker source nil
)
3519 (kill-buffer "*Edit Formulas*")
3521 (org-table-recalculate 'all
)
3522 (message "New formulas installed - press C-u C-c C-c to apply."))))
3524 (defun org-table-fedit-abort ()
3525 "Abort editing formulas, without installing the changes."
3527 (org-table-remove-rectangle-highlight)
3528 (let ((pos org-pos
) (sel-win org-selected-window
))
3529 (set-window-configuration org-window-configuration
)
3530 (select-window sel-win
)
3532 (move-marker pos nil
)
3533 (message "Formula editing aborted without installing changes")))
3535 (defun org-table-fedit-lisp-indent ()
3536 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3538 (let ((pos (point)) beg end ind
)
3539 (beginning-of-line 1)
3541 ((looking-at "[ \t]")
3543 (call-interactively 'lisp-indent-line
))
3544 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3545 ((not (fboundp 'pp-buffer
))
3546 (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
3547 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3548 (goto-char (- (match-end 0) 2))
3550 (setq ind
(make-string (current-column) ?\
))
3551 (condition-case nil
(forward-sexp 1)
3553 (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3556 (narrow-to-region beg end
)
3557 (if (eq last-command this-command
)
3559 (goto-char (point-min))
3560 (setq this-command nil
)
3561 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3562 (replace-match " ")))
3564 (untabify (point-min) (point-max))
3565 (goto-char (1+ (point-min)))
3566 (while (re-search-forward "^." nil t
)
3567 (beginning-of-line 1)
3569 (goto-char (point-max))
3570 (org-delete-backward-char 1)))
3574 (defun org-table-fedit-line-up ()
3575 "Move cursor one line up in the window showing the table."
3577 (org-table-fedit-move 'previous-line
))
3579 (defun org-table-fedit-line-down ()
3580 "Move cursor one line down in the window showing the table."
3582 (org-table-fedit-move 'next-line
))
3584 (defun org-table-fedit-move (command)
3585 "Move the cursor in the window showing the table.
3586 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3587 (let ((org-table-allow-automatic-line-recalculation nil
)
3588 (pos org-pos
) (win (selected-window)) p
)
3589 (select-window (get-buffer-window (marker-buffer org-pos
)))
3591 (call-interactively command
)
3592 (while (and (org-at-table-p)
3593 (org-at-table-hline-p))
3594 (call-interactively command
))
3595 (or (org-at-table-p) (goto-char p
))
3596 (move-marker pos
(point))
3597 (select-window win
)))
3599 (defun org-table-fedit-scroll (N)
3601 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3602 (scroll-other-window N
)))
3604 (defun org-table-fedit-scroll-down (N)
3606 (org-table-fedit-scroll (- N
)))
3608 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3609 "Add a new overlay."
3610 (let ((ov (make-overlay beg end
)))
3611 (overlay-put ov
'face
(or face
'secondary-selection
))
3612 (push ov org-table-rectangle-overlays
)))
3614 (defun org-table-highlight-rectangle (&optional beg end face
)
3615 "Highlight rectangular region in a table.
3616 When buffer positions BEG and END are provided, use them to
3617 delimit the region to highlight. Otherwise, refer to point. Use
3618 FACE, when non-nil, for the highlight."
3619 (let* ((beg (or beg
(point)))
3620 (end (or end
(point)))
3626 (cons (line-beginning-position) (org-table-current-column))))
3630 (cons (line-beginning-position) (org-table-current-column)))))
3631 (when (boundp 'org-show-positions
)
3632 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3633 (goto-char (car start-coordinates
))
3634 (let ((column-start (min (cdr start-coordinates
) (cdr end-coordinates
)))
3635 (column-end (max (cdr start-coordinates
) (cdr end-coordinates
)))
3636 (last-row (car end-coordinates
)))
3637 (while (<= (point) last-row
)
3638 (when (looking-at org-table-dataline-regexp
)
3639 (org-table-goto-column column-start
)
3640 (skip-chars-backward "^|\n")
3642 (org-table-goto-column column-end
)
3643 (skip-chars-forward "^|\n")
3644 (org-table-add-rectangle-overlay p
(point) face
)))
3646 (goto-char (car start-coordinates
)))
3647 (add-hook 'before-change-functions
#'org-table-remove-rectangle-highlight
))
3649 (defun org-table-remove-rectangle-highlight (&rest _ignore
)
3650 "Remove the rectangle overlays."
3651 (unless org-inhibit-highlight-removal
3652 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3653 (mapc 'delete-overlay org-table-rectangle-overlays
)
3654 (setq org-table-rectangle-overlays nil
)))
3656 (defvar-local org-table-coordinate-overlays nil
3657 "Collects the coordinate grid overlays, so that they can be removed.")
3659 (defun org-table-overlay-coordinates ()
3660 "Add overlays to the table at point, to show row/column coordinates."
3662 (mapc 'delete-overlay org-table-coordinate-overlays
)
3663 (setq org-table-coordinate-overlays nil
)
3665 (let ((id 0) (ih 0) hline eol str ov
)
3666 (goto-char (org-table-begin))
3667 (while (org-at-table-p)
3668 (setq eol
(point-at-eol))
3669 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
3670 (push ov org-table-coordinate-overlays
)
3671 (setq hline
(looking-at org-table-hline-regexp
))
3672 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3673 (format "%4d" (setq id
(1+ id
)))))
3674 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3677 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3679 (let* ((beg (1+ (match-beginning 0)))
3680 (s1 (format "$%d" ic
))
3681 (s2 (org-number-to-letters ic
))
3682 (str (if (eq t org-table-use-standard-references
) s2 s1
))
3683 (ov (make-overlay beg
(+ beg
(length str
)))))
3684 (push ov org-table-coordinate-overlays
)
3685 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))))
3689 (defun org-table-toggle-coordinate-overlays ()
3690 "Toggle the display of Row/Column numbers in tables."
3692 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3693 (message "Tables Row/Column numbers display turned %s"
3694 (if org-table-overlay-coordinates
"on" "off"))
3695 (when (and (org-at-table-p) org-table-overlay-coordinates
)
3697 (unless org-table-overlay-coordinates
3698 (mapc 'delete-overlay org-table-coordinate-overlays
)
3699 (setq org-table-coordinate-overlays nil
)))
3702 (defun org-table-toggle-formula-debugger ()
3703 "Toggle the formula debugger in tables."
3705 (setq org-table-formula-debug
(not org-table-formula-debug
))
3706 (message "Formula debugging has been turned %s"
3707 (if org-table-formula-debug
"on" "off")))
3710 ;;; Columns Shrinking
3712 (defun org-table--shrunk-field ()
3713 "Non-nil if current field is narrowed.
3714 When non-nil, return the overlay narrowing the field."
3715 (cl-some (lambda (o)
3716 (and (eq 'table-column-hide
(overlay-get o
'org-overlay-type
))
3718 (overlays-at (save-excursion
3719 (skip-chars-forward (if (org-at-table-hline-p) "^+|"
3721 (line-end-position))
3724 (defun org-table--list-shrunk-columns ()
3725 "List currently shrunk columns in table at point."
3727 ;; We really check shrunk columns in current row only. It could
3728 ;; be wrong if all rows do not contain the same number of columns
3729 ;; (i.e. the table is not properly aligned). As a consequence,
3730 ;; some columns may not be shrunk again upon aligning the table.
3732 ;; For example, in the following table, cursor is on first row and
3733 ;; "<>" indicates a shrunk column.
3738 ;; Aligning table from the first row will not shrink again the
3739 ;; second row, which was not visible initially.
3741 ;; However, fixing it requires to check every row, which may be
3742 ;; slow on large tables. Moreover, the hindrance of this
3743 ;; pathological case is very limited.
3745 (search-forward "|")
3746 (let ((separator (if (org-at-table-hline-p) "+" "|"))
3748 (shrunk (and (org-table--shrunk-field) (list 1)))
3749 (end (line-end-position)))
3750 (while (search-forward separator end t
)
3752 (when (org-table--shrunk-field) (push column shrunk
)))
3753 (nreverse shrunk
))))
3755 (defun org-table--make-shrinking-overlay (start end display field
&optional pre
)
3756 "Create an overlay to shrink text between START and END.
3758 Use string DISPLAY instead of the real text between the two
3759 buffer positions. FIELD is the real contents of the field, as
3760 a string, or nil. It is meant to be displayed upon moving the
3761 mouse onto the overlay.
3763 When optional argument PRE is non-nil, assume the overlay is
3764 located at the beginning of the field, and prepend
3765 `org-table-separator-space' to it. Otherwise, concatenate
3766 `org-table-shrunk-column-indicator' at its end.
3768 Return the overlay."
3769 (let ((show-before-edit
3771 ;; Removing one overlay removes all other overlays in the
3773 (mapc #'delete-overlay
3774 (cdr (overlay-get o
'org-table-column-overlays
)))))
3775 (o (make-overlay start end
)))
3776 (overlay-put o
'insert-behind-hooks
(list show-before-edit
))
3777 (overlay-put o
'insert-in-front-hooks
(list show-before-edit
))
3778 (overlay-put o
'modification-hooks
(list show-before-edit
))
3779 (overlay-put o
'org-overlay-type
'table-column-hide
)
3780 (when (stringp field
) (overlay-put o
'help-echo field
))
3781 ;; Make sure overlays stays on top of table coordinates overlays.
3782 ;; See `org-table-overlay-coordinates'.
3783 (overlay-put o
'priority
1)
3784 (let ((d (if pre
(concat org-table-separator-space display
)
3785 (concat display org-table-shrunk-column-indicator
))))
3786 (org-overlay-display o d
'org-table t
))
3789 (defun org-table--shrink-field (width align start end contents
)
3790 "Shrink a table field to a specified width.
3792 WIDTH is an integer representing the number of characters to
3793 display, in addition to `org-table-shrunk-column-indicator'.
3794 ALIGN is the alignment of the current column, as either \"l\",
3795 \"c\" or \"r\". START and END are, respectively, the beginning
3796 and ending positions of the field. CONTENTS is its trimmed
3797 contents, as a string, or `hline' for table rules.
3799 Real field is hidden under one or two overlays. They have the
3800 following properties:
3804 Set to `table-column-hide'. Used to identify overlays
3805 responsible for shrinking columns in a table.
3807 `org-table-column-overlays'
3809 It is a list with the pattern (siblings . COLUMN-OVERLAYS)
3810 where COLUMN-OVERLAYS is the list of all overlays hiding the
3813 Whenever the text behind or next to the overlay is modified, all
3814 the overlays in the column are deleted, effectively displaying
3817 Return a list of overlays hiding the field, or nil if field is
3820 ((= start end
) nil
) ;no field to narrow
3821 ((org-table--shrunk-field) nil
) ;already shrunk
3822 ((= 0 width
) ;shrink to one character
3823 (list (org-table--make-shrinking-overlay
3824 start end
"" (if (eq 'hline contents
) "" contents
))))
3825 ((eq contents
'hline
)
3826 (list (org-table--make-shrinking-overlay
3827 start end
(make-string (1+ width
) ?-
) "")))
3828 ((equal contents
"") ;no contents to hide
3830 (let ((w (org-string-width (buffer-substring start end
)))
3831 ;; We really want WIDTH + 2 whitespace, to include blanks
3835 (org-table--make-shrinking-overlay
3836 (1- end
) end
(make-string (- full w
) ?\s
) "")
3837 (org-table--make-shrinking-overlay (- end
(- w full
) 1) end
"" "")))))
3839 ;; If the field is not empty, display exactly WIDTH characters.
3840 ;; It can mean to partly hide the field, or extend it with virtual
3841 ;; blanks. To that effect, we use one or two overlays. The
3842 ;; first, optional, one may add or hide white spaces before the
3843 ;; contents of the field. The other, mandatory, one cuts the
3844 ;; field or displays white spaces at the end of the field. It
3845 ;; also always displays `org-table-shrunk-column-indicator'.
3846 (let* ((lead (org-with-point-at start
(skip-chars-forward " ")))
3847 (trail (org-with-point-at end
(abs (skip-chars-backward " "))))
3848 (contents-width (org-string-width
3849 (buffer-substring (+ start lead
) (- end trail
)))))
3851 ;; Contents are too large to fit in WIDTH character. Limit, if
3852 ;; possible, blanks at the beginning of the field to a single
3853 ;; white space, and cut the field at an appropriate location.
3854 ((<= width contents-width
)
3857 (org-table--make-shrinking-overlay
3858 start
(+ start lead
) "" contents t
)))
3860 (org-table--make-shrinking-overlay
3861 ;; Find cut location so that WIDTH characters are
3862 ;; visible using dichotomy.
3863 (let* ((begin (+ start lead
))
3866 ;; Compensate the absence of leading space,
3867 ;; thus preserving alignment.
3868 (width (if (= lead
0) (1+ width
) width
)))
3870 (while (> (- upper lower
) 1)
3871 (let ((mean (+ (ash lower -
1)
3873 (logand lower upper
1))))
3874 (pcase (org-string-width (buffer-substring begin mean
))
3875 ((pred (= width
)) (throw :exit mean
))
3876 ((pred (< width
)) (setq upper mean
))
3877 (_ (setq lower mean
)))))
3880 (if pre
(list pre post
) (list post
))))
3881 ;; Contents fit it WIDTH characters. First compute number of
3882 ;; white spaces needed on each side of contents, then expand or
3883 ;; compact blanks on each side of the field in order to
3884 ;; preserve width and obey to alignment constraints.
3886 (let* ((required (- width contents-width
))
3889 ;; Compensate the absence of leading space, thus
3890 ;; preserving alignment.
3891 ((guard (= lead
0)) -
1)
3894 ("c" (/ required
2))))
3895 (after (- required before
))
3898 ((or (guard (= lead
0)) (pred (= before
))) nil
)
3900 (org-table--make-shrinking-overlay
3901 start
(+ start
(- lead before
)) "" contents t
))
3903 (org-table--make-shrinking-overlay
3905 (make-string (- before
(1- lead
)) ?\s
)
3910 (org-table--make-shrinking-overlay (1- end
) end
"" contents
))
3912 (org-table--make-shrinking-overlay
3913 (+ after
(- end trail
)) end
"" contents
))
3915 (org-table--make-shrinking-overlay
3917 (make-string (- after
(1- trail
)) ?\s
)
3919 (if pre
(list pre post
) (list post
)))))))))
3921 (defun org-table--read-column-selection (select max
)
3922 "Read column selection select as a list of numbers.
3924 SELECT is a string containing column ranges, separated by white
3925 space characters, see `org-table-hide-column' for details. MAX
3926 is the maximum column number.
3928 Return value is a sorted list of numbers. Ignore any number
3929 outside of the [1;MAX] range."
3936 ((member s
'("-" "1-")) (throw :all
(number-sequence 1 max
)))
3937 ((string-match-p "\\`[0-9]+\\'" s
)
3938 (let ((n (string-to-number s
)))
3939 (and (> n
0) (<= n max
) (list n
))))
3940 ((string-match "\\`\\([0-9]+\\)?-\\([0-9]+\\)?\\'" s
)
3941 (let ((n (match-string 1 s
))
3942 (m (match-string 2 s
)))
3943 (number-sequence (if n
(max 1 (string-to-number n
))
3945 (if m
(min max
(string-to-number m
))
3947 (t nil
))) ;invalid specification
3948 (split-string select
)))
3951 (defun org-table--shrink-columns (columns beg end
)
3952 "Shrink COLUMNS in a table.
3953 COLUMNS is a sorted list of column numbers. BEG and END are,
3954 respectively, the beginning position and the end position of the
3956 (org-with-wide-buffer
3957 (org-font-lock-ensure beg end
)
3963 (while (< (point) end
)
3965 (let* ((hline?
(org-at-table-hline-p))
3966 (separator (if hline?
"+" "|")))
3968 (search-forward "|")
3969 (or (= c
1) ;already there
3970 (search-forward separator
(line-end-position) t
(1- c
))
3971 (throw :continue nil
)) ;skip invalid columns
3972 ;; Extract boundaries and contents from current field.
3973 ;; Also set the column's width if we encounter a width
3974 ;; cookie for the first time.
3975 (let* ((start (point))
3977 (skip-chars-forward (concat "^|" separator
)
3978 (line-end-position))
3980 (contents (if hline?
'hline
3981 (org-trim (buffer-substring start end
)))))
3982 (push (list start end contents
) fields
)
3983 (when (and (not hline?
)
3984 (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)>\\'"
3986 (unless align
(setq align
(match-string 1 contents
)))
3988 (setq width
(string-to-number (match-string 2 contents
))))))))
3990 ;; Link overlays for current field to the other overlays in the
3992 (let ((chain (list 'siblings
)))
3993 (dolist (field fields
)
3994 (dolist (new (apply #'org-table--shrink-field
3995 (or width
0) (or align
"l") field
))
3996 (push new
(cdr chain
))
3997 (overlay-put new
'org-table-column-overlays chain
))))))))
4000 (defun org-table-toggle-column-width (&optional arg
)
4001 "Shrink or expand current column in an Org table.
4003 If a width cookie specifies a width W for the column, the first
4004 W visible characters are displayed. Otherwise, the column is
4005 shrunk to a single character.
4007 When point is before the first column or after the last one, ask
4008 for the columns to shrink or expand, as a list of ranges.
4009 A column range can be one of the following patterns:
4012 N-M every column between N and M (both inclusive)
4013 N- every column between N (inclusive) and the last column
4014 -M every column between the first one and M (inclusive)
4017 When optional argument ARG is a string, use it as white space
4018 separated list of column ranges.
4020 When called with `\\[universal-argument]' prefix, call \
4021 `org-table-shrink', i.e.,
4022 shrink columns with a width cookie and expand the others.
4024 When called with `\\[universal-argument] \\[universal-argument]' \
4025 prefix, expand all columns."
4027 (unless (org-at-table-p) (user-error "Not in a table"))
4028 (let* ((begin (org-table-begin))
4029 (end (org-table-end))
4030 ;; Compute an upper bound for the number of columns.
4031 ;; Nonexistent columns are ignored anyway.
4032 (max-columns (/ (- (line-end-position) (line-beginning-position)) 2))
4033 (shrunk (org-table--list-shrunk-columns))
4038 (skip-chars-backward "^|" (line-beginning-position))
4039 (or (bolp) (looking-at-p "[ \t]*$")))
4040 ;; Point is either before first column or past last
4041 ;; one. Ask for columns to operate on.
4042 (org-table--read-column-selection
4043 (read-string "Column ranges (e.g. 2-4 6-): ")
4045 (list (org-table-current-column))))
4046 ((pred stringp
) (org-table--read-column-selection arg max-columns
))
4047 ((or `(4) `(16)) nil
)
4048 (_ (user-error "Invalid argument: %S" arg
)))))
4050 (`(4) (org-table-shrink begin end
))
4051 (`(16) (org-table-expand begin end
))
4053 (org-table-expand begin end
)
4054 (org-table--shrink-columns
4055 (cl-set-exclusive-or columns shrunk
) begin end
)))))
4058 (defun org-table-shrink (&optional begin end
)
4059 "Shrink all columns with a width cookie in the table at point.
4061 Columns without a width cookie are expanded.
4063 Optional arguments BEGIN and END, when non-nil, specify the
4064 beginning and end position of the current table."
4066 (unless (or begin
(org-at-table-p)) (user-error "Not at a table"))
4067 (org-with-wide-buffer
4068 (let ((begin (or begin
(org-table-begin)))
4069 (end (or end
(org-table-end)))
4070 (regexp "|[ \t]*<[lrc]?[0-9]+>[ \t]*\\(|\\|$\\)")
4073 (while (re-search-forward regexp end t
)
4074 (goto-char (match-beginning 1))
4075 (cl-pushnew (org-table-current-column) columns
))
4076 (org-table-expand begin end
)
4077 ;; Make sure invisible characters in the table are at the right
4078 ;; place since column widths take them into account.
4079 (org-font-lock-ensure begin end
)
4080 (org-table--shrink-columns (sort columns
#'<) begin end
))))
4083 (defun org-table-expand (&optional begin end
)
4084 "Expand all columns in the table at point.
4085 Optional arguments BEGIN and END, when non-nil, specify the
4086 beginning and end position of the current table."
4088 (unless (or begin
(org-at-table-p)) (user-error "Not at a table"))
4089 (org-with-wide-buffer
4090 (let ((begin (or begin
(org-table-begin)))
4091 (end (or end
(org-table-end))))
4092 (remove-overlays begin end
'org-overlay-type
'table-column-hide
))))
4098 (defun org-table-map-tables (f &optional quietly
)
4099 "Apply function F to the start of all tables in the buffer."
4100 (org-with-point-at 1
4101 (while (re-search-forward org-table-line-regexp nil t
)
4102 (let ((table (org-element-lineage (org-element-at-point) '(table) t
)))
4105 (message "Mapping tables: %d%%"
4106 (floor (* 100.0 (point)) (buffer-size))))
4107 (goto-char (org-element-property :begin table
))
4108 (let ((end (copy-marker (org-element-property :end table
))))
4110 (progn (funcall f
) (goto-char end
))
4111 (set-marker end nil
)))))))
4112 (unless quietly
(message "Mapping tables: done")))
4115 (defun org-table-export (&optional file format
)
4116 "Export table to a file, with configurable format.
4117 Such a file can be imported into usual spreadsheet programs.
4119 FILE can be the output file name. If not given, it will be taken
4120 from a TABLE_EXPORT_FILE property in the current entry or higher
4121 up in the hierarchy, or the user will be prompted for a file
4122 name. FORMAT can be an export format, of the same kind as it
4123 used when `-mode' sends a table in a different format.
4125 The command suggests a format depending on TABLE_EXPORT_FORMAT,
4126 whether it is set locally or up in the hierarchy, then on the
4127 extension of the given file name, and finally on the variable
4128 `org-table-export-default-format'."
4130 (unless (org-at-table-p) (user-error "No table at point"))
4131 (org-table-align) ; Make sure we have everything we need.
4132 (let ((file (or file
(org-entry-get (point) "TABLE_EXPORT_FILE" t
))))
4134 (setq file
(read-file-name "Export table to: "))
4135 (unless (or (not (file-exists-p file
))
4136 (y-or-n-p (format "Overwrite file %s? " file
)))
4137 (user-error "File not written")))
4138 (when (file-directory-p file
)
4139 (user-error "This is a directory path, not a file"))
4140 (when (and (buffer-file-name (buffer-base-buffer))
4142 (file-truename file
)
4143 (file-truename (buffer-file-name (buffer-base-buffer)))))
4144 (user-error "Please specify a file name that is different from current"))
4145 (let ((fileext (concat (file-name-extension file
) "$"))
4146 (format (or format
(org-entry-get (point) "TABLE_EXPORT_FORMAT" t
))))
4148 (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
4149 "orgtbl-to-html" "orgtbl-to-generic"
4150 "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
4151 "orgtbl-to-unicode"))
4153 (replace-regexp-in-string
4155 (replace-regexp-in-string
4160 (and (string-match-p fileext f
) f
))
4162 org-table-export-default-format
)
4165 (org-completing-read
4166 "Format: " formats nil nil deffmt-readable
))))
4167 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
4168 (let ((transform (intern (match-string 1 format
)))
4169 (params (and (match-end 2)
4170 (read (concat "(" (match-string 2 format
) ")"))))
4171 (table (org-table-to-lisp
4172 (buffer-substring-no-properties
4173 (org-table-begin) (org-table-end)))))
4174 (unless (fboundp transform
)
4175 (user-error "No such transformation function %s" transform
))
4177 (with-current-buffer (find-file-noselect file
)
4178 (setq buf
(current-buffer))
4181 (insert (funcall transform table params
) "\n")
4184 (message "Export done."))
4185 (user-error "TABLE_EXPORT_FORMAT invalid")))))
4188 (defun org-table--align-field (field width align
)
4189 "Format FIELD according to column WIDTH and alignement ALIGN.
4190 FIELD is a string. WIDTH is a number. ALIGN is either \"c\",
4192 (let* ((spaces (- width
(org-string-width field
)))
4193 (prefix (pcase align
4195 ("r" (make-string spaces ?\s
))
4196 ("c" (make-string (/ spaces
2) ?\s
))))
4197 (suffix (make-string (- spaces
(length prefix
)) ?\s
)))
4198 (concat org-table-separator-space
4202 org-table-separator-space
)))
4204 (defun org-table-align ()
4205 "Align the table at point by aligning all vertical bars."
4207 (let ((beg (org-table-begin))
4208 (end (copy-marker (org-table-end))))
4209 (org-table-save-field
4210 ;; Make sure invisible characters in the table are at the right
4211 ;; place since column widths take them into account.
4212 (org-font-lock-ensure beg end
)
4213 (move-marker org-table-aligned-begin-marker beg
)
4214 (move-marker org-table-aligned-end-marker end
)
4216 (org-table-with-shrunk-columns
4217 (let* ((indent (progn (looking-at "[ \t]*") (match-string 0)))
4218 ;; Table's rows as lists of fields. Rules are replaced
4219 ;; by nil. Trailing spaces are removed.
4222 (and (not (string-match-p org-table-hline-regexp l
))
4223 (org-split-string l
"[ \t]*|[ \t]*")))
4224 (split-string (buffer-substring beg end
) "\n" t
)))
4225 ;; Compute number of columns. If the table contains no
4226 ;; field, create a default table and bail out.
4228 (if fields
(apply #'max
(mapcar #'length fields
))
4229 (kill-region beg end
)
4230 (org-table-create org-table-default-size
)
4231 (user-error "Empty table - created default table")))
4234 ;; Compute alignment and width for each column.
4235 (dotimes (i columns-number
)
4236 (let* ((max-width 1)
4240 (dolist (row fields
)
4241 (let ((cell (or (nth i row
) "")))
4242 (setq max-width
(max max-width
(org-string-width cell
)))
4243 (cond (fixed-align? nil
)
4244 ((equal cell
"") nil
)
4245 ((string-match "\\`<\\([lrc]\\)[0-9]*>\\'" cell
)
4246 (setq fixed-align?
(match-string 1 cell
)))
4249 (when (string-match-p org-table-number-regexp cell
)
4250 (cl-incf numbers
))))))
4251 (push max-width widths
)
4254 ((>= numbers
(* org-table-number-fraction non-empty
)) "r")
4257 (setq widths
(nreverse widths
))
4258 (setq alignments
(nreverse alignments
))
4259 ;; Store alignment of this table, for later editing of single
4261 (setq org-table-last-alignment alignments
)
4262 (setq org-table-last-column-widths widths
)
4263 ;; Build new table rows. Only replace rows that actually
4265 (dolist (row fields
)
4266 (let ((previous (buffer-substring (point) (line-end-position)))
4270 (if (null row
) ;horizontal rule
4271 (mapconcat (lambda (w) (make-string (+ 2 w
) ?-
))
4274 (let ((cells ;add missing fields
4276 (make-list (- columns-number
4279 (mapconcat #'identity
4280 (cl-mapcar #'org-table--align-field
4285 (if (equal new previous
)
4288 (delete-region (point) (line-beginning-position 2)))))
4289 (set-marker end nil
)
4290 (when org-table-overlay-coordinates
(org-table-overlay-coordinates))
4291 (setq org-table-may-need-update nil
))))))
4294 (defun org-table-justify-field-maybe (&optional new
)
4295 "Justify the current field, text to left, number to right.
4296 Optional argument NEW may specify text to replace the current field content."
4298 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
4299 ((org-at-table-hline-p))
4301 (or (not (eq (marker-buffer org-table-aligned-begin-marker
)
4303 (< (point) org-table-aligned-begin-marker
)
4304 (>= (point) org-table-aligned-end-marker
)))
4305 ;; This is not the same table, force a full re-align.
4306 (setq org-table-may-need-update t
))
4308 ;; Realign the current field, based on previous full realign.
4310 (col (org-table-current-column)))
4312 (skip-chars-backward "^|")
4313 (if (not (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)"))
4314 (setq org-table-may-need-update t
)
4315 (let* ((align (nth (1- col
) org-table-last-alignment
))
4316 (width (nth (1- col
) org-table-last-column-widths
))
4317 (cell (match-string 0))
4318 (field (match-string 1))
4319 (properly-closed?
(/= (match-beginning 2) (match-end 2)))
4322 (cond (org-table-may-need-update
4323 (format " %s |" (or new field
)))
4324 ((not properly-closed?
)
4325 (setq org-table-may-need-update t
)
4326 (format " %s |" (or new field
)))
4328 (concat (org-table--align-field field width align
)
4330 ((<= (org-string-width new
) width
)
4331 (concat (org-table--align-field new width align
)
4334 (setq org-table-may-need-update t
)
4335 (format " %s |" new
))))))
4336 (unless (equal new-cell cell
)
4337 (let (org-table-may-need-update)
4338 (replace-match new-cell t t
)))
4339 (goto-char pos
))))))))
4342 (defun org-table-sort-lines
4343 (&optional with-case sorting-type getkey-func compare-func interactive?
)
4344 "Sort table lines according to the column at point.
4346 The position of point indicates the column to be used for
4347 sorting, and the range of lines is the range between the nearest
4348 horizontal separator lines, or the entire table of no such lines
4349 exist. If point is before the first column, you will be prompted
4350 for the sorting column. If there is an active region, the mark
4351 specifies the first line and the sorting column, while point
4352 should be in the last line to be included into the sorting.
4354 The command then prompts for the sorting type which can be
4355 alphabetically, numerically, or by time (as given in a time stamp
4356 in the field, or as a HH:MM value). Sorting in reverse order is
4359 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive
4360 if the locale allows for it.
4362 If SORTING-TYPE is specified when this function is called from a Lisp
4363 program, no prompting will take place. SORTING-TYPE must be a character,
4364 any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
4365 sorting should be done in reverse order.
4367 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
4368 a function to be called to extract the key. It must return a value
4369 that is compatible with COMPARE-FUNC, the function used to compare
4372 A non-nil value for INTERACTIVE? is used to signal that this
4373 function is being called interactively."
4374 (interactive (list current-prefix-arg nil nil nil t
))
4375 (when (org-region-active-p) (goto-char (region-beginning)))
4376 ;; Point must be either within a field or before a data line.
4378 (skip-chars-backward " \t")
4379 (when (bolp) (search-forward "|" (line-end-position) t
))
4380 (org-table-check-inside-data-field))
4381 ;; Set appropriate case sensitivity and column used for sorting.
4382 (let ((column (let ((c (org-table-current-column)))
4385 (read-number "Use column N for sorting: "))
4389 (read-char-exclusive "Sort Table: [a]lphabetic, [n]umeric, \
4390 \[t]ime, [f]unc. A/N/T/F means reversed: ")))
4391 (start (org-table-begin))
4392 (end (org-table-end)))
4394 ;; Narrow buffer to appropriate sorting area.
4395 (if (org-region-active-p)
4396 (progn (goto-char (region-beginning))
4399 (save-excursion (goto-char (region-end))
4400 (line-beginning-position 2))))
4403 (if (re-search-backward org-table-hline-regexp start t
)
4404 (line-beginning-position 2)
4406 (if (save-excursion (re-search-forward org-table-hline-regexp end t
))
4409 ;; Determine arguments for `sort-subr'. Also record original
4410 ;; position. `org-table-save-field' cannot help here since
4411 ;; sorting is too much destructive.
4413 (cons (count-lines (point-min) (line-beginning-position))
4415 (extract-key-from-field
4416 ;; Function to be called on the contents of the field
4417 ;; used for sorting in the current row.
4418 (cl-case sorting-type
4419 ((?n ?N
) #'string-to-number
)
4420 ((?a ?A
) #'org-sort-remove-invisible
)
4423 (cond ((string-match org-ts-regexp-both f
)
4425 (org-time-string-to-time (match-string 0 f
))))
4426 ((org-duration-p f
) (org-duration-to-minutes f
))
4427 ((string-match "\\<[0-9]+:[0-9]\\{2\\}\\>" f
)
4428 (org-duration-to-minutes (match-string 0 f
)))
4433 (org-read-function "Function for extracting keys: "))
4434 (error "Missing key extractor to sort rows")))
4435 (t (user-error "Invalid sorting type `%c'" sorting-type
))))
4437 (cl-case sorting-type
4439 ((?a ?A
) (if with-case
#'org-string-collate-lessp
4440 (lambda (s1 s2
) (org-string-collate-lessp s1 s2 nil t
))))
4445 "Function for comparing keys (empty for default \
4446 `sort-subr' predicate): "
4448 (shrunk-columns (remq column
(org-table--list-shrunk-columns))))
4449 (goto-char (point-min))
4450 (sort-subr (memq sorting-type
'(?A ?N ?T ?F
))
4453 (while (and (not (eobp))
4454 (not (looking-at org-table-dataline-regexp
)))
4458 (funcall extract-key-from-field
4459 (org-trim (org-table-get-field column
))))
4462 ;; Hide all columns but the one being sorted.
4463 (org-table--shrink-columns shrunk-columns start end
)
4464 ;; Move back to initial field.
4465 (forward-line (car coordinates
))
4466 (move-to-column (cdr coordinates
))))))
4468 (defun org-table-transpose-table-at-point ()
4469 "Transpose Org table at point and eliminate hlines.
4477 will be transposed as
4484 Note that horizontal lines disappear."
4486 (let* ((table (delete 'hline
(org-table-to-lisp)))
4487 (dline_old (org-table-current-line))
4488 (col_old (org-table-current-column))
4489 (contents (mapcar (lambda (_)
4495 (setq tp
(cdr tp
))))
4498 (goto-char (org-table-begin))
4499 (re-search-forward "|")
4501 (delete-region (point) (org-table-end))
4504 (concat "| " (mapconcat 'identity x
" | " ) " |\n" ))
4506 (org-table-goto-line col_old
)
4507 (org-table-goto-column dline_old
))
4511 (defun org-table-wrap-region (arg)
4512 "Wrap several fields in a column like a paragraph.
4513 This is useful if you'd like to spread the contents of a field over several
4514 lines, in order to keep the table compact.
4516 If there is an active region, and both point and mark are in the same column,
4517 the text in the column is wrapped to minimum width for the given number of
4518 lines. Generally, this makes the table more compact. A prefix ARG may be
4519 used to change the number of desired lines. For example, \
4520 `C-2 \\[org-table-wrap-region]'
4521 formats the selected text to two lines. If the region was longer than two
4522 lines, the remaining lines remain empty. A negative prefix argument reduces
4523 the current number of lines by that amount. The wrapped text is pasted back
4524 into the table. If you formatted it to more lines than it was before, fields
4525 further down in the table get overwritten - so you might need to make space in
4528 If there is no region, the current field is split at the cursor position and
4529 the text fragment to the right of the cursor is prepended to the field one
4532 If there is no region, but you specify a prefix ARG, the current field gets
4533 blank, and the content is appended to the field above."
4535 (org-table-check-inside-data-field)
4536 (if (org-region-active-p)
4537 ;; There is a region: fill as a paragraph.
4538 (let ((start (region-beginning)))
4539 (org-table-cut-region (region-beginning) (region-end))
4540 (when (> (length (car org-table-clip
)) 1)
4541 (user-error "Region must be limited to single column"))
4542 (let ((nlines (cond ((not arg
) (length org-table-clip
))
4543 ((< arg
1) (+ (length org-table-clip
) arg
))
4545 (setq org-table-clip
4547 (org-wrap (mapconcat #'car org-table-clip
" ")
4551 (org-table-paste-rectangle))
4552 ;; No region, split the current field at point.
4553 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
4554 (skip-chars-forward "^\r\n|"))
4556 (arg ; Combine with field above.
4557 (let ((s (org-table-blank-field))
4558 (col (org-table-current-column)))
4560 (while (org-at-table-hline-p) (forward-line -
1))
4561 (org-table-goto-column col
)
4562 (skip-chars-forward "^|")
4563 (skip-chars-backward " ")
4564 (insert " " (org-trim s
))
4566 ((looking-at "\\([^|]+\\)+|") ; Split field.
4567 (let ((s (match-string 1)))
4568 (replace-match " |")
4569 (goto-char (match-beginning 0))
4570 (org-table-next-row)
4571 (insert (org-trim s
) " ")
4573 (t (org-table-next-row)))))
4575 (defun org-table--number-for-summing (s)
4577 (if (string-match "^ *|? *" s
)
4578 (setq s
(replace-match "" nil nil s
)))
4579 (if (string-match " *|? *$" s
)
4580 (setq s
(replace-match "" nil nil s
)))
4581 (setq n
(string-to-number s
))
4583 ((and (string-match "0" s
)
4584 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
4585 ((string-match "\\`[ \t]+\\'" s
) nil
)
4586 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
4587 (let ((h (string-to-number (or (match-string 1 s
) "0")))
4588 (m (string-to-number (or (match-string 2 s
) "0")))
4589 (s (string-to-number (or (match-string 4 s
) "0"))))
4590 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
4591 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
4596 (defun org-table-sum (&optional beg end nlast
)
4597 "Sum numbers in region of current table column.
4598 The result will be displayed in the echo area, and will be available
4599 as kill to be inserted with \\[yank].
4601 If there is an active region, it is interpreted as a rectangle and all
4602 numbers in that rectangle will be summed. If there is no active
4603 region and point is located in a table column, sum all numbers in that
4606 If at least one number looks like a time HH:MM or HH:MM:SS, all other
4607 numbers are assumed to be times as well (in decimal hours) and the
4608 numbers are added as such.
4610 If NLAST is a number, only the NLAST fields will actually be summed."
4613 (let (col (org-timecnt 0) diff h m s org-table-clip
)
4615 ((and beg end
)) ; beg and end given explicitly
4616 ((org-region-active-p)
4617 (setq beg
(region-beginning) end
(region-end)))
4619 (setq col
(org-table-current-column))
4620 (goto-char (org-table-begin))
4621 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
4622 (user-error "No table data"))
4623 (org-table-goto-column col
)
4625 (goto-char (org-table-end))
4626 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
4627 (user-error "No table data"))
4628 (org-table-goto-column col
)
4629 (setq end
(point))))
4630 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
4631 (items1 (cond ((not nlast
) items
)
4632 ((>= nlast
(length items
)) items
)
4633 (t (setq items
(reverse items
))
4634 (setcdr (nthcdr (1- nlast
) items
) nil
)
4636 (numbers (delq nil
(mapcar #'org-table--number-for-summing
4638 (res (apply '+ numbers
))
4639 (sres (if (= org-timecnt
0)
4640 (number-to-string res
)
4641 (setq diff
(* 3600 res
)
4642 h
(floor diff
3600) diff
(mod diff
3600)
4643 m
(floor diff
60) diff
(mod diff
60)
4645 (format "%.0f:%02.0f:%02.0f" h m s
))))
4647 (when (called-interactively-p 'interactive
)
4648 (message (substitute-command-keys
4649 (format "Sum of %d items: %-20s \
4650 \(\\[yank] will insert result into buffer)"
4656 (defun org-table-analyze ()
4657 "Analyze table at point and store results.
4659 This function sets up the following dynamically scoped variables:
4661 `org-table-column-name-regexp',
4662 `org-table-column-names',
4663 `org-table-current-begin-pos',
4664 `org-table-current-line-types',
4665 `org-table-current-ncol',
4668 `org-table-local-parameters',
4669 `org-table-named-field-locations'."
4670 (let ((beg (org-table-begin))
4671 (end (org-table-end)))
4674 ;; Extract column names.
4675 (setq org-table-column-names nil
)
4676 (when (save-excursion
4677 (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
))
4679 (dolist (name (org-split-string (match-string 1) " *| *"))
4681 (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name
)
4682 (push (cons name
(int-to-string c
)) org-table-column-names
)))))
4683 (setq org-table-column-names
(nreverse org-table-column-names
))
4684 (setq org-table-column-name-regexp
4685 (format "\\$\\(%s\\)\\>"
4686 (regexp-opt (mapcar #'car org-table-column-names
) t
)))
4687 ;; Extract local parameters.
4688 (setq org-table-local-parameters nil
)
4690 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
4691 (dolist (field (org-split-string (match-string 1) " *| *"))
4693 "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
4694 (push (cons (match-string 1 field
) (match-string 2 field
))
4695 org-table-local-parameters
)))))
4696 ;; Update named fields locations. We minimize `count-lines'
4697 ;; processing by storing last known number of lines in LAST.
4698 (setq org-table-named-field-locations nil
)
4700 (let ((last (cons (point) 0)))
4701 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
4702 (let ((c (match-string 1))
4703 (fields (org-split-string (match-string 2) " *| *")))
4705 (forward-line (if (equal c
"_") 1 -
1))
4707 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
4708 (org-split-string (match-string 1) " *| *")))
4709 (line (cl-incf (cdr last
) (count-lines (car last
) (point))))
4711 (setcar last
(point)) ; Update last known position.
4712 (while (and fields fields1
)
4713 (let ((field (pop fields
))
4716 (when (and (stringp field
)
4718 (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
4720 (push (cons field v
) org-table-local-parameters
)
4721 (push (list field line col
)
4722 org-table-named-field-locations
))))))))))
4723 ;; Re-use existing markers when possible.
4724 (if (markerp org-table-current-begin-pos
)
4725 (move-marker org-table-current-begin-pos
(point))
4726 (setq org-table-current-begin-pos
(point-marker)))
4727 ;; Analyze the line types.
4728 (let ((l 0) hlines dlines types
)
4729 (while (looking-at "[ \t]*|\\(-\\)?")
4730 (push (if (match-end 1) 'hline
'dline
) types
)
4731 (if (match-end 1) (push l hlines
) (push l dlines
))
4734 (push 'hline types
) ; Add an imaginary extra hline to the end.
4735 (setq org-table-current-line-types
(apply #'vector
(nreverse types
)))
4736 (setq org-table-dlines
(apply #'vector
(cons nil
(nreverse dlines
))))
4737 (setq org-table-hlines
(apply #'vector
(cons nil
(nreverse hlines
)))))
4738 ;; Get the number of columns from the first data line in table.
4740 (forward-line (aref org-table-dlines
1))
4743 (buffer-substring (line-beginning-position) (line-end-position))
4745 (nfields (length fields
))
4747 (setq org-table-current-ncol nfields
)
4749 (aref org-table-dlines
(1- (length org-table-dlines
)))))
4750 (dotimes (i nfields
)
4751 (let ((column (1+ i
)))
4752 (push (list (format "LR%d" column
) last-dline column
) al
)
4753 (push (cons (format "LR%d" column
) (nth i fields
)) al2
))))
4754 (setq org-table-named-field-locations
4755 (append org-table-named-field-locations al
))
4756 (setq org-table-local-parameters
4757 (append org-table-local-parameters al2
))))))
4759 (defun org-table--force-dataline ()
4760 "Move point to the closest data line in a table.
4761 Raise an error if the table contains no data line. Preserve
4762 column when moving point."
4763 (unless (org-match-line org-table-dataline-regexp
)
4764 (let* ((re org-table-dataline-regexp
)
4765 (column (current-column))
4766 (p1 (save-excursion (re-search-forward re
(org-table-end) t
)))
4767 (p2 (save-excursion (re-search-backward re
(org-table-begin) t
))))
4769 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
4772 ((or p1 p2
) (goto-char (or p1 p2
)))
4773 (t (user-error "No table data line around here")))
4774 (org-move-to-column column
))))
4776 (defun org-table-show-reference (&optional local
)
4777 "Show the location/value of the $ expression at point.
4778 When LOCAL is non-nil, show references for the table at point."
4780 (org-table-remove-rectangle-highlight)
4781 (when local
(org-table-analyze))
4783 (let ((pos (if local
(point) org-pos
))
4785 (org-inhibit-highlight-removal t
)
4786 (win (selected-window))
4787 (org-show-positions nil
)
4788 var name e what match dest
)
4790 ((org-in-regexp "^@[0-9]+[ \t=]")
4791 (setq match
(concat (substring (match-string 0) 0 -
1)
4793 (substring (match-string 0) 0 -
1)
4796 ((or (org-in-regexp org-table-range-regexp2
)
4797 (org-in-regexp org-table-translate-regexp
)
4798 (org-in-regexp org-table-range-regexp
))
4801 (org-table-convert-refs-to-rc (match-string 0))))
4803 ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
4804 ((org-in-regexp "\\$[0-9]+") 'column
)
4806 (t (user-error "No reference at point")))
4807 match
(and what
(or match
(match-string 0))))
4808 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
4809 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
4810 'secondary-selection
))
4811 (add-hook 'before-change-functions
4812 #'org-table-remove-rectangle-highlight
)
4813 (when (eq what
'name
) (setq var
(substring match
1)))
4814 (when (eq what
'range
)
4815 (unless (eq (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
4816 (setq match
(org-table-formula-substitute-names match
)))
4820 (re-search-backward "^\\S-" nil t
)
4822 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
4823 \\([0-9]+\\|&\\)\\) *=")
4826 (org-table-convert-refs-to-rc (match-string 1))))
4827 (org-table-add-rectangle-overlay
4828 (match-beginning 1) (match-end 1) face2
))))
4829 (if (and (markerp pos
) (marker-buffer pos
))
4830 (if (get-buffer-window (marker-buffer pos
))
4831 (select-window (get-buffer-window (marker-buffer pos
)))
4832 (org-switch-to-buffer-other-window (get-buffer-window
4833 (marker-buffer pos
)))))
4835 (org-table--force-dataline)
4837 (if local org-table-current-begin-pos
(org-table-begin))))
4839 (setq name
(substring dest
1))
4841 ((string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
4842 (org-table-goto-field dest
))
4843 ((string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
4845 (org-table-goto-field dest
))
4846 (t (org-table-goto-column (string-to-number name
))))
4847 (move-marker pos
(point))
4848 (org-table-highlight-rectangle nil nil face2
))
4850 ((equal dest match
))
4853 (ignore-errors (org-table-get-range match table-start nil
'highlight
)))
4854 ((setq e
(assoc var org-table-named-field-locations
))
4855 (org-table-goto-field var
)
4856 (org-table-highlight-rectangle)
4857 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
4858 ((setq e
(assoc var org-table-column-names
))
4859 (org-table-goto-column (string-to-number (cdr e
)))
4860 (org-table-highlight-rectangle)
4861 (goto-char table-start
)
4862 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
4865 (goto-char (match-beginning 1))
4866 (org-table-highlight-rectangle)
4867 (message "Named column (column %s)" (cdr e
)))
4868 (user-error "Column name not found")))
4871 (org-table-goto-column (string-to-number (substring match
1)))
4872 (org-table-highlight-rectangle)
4873 (message "Column %s" (substring match
1)))
4874 ((setq e
(assoc var org-table-local-parameters
))
4875 (goto-char table-start
)
4876 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
4878 (goto-char (match-beginning 1))
4879 (org-table-highlight-rectangle)
4880 (message "Local parameter."))
4881 (user-error "Parameter not found")))
4882 ((not var
) (user-error "No reference at point"))
4883 ((setq e
(assoc var org-table-formula-constants-local
))
4884 (message "Local Constant: $%s=%s in #+CONSTANTS line."
4886 ((setq e
(assoc var org-table-formula-constants
))
4887 (message "Constant: $%s=%s in `org-table-formula-constants'."
4889 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
4890 (message "Constant: $%s=%s, from `constants.el'%s."
4891 var e
(format " (%s units)" constants-unit-system
)))
4892 (t (user-error "Undefined name $%s" var
)))
4894 (when (and org-show-positions
4895 (not (memq this-command
'(org-table-fedit-scroll
4896 org-table-fedit-scroll-down
))))
4897 (push pos org-show-positions
)
4898 (push table-start org-show-positions
)
4899 (let ((min (apply 'min org-show-positions
))
4900 (max (apply 'max org-show-positions
)))
4901 (set-window-start (selected-window) min
)
4903 (or (pos-visible-in-window-p max
)
4904 (set-window-start (selected-window) max
)))))
4905 (select-window win
))))
4908 ;;; The Orgtbl minor mode
4910 ;; Define a minor mode which can be used in other modes in order to
4911 ;; integrate the Org table editor.
4913 ;; This is really a hack, because the Org table editor uses several
4914 ;; keys which normally belong to the major mode, for example the TAB
4915 ;; and RET keys. Here is how it works: The minor mode defines all the
4916 ;; keys necessary to operate the table editor, but wraps the commands
4917 ;; into a function which tests if the cursor is currently inside
4918 ;; a table. If that is the case, the table editor command is
4919 ;; executed. However, when any of those keys is used outside a table,
4920 ;; the function uses `key-binding' to look up if the key has an
4921 ;; associated command in another currently active keymap (minor modes,
4922 ;; major mode, global), and executes that command. There might be
4923 ;; problems if any of the keys used by the table editor is otherwise
4924 ;; used as a prefix key.
4926 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
4927 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
4928 ;; addresses this by checking explicitly for both bindings.
4930 ;; The optimized version (see variable `orgtbl-optimized') takes over
4931 ;; all keys which are bound to `self-insert-command' in the *global map*.
4932 ;; Some modes bind other commands to simple characters, for example
4933 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
4934 ;; active, this binding is ignored inside tables and replaced with a
4935 ;; modified self-insert.
4937 (defvar orgtbl-mode-map
(make-keymap)
4938 "Keymap for `orgtbl-mode'.")
4940 (defvar org-old-auto-fill-inhibit-regexp nil
4941 "Local variable used by `orgtbl-mode'.")
4943 (defconst orgtbl-line-start-regexp
4944 "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
4945 "Matches a line belonging to an orgtbl.")
4947 (defconst orgtbl-extra-font-lock-keywords
4948 (list (list (concat "^" orgtbl-line-start-regexp
".*")
4949 0 (quote 'org-table
) 'prepend
))
4950 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
4953 (defun turn-on-orgtbl ()
4954 "Unconditionally turn on `orgtbl-mode'."
4955 (require 'org-table
)
4958 ;; Install it as a minor mode.
4959 (put 'orgtbl-mode
:included t
)
4960 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
4962 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map
"OrgTbl menu"
4964 ["Create or convert" org-table-create-or-convert-from-region
4965 :active
(not (org-at-table-p)) :keys
"C-c |" ]
4967 ["Align" org-ctrl-c-ctrl-c
:active
(org-at-table-p) :keys
"C-c C-c"]
4968 ["Next Field" org-cycle
:active
(org-at-table-p) :keys
"TAB"]
4969 ["Previous Field" org-shifttab
:active
(org-at-table-p) :keys
"S-TAB"]
4970 ["Next Row" org-return
:active
(org-at-table-p) :keys
"RET"]
4972 ["Blank Field" org-table-blank-field
:active
(org-at-table-p) :keys
"C-c SPC"]
4973 ["Edit Field" org-table-edit-field
:active
(org-at-table-p) :keys
"C-c ` "]
4974 ["Copy Field from Above"
4975 org-table-copy-down
:active
(org-at-table-p) :keys
"S-RET"]
4978 ["Move Column Left" org-metaleft
:active
(org-at-table-p) :keys
"M-<left>"]
4979 ["Move Column Right" org-metaright
:active
(org-at-table-p) :keys
"M-<right>"]
4980 ["Delete Column" org-shiftmetaleft
:active
(org-at-table-p) :keys
"M-S-<left>"]
4981 ["Insert Column" org-shiftmetaright
:active
(org-at-table-p) :keys
"M-S-<right>"])
4983 ["Move Row Up" org-metaup
:active
(org-at-table-p) :keys
"M-<up>"]
4984 ["Move Row Down" org-metadown
:active
(org-at-table-p) :keys
"M-<down>"]
4985 ["Delete Row" org-shiftmetaup
:active
(org-at-table-p) :keys
"M-S-<up>"]
4986 ["Insert Row" org-shiftmetadown
:active
(org-at-table-p) :keys
"M-S-<down>"]
4987 ["Sort lines in region" org-table-sort-lines
:active
(org-at-table-p) :keys
"C-c ^"]
4989 ["Insert Hline" org-table-insert-hline
:active
(org-at-table-p) :keys
"C-c -"])
4991 ["Copy Rectangle" org-copy-special
:active
(org-at-table-p)]
4992 ["Cut Rectangle" org-cut-special
:active
(org-at-table-p)]
4993 ["Paste Rectangle" org-paste-special
:active
(org-at-table-p)]
4994 ["Fill Rectangle" org-table-wrap-region
:active
(org-at-table-p)])
4997 ["Insert table template" orgtbl-insert-radio-table
4998 (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates
)]
4999 ["Comment/uncomment table" orgtbl-toggle-comment t
])
5001 ["Set Column Formula" org-table-eval-formula
:active
(org-at-table-p) :keys
"C-c ="]
5002 ["Set Field Formula" (org-table-eval-formula '(4)) :active
(org-at-table-p) :keys
"C-u C-c ="]
5003 ["Edit Formulas" org-table-edit-formulas
:active
(org-at-table-p) :keys
"C-c '"]
5004 ["Recalculate line" org-table-recalculate
:active
(org-at-table-p) :keys
"C-c *"]
5005 ["Recalculate all" (org-table-recalculate '(4)) :active
(org-at-table-p) :keys
"C-u C-c *"]
5006 ["Iterate all" (org-table-recalculate '(16)) :active
(org-at-table-p) :keys
"C-u C-u C-c *"]
5007 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks
:active
(org-at-table-p) :keys
"C-c #"]
5008 ["Sum Column/Rectangle" org-table-sum
5009 :active
(or (org-at-table-p) (org-region-active-p)) :keys
"C-c +"]
5010 ["Which Column?" org-table-current-column
:active
(org-at-table-p) :keys
"C-c ?"]
5012 org-table-toggle-formula-debugger
:active
(org-at-table-p)
5014 :style toggle
:selected org-table-formula-debug
]
5015 ["Show Col/Row Numbers"
5016 org-table-toggle-coordinate-overlays
:active
(org-at-table-p)
5018 :style toggle
:selected org-table-overlay-coordinates
]
5021 ["Ascii plot" orgtbl-ascii-plot
:active
(org-at-table-p) :keys
"C-c \" a"]
5022 ["Gnuplot" org-plot
/gnuplot
:active
(org-at-table-p) :keys
"C-c \" g"])))
5025 (define-minor-mode orgtbl-mode
5026 "The Org mode table editor as a minor mode for use in other modes."
5027 :lighter
" OrgTbl" :keymap orgtbl-mode-map
5028 (org-load-modules-maybe)
5030 ((derived-mode-p 'org-mode
)
5031 ;; Exit without error, in case some hook functions calls this by
5032 ;; accident in Org mode.
5033 (message "Orgtbl mode is not useful in Org mode, command ignored"))
5035 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
5036 ;; Make sure we are first in minor-mode-map-alist
5037 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
5038 ;; FIXME: maybe it should use emulation-mode-map-alists?
5039 (and c
(setq minor-mode-map-alist
5040 (cons c
(delq c minor-mode-map-alist
)))))
5041 (setq-local org-table-may-need-update t
)
5042 (add-hook 'before-change-functions
'org-before-change-function
5044 (setq-local org-old-auto-fill-inhibit-regexp
5045 auto-fill-inhibit-regexp
)
5046 (setq-local auto-fill-inhibit-regexp
5047 (if auto-fill-inhibit-regexp
5048 (concat orgtbl-line-start-regexp
"\\|"
5049 auto-fill-inhibit-regexp
)
5050 orgtbl-line-start-regexp
))
5051 (when (fboundp 'font-lock-add-keywords
)
5052 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
5053 (org-restart-font-lock))
5054 (easy-menu-add orgtbl-mode-menu
))
5056 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
5057 (remove-hook 'before-change-functions
'org-before-change-function t
)
5058 (when (fboundp 'font-lock-remove-keywords
)
5059 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
5060 (org-restart-font-lock))
5061 (easy-menu-remove orgtbl-mode-menu
)
5062 (force-mode-line-update 'all
))))
5064 (defun orgtbl-make-binding (fun n
&rest keys
)
5065 "Create a function for binding in the table minor mode.
5066 FUN is the command to call inside a table. N is used to create a unique
5067 command name. KEYS are keys that should be checked in for a command
5068 to execute outside of tables."
5071 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
5073 (concat "In tables, run `" (symbol-name fun
) "'.\n"
5074 "Outside of tables, run the binding of `"
5075 (mapconcat #'key-description keys
"' or `")
5080 (list 'call-interactively
(list 'quote fun
))
5081 (list 'let
'(orgtbl-mode)
5082 (list 'call-interactively
5085 (list 'key-binding k
))
5087 '('orgtbl-error
))))))))
5089 (defun orgtbl-error ()
5090 "Error when there is no default binding for a table key."
5092 (user-error "This key has no function outside tables"))
5094 (defun orgtbl-setup ()
5095 "Setup orgtbl keymaps."
5098 '(([(meta shift left
)] org-table-delete-column
)
5099 ([(meta left
)] org-table-move-column-left
)
5100 ([(meta right
)] org-table-move-column-right
)
5101 ([(meta shift right
)] org-table-insert-column
)
5102 ([(meta shift up
)] org-table-kill-row
)
5103 ([(meta shift down
)] org-table-insert-row
)
5104 ([(meta up
)] org-table-move-row-up
)
5105 ([(meta down
)] org-table-move-row-down
)
5106 ("\C-c\C-w" org-table-cut-region
)
5107 ("\C-c\M-w" org-table-copy-region
)
5108 ("\C-c\C-y" org-table-paste-rectangle
)
5109 ("\C-c\C-w" org-table-wrap-region
)
5110 ("\C-c-" org-table-insert-hline
)
5111 ("\C-c}" org-table-toggle-coordinate-overlays
)
5112 ("\C-c{" org-table-toggle-formula-debugger
)
5113 ("\C-m" org-table-next-row
)
5114 ([(shift return
)] org-table-copy-down
)
5115 ("\C-c?" org-table-field-info
)
5116 ("\C-c " org-table-blank-field
)
5117 ("\C-c+" org-table-sum
)
5118 ("\C-c=" org-table-eval-formula
)
5119 ("\C-c'" org-table-edit-formulas
)
5120 ("\C-c`" org-table-edit-field
)
5121 ("\C-c*" org-table-recalculate
)
5122 ("\C-c^" org-table-sort-lines
)
5123 ("\M-a" org-table-beginning-of-field
)
5124 ("\M-e" org-table-end-of-field
)
5125 ([(control ?
#)] org-table-rotate-recalc-marks
)))
5127 (while (setq elt
(pop bindings
))
5128 (setq nfunc
(1+ nfunc
))
5129 (setq key
(org-key (car elt
))
5131 cmd
(orgtbl-make-binding fun nfunc key
))
5132 (org-defkey orgtbl-mode-map key cmd
))
5134 ;; Special treatment needed for TAB, RET and DEL
5135 (org-defkey orgtbl-mode-map
[(return)]
5136 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
5137 (org-defkey orgtbl-mode-map
"\C-m"
5138 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
5139 (org-defkey orgtbl-mode-map
[(tab)]
5140 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
5141 (org-defkey orgtbl-mode-map
"\C-i"
5142 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
5143 (org-defkey orgtbl-mode-map
[(shift tab
)]
5144 (orgtbl-make-binding 'org-table-previous-field
104
5145 [(shift tab
)] [(tab)] "\C-i"))
5146 (org-defkey orgtbl-mode-map
[backspace]
5147 (orgtbl-make-binding 'org-delete-backward-char 109
5148 [backspace] (kbd "DEL")))
5150 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
5151 (orgtbl-make-binding 'org-table-previous-field
107
5152 [S-iso-lefttab
] [backtab] [(shift tab)]
5155 (org-defkey orgtbl-mode-map [backtab]
5156 (orgtbl-make-binding 'org-table-previous-field
108
5157 [backtab] [S-iso-lefttab] [(shift tab)]
5160 (org-defkey orgtbl-mode-map "\M-\C-m"
5161 (orgtbl-make-binding 'org-table-wrap-region 105
5162 "\M-\C-m" [(meta return)]))
5163 (org-defkey orgtbl-mode-map [(meta return)]
5164 (orgtbl-make-binding 'org-table-wrap-region 106
5165 [(meta return)] "\M-\C-m"))
5167 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
5168 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
5170 (when orgtbl-optimized
5171 ;; If the user wants maximum table support, we need to hijack
5172 ;; some standard editing functions
5173 (org-remap orgtbl-mode-map
5174 'self-insert-command 'orgtbl-self-insert-command
5175 'delete-char 'org-delete-char
5176 'delete-backward-char 'org-delete-backward-char)
5177 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
5180 (defun orgtbl-ctrl-c-ctrl-c (arg)
5181 "If the cursor is inside a table, realign the table.
5182 If it is a table to be sent away to a receiver, do it.
5183 With prefix arg, also recompute table."
5185 (let ((case-fold-search t) (pos (point)) action)
5187 (beginning-of-line 1)
5189 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
5190 ((looking-at "[ \t]*|") pos)
5191 ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
5195 (org-table-maybe-eval-formula)
5197 (call-interactively 'org-table-recalculate)
5198 (org-table-maybe-recalculate-line))
5199 (call-interactively 'org-table-align)
5200 (when (orgtbl-send-table 'maybe)
5201 (run-hooks 'orgtbl-after-send-table-hook)))
5202 ((eq action 'recalc)
5204 (beginning-of-line 1)
5205 (skip-chars-backward " \r\n\t")
5206 (if (org-at-table-p)
5207 (org-call-with-arg 'org-table-recalculate t))))
5208 (t (let (orgtbl-mode)
5209 (call-interactively (key-binding "\C-c\C-c")))))))
5211 (defun orgtbl-create-or-convert-from-region (_arg)
5212 "Create table or convert region to table, if no conflicting binding.
5213 This installs the table binding `C-c |', but only if there is no
5214 conflicting binding to this key outside orgtbl-mode."
5216 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
5218 (call-interactively cmd)
5219 (call-interactively 'org-table-create-or-convert-from-region))))
5221 (defun orgtbl-tab (arg)
5222 "Justification and field motion for `orgtbl-mode'."
5224 (if arg (org-table-edit-field t)
5225 (org-table-justify-field-maybe)
5226 (org-table-next-field)))
5228 (defun orgtbl-ret ()
5229 "Justification and field motion for `orgtbl-mode'."
5233 (org-table-justify-field-maybe)
5234 (org-table-next-row)))
5236 (defun orgtbl-self-insert-command (N)
5237 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
5238 If the cursor is in a table looking at whitespace, the whitespace is
5239 overwritten, and the table is not marked as requiring realignment."
5241 (if (and (org-at-table-p)
5243 (and org-table-auto-blank-field
5244 (member last-command
5245 '(orgtbl-hijacker-command-100
5246 orgtbl-hijacker-command-101
5247 orgtbl-hijacker-command-102
5248 orgtbl-hijacker-command-103
5249 orgtbl-hijacker-command-104
5250 orgtbl-hijacker-command-105
5252 (org-table-blank-field))
5255 (looking-at "[^|\n]* \\( \\)|"))
5256 (let (org-table-may-need-update)
5257 (delete-region (match-beginning 1) (match-end 1))
5258 (self-insert-command N))
5259 (setq org-table-may-need-update t)
5262 (cmd (or (key-binding
5263 (or (and (listp function-key-map)
5264 (setq a (assoc last-input-event function-key-map))
5266 (vector last-input-event)))
5267 'self-insert-command)))
5268 (call-interactively cmd)
5269 (if (and org-self-insert-cluster-for-undo
5270 (eq cmd 'self-insert-command))
5271 (if (not (eq last-command 'orgtbl-self-insert-command))
5272 (setq org-self-insert-command-undo-counter 1)
5273 (if (>= org-self-insert-command-undo-counter 20)
5274 (setq org-self-insert-command-undo-counter 1)
5275 (and (> org-self-insert-command-undo-counter 0)
5277 (not (cadr buffer-undo-list)) ; remove nil entry
5278 (setcdr buffer-undo-list (cddr buffer-undo-list)))
5279 (setq org-self-insert-command-undo-counter
5280 (1+ org-self-insert-command-undo-counter))))))))
5283 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
5284 "Regular expression matching exponentials as produced by calc.")
5286 (defun orgtbl-gather-send-defs ()
5287 "Gather a plist of :name, :transform, :params for each destination before
5290 (goto-char (org-table-begin))
5292 (beginning-of-line 0)
5293 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
5294 (let ((name (org-no-properties (match-string 1)))
5295 (transform (intern (match-string 2)))
5296 (params (if (match-end 3)
5297 (read (concat "(" (match-string 3) ")")))))
5298 (push (list :name name :transform transform :params params)
5300 (beginning-of-line 0)))
5303 (defun orgtbl-send-replace-tbl (name text)
5304 "Find and replace table NAME with TEXT."
5306 (goto-char (point-min))
5307 (let* ((location-flag nil)
5308 (name (regexp-quote name))
5309 (begin-re (format "BEGIN +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name))
5310 (end-re (format "END +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name)))
5311 (while (re-search-forward begin-re nil t)
5312 (unless location-flag (setq location-flag t))
5313 (let ((beg (line-beginning-position 2)))
5314 (unless (re-search-forward end-re nil t)
5315 (user-error "Cannot find end of receiver location at %d" beg))
5317 (delete-region beg (point))
5318 (insert text "\n")))
5319 (unless location-flag
5320 (user-error "No valid receiver location found in the buffer")))))
5323 (defun org-table-to-lisp (&optional txt)
5324 "Convert the table at point to a Lisp structure.
5325 The structure will be a list. Each item is either the symbol `hline'
5326 for a horizontal separator line, or a list of field values as strings.
5327 The table is taken from the parameter TXT, or from the buffer at point."
5328 (unless (or txt (org-at-table-p)) (user-error "No table at point"))
5330 (buffer-substring-no-properties (org-table-begin)
5333 (if (string-match org-table-hline-regexp x) 'hline
5334 (org-split-string (org-trim x) "\\s-*|\\s-*")))
5335 (org-split-string txt "[ \t]*\n[ \t]*"))))
5337 (defun orgtbl-send-table (&optional maybe)
5338 "Send a transformed version of table at point to the receiver position.
5339 With argument MAYBE, fail quietly if no transformation is defined
5343 (unless (org-at-table-p) (user-error "Not at a table"))
5344 ;; when non-interactive, we assume align has just happened.
5345 (when (called-interactively-p 'any) (org-table-align))
5346 (let ((dests (orgtbl-gather-send-defs))
5347 (table (org-table-to-lisp
5348 (buffer-substring-no-properties (org-table-begin)
5352 (if maybe (throw 'exit nil)
5353 (user-error "Don't know how to transform this table")))
5354 (dolist (dest dests)
5355 (let ((name (plist-get dest :name))
5356 (transform (plist-get dest :transform))
5357 (params (plist-get dest :params)))
5358 (unless (fboundp transform)
5359 (user-error "No such transformation function %s" transform))
5360 (orgtbl-send-replace-tbl name (funcall transform table params)))
5362 (message "Table converted and installed at %d receiver location%s"
5363 ntbl (if (> ntbl 1) "s" ""))
5364 (and (> ntbl 0) ntbl))))
5366 (defun org-remove-by-index (list indices &optional i0)
5367 "Remove the elements in LIST with indices in INDICES.
5368 First element has index 0, or I0 if given."
5371 (if (integerp indices) (setq indices (list indices)))
5372 (setq i0 (1- (or i0 0)))
5373 (delq :rm (mapcar (lambda (x)
5375 (if (memq i0 indices) :rm x))
5378 (defun orgtbl-toggle-comment ()
5379 "Comment or uncomment the orgtbl at point."
5381 (let* ((case-fold-search t)
5382 (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
5383 (re2 (concat "^" orgtbl-line-start-regexp))
5384 (commented (save-excursion (beginning-of-line 1)
5385 (cond ((looking-at re1) t)
5386 ((looking-at re2) nil)
5387 (t (user-error "Not at an org table")))))
5388 (re (if commented re1 re2))
5391 (beginning-of-line 1)
5392 (while (looking-at re) (beginning-of-line 0))
5393 (beginning-of-line 2)
5395 (while (looking-at re) (beginning-of-line 2))
5397 (comment-region beg end (if commented '(4) nil))))
5399 (defun orgtbl-insert-radio-table ()
5400 "Insert a radio table template appropriate for this major mode."
5402 (let* ((e (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates))
5405 (unless e (user-error "No radio table setup defined for %s" major-mode))
5406 (setq name (read-string "Table name: "))
5407 (while (string-match "%n" txt)
5408 (setq txt (replace-match name t t txt)))
5409 (or (bolp) (insert "\n"))
5415 (defun orgtbl-to-generic (table params)
5416 "Convert the orgtbl-mode TABLE to some other format.
5418 This generic routine can be used for many standard cases.
5420 TABLE is a list, each entry either the symbol `hline' for
5421 a horizontal separator line, or a list of fields for that
5422 line. PARAMS is a property list of parameters that can
5423 influence the conversion.
5425 Valid parameters are:
5429 Export back-end used as a basis to transcode elements of the
5430 table, when no specific parameter applies to it. It is also
5431 used to translate cells contents. You can prevent this by
5432 setting :raw property to a non-nil value.
5436 When non-nil, only convert rows, not the table itself. This is
5437 equivalent to setting to the empty string both :tstart
5438 and :tend, which see.
5442 When set to an integer N, skip the first N lines of the table.
5443 Horizontal separation lines do count for this parameter!
5447 List of columns that should be skipped. If the table has
5448 a column with calculation marks, that column is automatically
5449 discarded beforehand.
5453 String to be inserted on horizontal separation lines. May be
5454 nil to ignore these lines altogether.
5458 Separator between two fields, as a string.
5460 Each in the following group may be either a string or a function
5461 of no arguments returning a string:
5465 Strings to start and end the table. Ignored when :splice is t.
5469 Strings to start and end a new table line.
5473 Strings to start and end the last table line. Default,
5474 respectively, to :lstart and :lend.
5476 Each in the following group may be a string or a function of one
5477 argument (either the cells in the current row, as a list of
5478 strings, or the current cell) returning a string:
5482 Format string for an entire row, with enough %s to capture all
5483 fields. When non-nil, :lstart, :lend, and :sep are ignored.
5487 Format for the entire last line, defaults to :lfmt.
5491 A format to be used to wrap the field, should contain %s for
5492 the original field value. For example, to wrap everything in
5493 dollars, you could use :fmt \"$%s$\". This may also be
5494 a property list with column numbers and format strings, or
5497 (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
5499 :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
5501 Same as above, specific for the header lines in the table.
5502 All lines before the first hline are treated as header. If
5503 any of these is not present, the data line value is used.
5505 This may be either a string or a function of two arguments:
5509 Use this format to print numbers with exponential. The format
5510 should have %s twice for inserting mantissa and exponent, for
5511 example \"%s\\\\times10^{%s}\". This may also be a property
5512 list with column numbers and format strings or functions.
5513 :fmt will still be applied after :efmt."
5514 ;; Make sure `org-export-create-backend' is available.
5516 (let* ((backend (plist-get params :backend))
5518 ;; Build a custom back-end according to PARAMS. Before
5519 ;; defining a translator, check if there is anything to do.
5520 ;; When there isn't, let BACKEND handle the element.
5521 (org-export-create-backend
5522 :parent (or backend 'org)
5524 `((table . ,(org-table--to-generic-table params))
5525 (table-row . ,(org-table--to-generic-row params))
5526 (table-cell . ,(org-table--to-generic-cell params))
5527 ;; Macros are not going to be expanded. However, no
5528 ;; regular back-end has a transcoder for them. We
5529 ;; provide one so they are not ignored, but displayed
5531 (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
5533 ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
5534 ;; Initialize communication channel in INFO.
5536 (let ((org-inhibit-startup t)) (org-mode))
5537 (let ((standard-output (current-buffer))
5538 (org-element-use-cache nil))
5540 (cond ((eq e 'hline) (princ "|--\n"))
5542 (princ "| ") (dolist (c e) (princ c) (princ " |"))
5544 ;; Add back-end specific filters, but not user-defined ones. In
5545 ;; particular, make sure to call parse-tree filters on the
5548 (let ((org-export-filters-alist nil))
5549 (org-export-install-filters
5551 (org-export-get-environment backend nil params)
5552 `(:back-end ,(org-export-get-backend backend))))))
5554 (org-export-filter-apply-functions
5555 (plist-get info :filter-parse-tree)
5556 (org-element-map (org-element-parse-buffer) 'table
5559 (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
5560 (user-error "Unknown :backend value"))
5561 (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
5562 ;; Handle :skip parameter.
5563 (let ((skip (plist-get info :skip)))
5565 (unless (wholenump skip) (user-error "Wrong :skip value"))
5567 (org-element-map data 'table-row
5570 (org-element-extract-element row)
5574 ;; Handle :skipcols parameter.
5575 (let ((skipcols (plist-get info :skipcols)))
5577 (unless (consp skipcols) (user-error "Wrong :skipcols value"))
5578 (org-element-map data 'table
5580 (let ((specialp (org-export-table-has-special-column-p table)))
5581 (dolist (row (org-element-contents table))
5582 (when (eq (org-element-property :type row) 'standard)
5584 (dolist (cell (nthcdr (if specialp 1 0)
5585 (org-element-contents row)))
5586 (when (memq c skipcols)
5587 (org-element-extract-element cell))
5588 (cl-incf c))))))))))
5589 ;; Since we are going to export using a low-level mechanism,
5590 ;; ignore special column and special rows manually.
5591 (let ((special? (org-export-table-has-special-column-p data))
5593 (org-element-map data (if special? '(table-cell table-row) 'table-row)
5595 (when (if (eq (org-element-type datum) 'table-row)
5596 (org-export-table-row-is-special-p datum nil)
5597 (org-export-first-sibling-p datum nil))
5598 (push datum ignore))))
5599 (setq info (plist-put info :ignore-list ignore)))
5600 ;; We use a low-level mechanism to export DATA so as to skip all
5601 ;; usual pre-processing and post-processing, i.e., hooks, Babel
5602 ;; code evaluation, include keywords and macro expansion. Only
5603 ;; back-end specific filters are retained.
5604 (let ((output (org-export-data-with-backend data custom-backend info)))
5605 ;; Remove final newline.
5606 (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
5608 (defun org-table--generic-apply (value name &optional with-cons &rest args)
5609 (cond ((null value) nil)
5610 ((functionp value) `(funcall ',value ,@args))
5612 (cond ((consp (car args)) `(apply #'format ,value ,@args))
5613 (args `(format ,value ,@args))
5615 ((and with-cons (consp value))
5616 `(let ((val (cadr (memq column ',value))))
5617 (cond ((null val) contents)
5618 ((stringp val) (format val ,@args))
5619 ((functionp val) (funcall val ,@args))
5620 (t (user-error "Wrong %s value" ,name)))))
5621 (t (user-error "Wrong %s value" name))))
5623 (defun org-table--to-generic-table (params)
5624 "Return custom table transcoder according to PARAMS.
5625 PARAMS is a plist. See `orgtbl-to-generic' for more
5627 (let ((backend (plist-get params :backend))
5628 (splice (plist-get params :splice))
5629 (tstart (plist-get params :tstart))
5630 (tend (plist-get params :tend)))
5631 `(lambda (table contents info)
5633 ,(and tstart (not splice)
5634 `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
5635 ,(if (or (not backend) tstart tend splice) 'contents
5636 `(org-export-with-backend ',backend table contents info))
5637 ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
5639 (defun org-table--to-generic-row (params)
5640 "Return custom table row transcoder according to PARAMS.
5641 PARAMS is a plist. See `orgtbl-to-generic' for more
5643 (let* ((backend (plist-get params :backend))
5644 (lstart (plist-get params :lstart))
5645 (llstart (plist-get params :llstart))
5646 (hlstart (plist-get params :hlstart))
5647 (hllstart (plist-get params :hllstart))
5648 (lend (plist-get params :lend))
5649 (llend (plist-get params :llend))
5650 (hlend (plist-get params :hlend))
5651 (hllend (plist-get params :hllend))
5652 (lfmt (plist-get params :lfmt))
5653 (llfmt (plist-get params :llfmt))
5654 (hlfmt (plist-get params :hlfmt))
5655 (hllfmt (plist-get params :hllfmt)))
5656 `(lambda (row contents info)
5657 (if (eq (org-element-property :type row) 'rule)
5659 ((plist-member params :hline)
5660 (org-table--generic-apply (plist-get params :hline) ":hline"))
5661 (backend `(org-export-with-backend ',backend row nil info)))
5662 (let ((headerp ,(and (or hlfmt hlstart hlend)
5663 '(org-export-table-row-in-header-p row info)))
5665 ,(and (or hllfmt hllstart hllend)
5666 '(org-export-table-row-ends-header-p row info)))
5667 (lastp (not (org-export-get-next-element row info))))
5669 ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
5670 ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
5671 ;; `:lstart', `:lend' and their relatives.
5673 '(org-element-map row 'table-cell
5675 ;; Export all cells, without separators.
5677 ;; Use `org-export-data-with-backend'
5678 ;; instead of `org-export-data' to eschew
5679 ;; cached values, which
5680 ;; ignore :orgtbl-ignore-sep parameter.
5681 (org-export-data-with-backend
5683 (plist-get info :back-end)
5684 (org-combine-plists info '(:orgtbl-ignore-sep t))))
5688 `(last-header-p ,(org-table--generic-apply
5689 hllfmt ":hllfmt" nil cells)))
5691 `(headerp ,(org-table--generic-apply
5692 hlfmt ":hlfmt" nil cells)))
5694 `(lastp ,(org-table--generic-apply
5695 llfmt ":llfmt" nil cells)))
5697 ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
5701 (or hllstart hllend)
5704 ,(org-table--generic-apply hllstart ":hllstart")
5706 ,(org-table--generic-apply hllend ":hllend"))))
5711 ,(org-table--generic-apply hlstart ":hlstart")
5713 ,(org-table--generic-apply hlend ":hlend"))))
5718 ,(org-table--generic-apply llstart ":llstart")
5720 ,(org-table--generic-apply llend ":llend"))))
5725 ,(org-table--generic-apply lstart ":lstart")
5727 ,(org-table--generic-apply lend ":lend")))
5729 `(org-export-with-backend
5730 ',backend row contents info))
5731 (t 'contents)))))))))))))))
5733 (defun org-table--to-generic-cell (params)
5734 "Return custom table cell transcoder according to PARAMS.
5735 PARAMS is a plist. See `orgtbl-to-generic' for more
5737 (let* ((backend (plist-get params :backend))
5738 (efmt (plist-get params :efmt))
5739 (fmt (plist-get params :fmt))
5740 (hfmt (plist-get params :hfmt))
5741 (sep (plist-get params :sep))
5742 (hsep (plist-get params :hsep)))
5743 `(lambda (cell contents info)
5744 ;; Make sure that contents are exported as Org data when :raw
5745 ;; parameter is non-nil.
5746 ,(when (and backend (plist-get params :raw))
5748 ;; Since we don't know what are the pseudo object
5749 ;; types defined in backend, we cannot pass them to
5750 ;; `org-element-interpret-data'. As a consequence,
5751 ;; they will be treated as pseudo elements, and will
5752 ;; have newlines appended instead of spaces.
5753 ;; Therefore, we must make sure :post-blank value is
5754 ;; really turned into spaces.
5755 (replace-regexp-in-string
5758 (org-element-interpret-data
5759 (org-element-contents cell))))))
5761 (let ((headerp ,(and (or hfmt hsep)
5762 '(org-export-table-row-in-header-p
5763 (org-export-get-parent-element cell) info)))
5765 ;; Call costly `org-export-table-cell-address' only if
5766 ;; absolutely necessary, i.e., if one
5767 ;; of :fmt :efmt :hfmt has a "plist type" value.
5768 ,(and (cl-some (lambda (v) (integerp (car-safe v)))
5769 (list efmt hfmt fmt))
5770 '(1+ (cdr (org-export-table-cell-address cell info))))))
5772 ;; Check if we can apply `:efmt' on CONTENTS.
5774 `(when (string-match orgtbl-exp-regexp contents)
5775 (let ((mantissa (match-string 1 contents))
5776 (exponent (match-string 2 contents)))
5777 (setq contents ,(org-table--generic-apply
5778 efmt ":efmt" t 'mantissa 'exponent)))))
5779 ;; Check if we can apply FMT (or HFMT) on CONTENTS.
5781 ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
5782 hfmt ":hfmt" t 'contents))))
5783 ,(and fmt `(t (setq contents ,(org-table--generic-apply
5784 fmt ":fmt" t 'contents))))))
5785 ;; If a separator is provided, use it instead of BACKEND's.
5786 ;; Separators are ignored when LFMT (or equivalent) is
5790 `(if (or ,(and (not sep) '(not headerp))
5791 (plist-get info :orgtbl-ignore-sep)
5792 (not (org-export-get-next-element cell info)))
5793 ,(if (not backend) 'contents
5794 `(org-export-with-backend ',backend cell contents info))
5796 ,(if (and sep hsep) `(if headerp ,hsep ,sep)
5798 (backend `(org-export-with-backend ',backend cell contents info))
5802 (defun orgtbl-to-tsv (table params)
5803 "Convert the orgtbl-mode table to TAB separated material."
5804 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
5807 (defun orgtbl-to-csv (table params)
5808 "Convert the orgtbl-mode table to CSV material.
5809 This does take care of the proper quoting of fields with comma or quotes."
5810 (orgtbl-to-generic table
5811 (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
5815 (defun orgtbl-to-latex (table params)
5816 "Convert the orgtbl-mode TABLE to LaTeX.
5818 TABLE is a list, each entry either the symbol `hline' for
5819 a horizontal separator line, or a list of fields for that line.
5820 PARAMS is a property list of parameters that can influence the
5821 conversion. All parameters from `orgtbl-to-generic' are
5822 supported. It is also possible to use the following ones:
5826 When non-nil, use formal \"booktabs\" style.
5830 Specify environment to use, as a string. If you use
5831 \"longtable\", you may also want to specify :language property,
5832 as a string, to get proper continuation strings."
5837 ;; Provide sane default values.
5838 (list :backend 'latex
5839 :latex-default-table-mode 'table
5840 :latex-tables-centered nil
5841 :latex-tables-booktabs (plist-get params :booktabs)
5842 :latex-table-scientific-notation nil
5843 :latex-default-table-environment
5844 (or (plist-get params :environment) "tabular"))
5848 (defun orgtbl-to-html (table params)
5849 "Convert the orgtbl-mode TABLE to HTML.
5851 TABLE is a list, each entry either the symbol `hline' for
5852 a horizontal separator line, or a list of fields for that line.
5853 PARAMS is a property list of parameters that can influence the
5854 conversion. All parameters from `orgtbl-to-generic' are
5855 supported. It is also possible to use the following one:
5859 Attributes and values, as a plist, which will be used in
5865 ;; Provide sane default values.
5866 (list :backend 'html
5867 :html-table-data-tags '("<td%s>" . "</td>")
5868 :html-table-use-header-tags-for-first-column nil
5869 :html-table-align-individual-fields t
5870 :html-table-row-tags '("<tr>" . "</tr>")
5871 :html-table-attributes
5872 (if (plist-member params :attributes)
5873 (plist-get params :attributes)
5874 '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
5879 (defun orgtbl-to-texinfo (table params)
5880 "Convert the orgtbl-mode TABLE to Texinfo.
5882 TABLE is a list, each entry either the symbol `hline' for
5883 a horizontal separator line, or a list of fields for that line.
5884 PARAMS is a property list of parameters that can influence the
5885 conversion. All parameters from `orgtbl-to-generic' are
5886 supported. It is also possible to use the following one:
5890 Column widths, as a string. When providing column fractions,
5891 \"@columnfractions\" command can be omitted."
5892 (require 'ox-texinfo)
5897 (list :backend 'texinfo
5898 :texinfo-tables-verbatim nil
5899 :texinfo-table-scientific-notation nil)
5901 (columns (let ((w (plist-get params :columns)))
5903 ((string-match-p "{\\|@columnfractions " w) w)
5904 (t (concat "@columnfractions " w))))))
5905 (if (not columns) output
5906 (replace-regexp-in-string
5907 "@multitable \\(.*\\)" columns output t nil 1))))
5910 (defun orgtbl-to-orgtbl (table params)
5911 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
5913 TABLE is a list, each entry either the symbol `hline' for
5914 a horizontal separator line, or a list of fields for that line.
5915 PARAMS is a property list of parameters that can influence the
5916 conversion. All parameters from `orgtbl-to-generic' are
5919 Useful when slicing one table into many. The :hline, :sep,
5920 :lstart, and :lend provide orgtbl framing. :tstart and :tend can
5921 be set to provide ORGTBL directives for the generated table."
5923 (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
5925 (defun orgtbl-to-table.el (table params)
5926 "Convert the orgtbl-mode TABLE into a table.el table.
5927 TABLE is a list, each entry either the symbol `hline' for
5928 a horizontal separator line, or a list of fields for that line.
5929 PARAMS is a property list of parameters that can influence the
5930 conversion. All parameters from `orgtbl-to-generic' are
5933 (insert (orgtbl-to-orgtbl table params))
5935 (replace-regexp-in-string
5937 (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
5939 (defun orgtbl-to-unicode (table params)
5940 "Convert the orgtbl-mode TABLE into a table with unicode characters.
5942 TABLE is a list, each entry either the symbol `hline' for
5943 a horizontal separator line, or a list of fields for that line.
5944 PARAMS is a property list of parameters that can influence the
5945 conversion. All parameters from `orgtbl-to-generic' are
5946 supported. It is also possible to use the following ones:
5950 When non-nil, use \"ascii-art-to-unicode\" package to translate
5951 the table. You can download it here:
5952 http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
5956 When non-nil, narrow columns width than provided width cookie,
5957 using \"=>\" as an ellipsis, just like in an Org mode buffer."
5962 (list :backend 'ascii
5963 :ascii-charset 'utf-8
5964 :ascii-table-widen-columns (not (plist-get params :narrow))
5965 :ascii-table-use-ascii-art (plist-get params :ascii-art))
5968 ;; Put the cursor in a column containing numerical values
5971 ;; A new column is added with a bar plot.
5972 ;; When the table is refreshed (C-u C-c *),
5973 ;; the plot is updated to reflect the new values.
5975 (defun orgtbl-ascii-draw (value min max &optional width characters)
5976 "Draw an ascii bar in a table.
5977 VALUE is the value to plot, it determines the width of the bar to draw.
5978 MIN is the value that will be displayed as empty (zero width bar).
5979 MAX is the value that will draw a bar filling all the WIDTH.
5980 WIDTH is the span in characters from MIN to MAX.
5981 CHARACTERS is a string that will compose the bar, with shades of grey
5982 from pure white to pure black. It defaults to a 10 characters string
5983 of regular ascii characters."
5984 (let* ((width (ceiling (or width 12)))
5985 (characters (or characters " .:;c!lhVHW"))
5986 (len (1- (length characters)))
5987 (value (float (if (numberp value)
5988 value (string-to-number value))))
5989 (relative (/ (- value min) (- max min)))
5990 (steps (round (* relative width len))))
5991 (cond ((< steps 0) "too small")
5992 ((> steps (* width len)) "too large")
5993 (t (let* ((int-division (/ steps len))
5994 (remainder (- steps (* int-division len))))
5995 (concat (make-string int-division (elt characters len))
5996 (string (elt characters remainder))))))))
5999 (defun orgtbl-ascii-plot (&optional ask)
6000 "Draw an ASCII bar plot in a column.
6002 With cursor in a column containing numerical values, this function
6003 will draw a plot in a new column.
6005 ASK, if given, is a numeric prefix to override the default 12
6006 characters width of the plot. ASK may also be the `\\[universal-argument]' \
6008 which will prompt for the width."
6010 (let ((col (org-table-current-column))
6011 (min 1e999) ; 1e999 will be converted to infinity
6012 (max -1e999) ; which is the desired result
6013 (table (org-table-to-lisp))
6016 (read-number "Length of column " 12))
6019 ;; Skip any hline a the top of table.
6020 (while (eq (car table) 'hline) (setq table (cdr table)))
6021 ;; Skip table header if any.
6022 (dolist (x (or (cdr (memq 'hline table)) table))
6024 (setq x (nth (1- col) x))
6026 "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
6028 (setq x (string-to-number x))
6029 (when (> min x) (setq min x))
6030 (when (< max x) (setq max x)))))
6031 (org-table-insert-column)
6032 (org-table-move-column-right)
6033 (org-table-store-formulas
6036 (concat "$" (number-to-string (1+ col)))
6037 (format "'(%s $%s %s %s %s)"
6038 "orgtbl-ascii-draw" col min max length))
6039 (org-table-get-stored-formulas)))
6040 (org-table-recalculate t)))
6042 ;; Example of extension: unicode characters
6043 ;; Here are two examples of different styles.
6045 ;; Unicode block characters are used to give a smooth effect.
6046 ;; See http://en.wikipedia.org/wiki/Block_Elements
6047 ;; Use one of those drawing functions
6048 ;; - orgtbl-ascii-draw (the default ascii)
6049 ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
6050 ;; - orgtbl-uc-draw-cont (smooth unicode)
6052 ;; This is best viewed with the "DejaVu Sans Mono" font
6053 ;; (use M-x set-frame-font).
6055 (defun orgtbl-uc-draw-grid (value min max &optional width)
6056 "Draw a bar in a table using block unicode characters.
6057 It is a variant of orgtbl-ascii-draw with Unicode block
6058 characters, for a smooth display. Bars appear as grids (to the
6059 extent the font allows)."
6060 ;; http://en.wikipedia.org/wiki/Block_Elements
6061 ;; best viewed with the "DejaVu Sans Mono" font.
6062 (orgtbl-ascii-draw value min max width
6063 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
6065 (defun orgtbl-uc-draw-cont (value min max &optional width)
6066 "Draw a bar in a table using block unicode characters.
6067 It is a variant of orgtbl-ascii-draw with Unicode block
6068 characters, for a smooth display. Bars are solid (to the extent
6070 (orgtbl-ascii-draw value min max width
6071 " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
6073 (defun org-table-get-remote-range (name-or-id form)
6074 "Get a field value or a list of values in a range from table at ID.
6076 NAME-OR-ID may be the name of a table in the current file as set
6077 by a \"#+NAME:\" directive. The first table following this line
6078 will then be used. Alternatively, it may be an ID referring to
6079 any entry, also in a different file. In this case, the first
6080 table in that entry will be referenced.
6081 FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
6082 \"@I$2..@II$2\". All the references must be absolute, not relative.
6084 The return value is either a single string for a single field, or a
6085 list of the fields in the rectangle."
6087 (let ((case-fold-search t) (id-loc nil)
6088 ;; Protect a bunch of variables from being overwritten by
6089 ;; the context of the remote table.
6090 org-table-column-names org-table-column-name-regexp
6091 org-table-local-parameters org-table-named-field-locations
6092 org-table-current-line-types
6093 org-table-current-begin-pos org-table-dlines
6094 org-table-current-ncol
6096 org-table-last-column-widths
6097 org-table-last-alignment
6099 (setq form (org-table-convert-refs-to-rc form))
6100 (org-with-wide-buffer
6101 (goto-char (point-min))
6102 (if (re-search-forward
6103 (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
6104 (regexp-quote name-or-id) "[ \t]*$")
6106 (setq buffer (current-buffer) loc (match-beginning 0))
6107 (setq id-loc (org-id-find name-or-id 'marker))
6108 (unless (and id-loc (markerp id-loc))
6109 (user-error "Can't find remote table \"%s\"" name-or-id))
6110 (setq buffer (marker-buffer id-loc)
6111 loc (marker-position id-loc))
6112 (move-marker id-loc nil))
6113 (with-current-buffer buffer
6114 (org-with-wide-buffer
6117 (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
6118 (not (match-beginning 1)))
6119 (user-error "Cannot find a table at NAME or ID %s" name-or-id))
6121 (setq form (org-table-formula-substitute-names
6122 (org-table-formula-handle-first/last-rc form)))
6123 (if (and (string-match org-table-range-regexp form)
6124 (> (length (match-string 0 form)) 1))
6125 (org-table-get-range
6126 (match-string 0 form) org-table-current-begin-pos 1)
6129 (defun org-table-remote-reference-indirection (form)
6130 "Return formula with table remote references substituted by indirection.
6131 For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
6132 This indirection works only with the format @ROW$COLUMN. The
6133 format \"B3\" is not supported because it can not be
6134 distinguished from a plain table name or ID."
6136 ;; Same as in `org-table-eval-formula'.
6137 (concat "\\<remote([ \t]*\\("
6138 ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
6140 "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")))
6141 (replace-regexp-in-string
6145 (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m))))
6146 (org-table-get-range
6147 (if (string-match-p "\\`\\$[0-9]+\\'" eq)
6152 (defmacro org-define-lookup-function (mode)
6153 (let ((mode-str (symbol-name mode))
6154 (first-p (eq mode 'first))
6155 (all-p (eq mode 'all)))
6156 (let ((plural-str (if all-p "s" "")))
6157 `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
6158 ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
6159 If R-LIST is nil, return matching element%s of S-LIST.
6160 If PREDICATE is not nil, use it instead of `equal' to match VAL.
6161 Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
6162 This function is generated by a call to the macro `org-define-lookup-function'."
6163 mode-str plural-str plural-str plural-str)
6164 (let ,(let ((lvars '((p (or predicate 'equal))
6166 (rl (or r-list s-list))
6168 (if first-p (cons '(match-p nil) lvars) lvars))
6169 (while ,(if first-p '(and (not match-p) sl) 'sl)
6170 (when (funcall p val (car sl))
6171 ,(when first-p '(setq match-p t))
6172 (let ((rval (car rl)))
6173 (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
6174 (setq sl (cdr sl) rl (cdr rl)))
6177 (org-define-lookup-function first)
6178 (org-define-lookup-function last)
6179 (org-define-lookup-function all)
6181 (provide 'org-table)
6184 ;; generated-autoload-file: "org-loaddefs.el"
6187 ;;; org-table.el ends here