1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
29 ;; This file contains the table editor and spreadsheet for Org-mode.
31 ;; Watch out: Here we are talking about two different kind of tables.
32 ;; Most of the code is for the tables created with the Org-mode table editor.
33 ;; Sometimes, we talk about tables created and edited with the table.el
34 ;; Emacs package. We call the former org-type tables, and the latter
35 ;; table.el-type tables.
43 (declare-function org-table-clean-before-export
"org-exp"
44 (lines &optional maybe-quoted
))
45 (declare-function org-format-org-table-html
"org-html" (lines &optional splice
))
46 (defvar orgtbl-mode
) ; defined below
47 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
48 (defvar org-export-html-table-tag
) ; defined in org-exp.el
49 (defvar constants-unit-system
)
51 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
52 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
53 In the optimized version, the table editor takes over all simple keys that
54 normally just insert a character. In tables, the characters are inserted
55 in a way to minimize disturbing the table structure (i.e. in overwrite mode
56 for empty fields). Outside tables, the correct binding of the keys is
59 The default for this option is t if the optimized version is also used in
60 Org-mode. See the variable `org-enable-table-editor' for details. Changing
61 this variable requires a restart of Emacs to become effective."
65 (defcustom orgtbl-radio-table-templates
66 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
67 % END RECEIVE ORGTBL %n
69 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
72 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
73 @c END RECEIVE ORGTBL %n
75 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
78 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
79 <!-- END RECEIVE ORGTBL %n -->
81 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
84 "Templates for radio tables in different major modes.
85 All occurrences of %n in a template will be replaced with the name of the
86 table, obtained by prompting the user."
89 (list (symbol :tag
"Major mode")
90 (string :tag
"Format"))))
92 (defgroup org-table-settings nil
93 "Settings for tables in Org-mode."
94 :tag
"Org Table Settings"
97 (defcustom org-table-default-size
"5x2"
98 "The default size for newly created tables, Columns x Rows."
99 :group
'org-table-settings
102 (defcustom org-table-number-regexp
103 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
104 "Regular expression for recognizing numbers in table columns.
105 If a table column contains mostly numbers, it will be aligned to the
106 right. If not, it will be aligned to the left.
108 The default value of this option is a regular expression which allows
109 anything which looks remotely like a number as used in scientific
110 context. For example, all of the following will be considered a
112 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
114 Other options offered by the customize interface are more restrictive."
115 :group
'org-table-settings
117 (const :tag
"Positive Integers"
119 (const :tag
"Integers"
121 (const :tag
"Floating Point Numbers"
122 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
123 (const :tag
"Floating Point Number or Integer"
124 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
125 (const :tag
"Exponential, Floating point, Integer"
126 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
127 (const :tag
"Very General Number-Like, including hex"
128 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
129 (string :tag
"Regexp:")))
131 (defcustom org-table-number-fraction
0.5
132 "Fraction of numbers in a column required to make the column align right.
133 In a column all non-white fields are considered. If at least this
134 fraction of fields is matched by `org-table-number-fraction',
135 alignment to the right border applies."
136 :group
'org-table-settings
139 (defgroup org-table-editing nil
140 "Behavior of tables during editing in Org-mode."
141 :tag
"Org Table Editing"
144 (defcustom org-table-automatic-realign t
145 "Non-nil means automatically re-align table when pressing TAB or RETURN.
146 When nil, aligning is only done with \\[org-table-align], or after column
148 :group
'org-table-editing
151 (defcustom org-table-auto-blank-field t
152 "Non-nil means automatically blank table field when starting to type into it.
153 This only happens when typing immediately after a field motion
154 command (TAB, S-TAB or RET).
155 Only relevant when `org-enable-table-editor' is equal to `optimized'."
156 :group
'org-table-editing
159 (defcustom org-table-tab-jumps-over-hlines t
160 "Non-nil means tab in the last column of a table with jump over a hline.
161 If a horizontal separator line is following the current line,
162 `org-table-next-field' can either create a new row before that line, or jump
163 over the line. When this option is nil, a new line will be created before
165 :group
'org-table-editing
168 (defgroup org-table-calculation nil
169 "Options concerning tables in Org-mode."
170 :tag
"Org Table Calculation"
173 (defcustom org-table-use-standard-references t
174 "Should org-mode work with table references like B3 instead of @3$2?
177 from accept as input, do not present for editing
178 t: accept as input and present for editing"
179 :group
'org-table-calculation
181 (const :tag
"Never, don't even check user input for them" nil
)
182 (const :tag
"Always, both as user input, and when editing" t
)
183 (const :tag
"Convert user input, don't offer during editing" 'from
)))
185 (defcustom org-table-copy-increment t
186 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
187 :group
'org-table-calculation
190 (defcustom org-calc-default-modes
191 '(calc-internal-prec 12
192 calc-float-format
(float 8)
195 calc-symbolic-mode nil
196 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
197 calc-display-working-message t
199 "List with Calc mode settings for use in calc-eval for table formulas.
200 The list must contain alternating symbols (Calc modes variables and values).
201 Don't remove any of the default settings, just change the values. Org-mode
202 relies on the variables to be present in the list."
203 :group
'org-table-calculation
206 (defcustom org-table-formula-evaluate-inline t
207 "Non-nil means TAB and RET evaluate a formula in current table field.
208 If the current field starts with an equal sign, it is assumed to be a formula
209 which should be evaluated as described in the manual and in the documentation
210 string of the command `org-table-eval-formula'. This feature requires the
212 When this variable is nil, formula calculation is only available through
213 the command \\[org-table-eval-formula]."
214 :group
'org-table-calculation
217 (defcustom org-table-formula-use-constants t
218 "Non-nil means interpret constants in formulas in tables.
219 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
220 by the value given in `org-table-formula-constants', or by a value obtained
221 from the `constants.el' package."
222 :group
'org-table-calculation
225 (defcustom org-table-formula-constants nil
226 "Alist with constant names and values, for use in table formulas.
227 The car of each element is a name of a constant, without the `$' before it.
228 The cdr is the value as a string. For example, if you'd like to use the
229 speed of light in a formula, you would configure
231 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
233 and then use it in an equation like `$1*$c'.
235 Constants can also be defined on a per-file basis using a line like
237 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
238 :group
'org-table-calculation
240 (cons (string :tag
"name")
241 (string :tag
"value"))))
243 (defcustom org-table-allow-automatic-line-recalculation t
244 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
245 Automatically means when TAB or RET or C-c C-c are pressed in the line."
246 :group
'org-table-calculation
249 (defcustom org-table-error-on-row-ref-crossing-hline t
250 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
254 (defcustom org-table-relative-ref-may-cross-hline t
255 "Non-nil means relative formula references may cross hlines.
256 Here are the allowed values:
258 nil Relative references may not cross hlines. They will reference the
259 field next to the hline instead. Coming from below, the reference
260 will be to the field below the hline. Coming from above, it will be
262 t Relative references may cross hlines.
263 error An attempt to cross a hline will throw an error.
265 It is probably good to never set this variable to nil, for the sake of
266 portability of tables."
267 :group
'org-table-calculation
269 (const :tag
"Allow to cross" t
)
270 (const :tag
"Stick to hline" nil
)
271 (const :tag
"Error on attempt to cross" error
)))
273 (defgroup org-table-import-export nil
274 "Options concerning table import and export in Org-mode."
275 :tag
"Org Table Import Export"
278 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
279 "Default export parameters for org-table-export. These can be
280 overridden on for a specific table by setting the TABLE_EXPORT_FORMAT
281 property. See the manual section on orgtbl radio tables for the different
282 export transformations and available parameters."
283 :group
'org-table-import-export
286 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
287 "Detects a table line marked for automatic recalculation.")
288 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
289 "Detects a table line marked for automatic recalculation.")
290 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
291 "Detects a table line marked for automatic recalculation.")
292 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
293 "Searching from within a table (any type) this finds the first line
295 (defvar org-table-last-highlighted-reference nil
)
296 (defvar org-table-formula-history nil
)
298 (defvar org-table-column-names nil
299 "Alist with column names, derived from the `!' line.")
300 (defvar org-table-column-name-regexp nil
301 "Regular expression matching the current column names.")
302 (defvar org-table-local-parameters nil
303 "Alist with parameter names, derived from the `$' line.")
304 (defvar org-table-named-field-locations nil
305 "Alist with locations of named fields.")
307 (defvar org-table-current-line-types nil
308 "Table row types, non-nil only for the duration of a comand.")
309 (defvar org-table-current-begin-line nil
310 "Table begin line, non-nil only for the duration of a comand.")
311 (defvar org-table-current-begin-pos nil
312 "Table begin position, non-nil only for the duration of a comand.")
313 (defvar org-table-dlines nil
314 "Vector of data line line numbers in the current table.")
315 (defvar org-table-hlines nil
316 "Vector of hline line numbers in the current table.")
318 (defconst org-table-range-regexp
319 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
321 "Regular expression for matching ranges in formulas.")
323 (defconst org-table-range-regexp2
325 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
327 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
328 "Match a range for reference display.")
330 (defconst org-table-translate-regexp
331 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
332 "Match a reference that needs translation, for reference display.")
334 (defun org-table-create-with-table.el
()
335 "Use the table.el package to insert a new table.
336 If there is already a table at point, convert between Org-mode tables
337 and table.el tables."
342 (if (y-or-n-p "Convert table to Org-mode table? ")
343 (org-table-convert)))
345 (if (y-or-n-p "Convert table to table.el table? ")
346 (org-table-convert)))
347 (t (call-interactively 'table-insert
))))
349 (defun org-table-create-or-convert-from-region (arg)
350 "Convert region to table, or create an empty table.
351 If there is an active region, convert it to a table, using the function
352 `org-table-convert-region'. See the documentation of that function
353 to learn how the prefix argument is interpreted to determine the field
355 If there is no such region, create an empty table with `org-table-create'."
357 (if (org-region-active-p)
358 (org-table-convert-region (region-beginning) (region-end) arg
)
359 (org-table-create arg
)))
361 (defun org-table-create (&optional size
)
362 "Query for a size and insert a table skeleton.
363 SIZE is a string Columns x Rows like for example \"3x2\"."
366 (setq size
(read-string
367 (concat "Table size Columns x Rows [e.g. "
368 org-table-default-size
"]: ")
369 "" nil org-table-default-size
)))
372 (indent (make-string (current-column) ?\
))
373 (split (org-split-string size
" *x *"))
374 (rows (string-to-number (nth 1 split
)))
375 (columns (string-to-number (car split
)))
376 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
378 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
379 (point-at-bol) (point)))
380 (beginning-of-line 1)
382 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
383 (dotimes (i rows
) (insert line
))
386 ;; Insert a hline after the first row.
393 (defun org-table-convert-region (beg0 end0
&optional separator
)
394 "Convert region to a table.
395 The region goes from BEG0 to END0, but these borders will be moved
396 slightly, to make sure a beginning of line in the first line is included.
398 SEPARATOR specifies the field separator in the lines. It can have the
401 '(4) Use the comma as a field separator
402 '(16) Use a TAB as field separator
403 integer When a number, use that many spaces as field separator
404 nil When nil, the command tries to be smart and figure out the
405 separator in the following way:
406 - when each line contains a TAB, assume TAB-separated material
407 - when each line contains a comma, assume CSV material
408 - else, assume one or more SPACE characters as separator."
410 (let* ((beg (min beg0 end0
))
411 (end (max beg0 end0
))
414 (beginning-of-line 1)
415 (setq beg
(move-marker (make-marker) (point)))
417 (if (bolp) (backward-char 1) (end-of-line 1))
418 (setq end
(move-marker (make-marker) (point)))
419 ;; Get the right field separator
424 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
425 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
428 (if (equal separator
'(4))
429 (while (<= (point) end
)
430 ;; parse the csv stuff
432 ((looking-at "^") (insert "| "))
433 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
434 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
435 (replace-match "\\1")
436 (if (looking-at "\"") (insert "\"")))
437 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
438 ((looking-at "[ \t]*,") (replace-match " | "))
439 (t (beginning-of-line 2))))
441 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
442 ((equal separator
'(16)) "^\\|\t")
443 ((integerp separator
)
444 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
))
445 (t (error "This should not happen"))))
446 (while (re-search-forward re end t
)
447 (replace-match "| " t t
)))
451 (defun org-table-import (file arg
)
452 "Import FILE as a table.
453 The file is assumed to be tab-separated. Such files can be produced by most
454 spreadsheet and database applications. If no tabs (at least one per line)
455 are found, lines will be split on whitespace into fields."
457 (or (bolp) (newline))
460 (insert-file-contents file
)
461 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
464 (defvar org-table-last-alignment
)
465 (defvar org-table-last-column-widths
)
466 (defun org-table-export (&optional file format
)
467 "Export table to a file, with configurable format.
468 Such a file can be imported into a spreadsheet program like Excel.
469 FILE can be the output file name. If not given, it will be taken from
470 a TABLE_EXPORT_FILE property in the current entry or higher up in the
471 hierarchy, or the user will be prompted for a file name.
472 FORMAT can be an export format, of the same kind as it used when
473 orgtbl-mode sends a table in a different format. The default format can
474 be found in the variable `org-table-export-default-format', but the function
475 first checks if there is an export format specified in a TABLE_EXPORT_FORMAT
476 property, locally or anywhere up in the hierarchy."
478 (unless (org-at-table-p)
479 (error "No table at point"))
481 (org-table-align) ;; make sure we have everything we need
482 (let* ((beg (org-table-begin))
483 (end (org-table-end))
484 (txt (buffer-substring-no-properties beg end
))
487 (org-entry-get beg
"TABLE_EXPORT_FILE" t
)
491 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)
495 (setq file
(read-file-name "Export table to: "))
496 (unless (or (not (file-exists-p file
))
497 (y-or-n-p (format "Overwrite file %s? " file
)))
499 (if (file-directory-p file
)
500 (error "This is a directory path, not a file"))
501 (if (and (buffer-file-name)
502 (equal (file-truename file
)
503 (file-truename (buffer-file-name))))
504 (error "Please specify a file name that is different from current"))
506 (setq deffmt-readable org-table-export-default-format
)
507 (while (string-match "\t" deffmt-readable
)
508 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
509 (while (string-match "\n" deffmt-readable
)
510 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
511 (setq format
(org-completing-read
513 '("orgtbl-to-tsv" "orgtbl-to-csv"
514 "orgtbl-to-latex" "orgtbl-to-html"
515 "orgtbl-to-generic" "orgtbl-to-texinfo"
516 "orgtbl-to-orgtbl") nil nil
518 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
519 (let* ((transform (intern (match-string 1 format
)))
520 (params (if (match-end 2)
521 (read (concat "(" (match-string 2 format
) ")"))))
522 (skip (plist-get params
:skip
))
523 (skipcols (plist-get params
:skipcols
))
524 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
525 (lines (org-table-clean-before-export lines
))
526 (i0 (if org-table-clean-did-remove-column
2 1))
529 (if (string-match org-table-hline-regexp x
)
532 (org-split-string (org-trim x
) "\\s-*|\\s-*")
535 (fun (if (= i0
2) 'cdr
'identity
))
536 (org-table-last-alignment
537 (org-remove-by-index (funcall fun org-table-last-alignment
)
539 (org-table-last-column-widths
540 (org-remove-by-index (funcall fun org-table-last-column-widths
)
543 (unless (fboundp transform
)
544 (error "No such transformation function %s" transform
))
545 (setq txt
(funcall transform table params
))
547 (with-current-buffer (find-file-noselect file
)
548 (setq buf
(current-buffer))
554 (message "Export done."))
555 (error "TABLE_EXPORT_FORMAT invalid"))))
557 (defvar org-table-aligned-begin-marker
(make-marker)
558 "Marker at the beginning of the table last aligned.
559 Used to check if cursor still is in that table, to minimize realignment.")
560 (defvar org-table-aligned-end-marker
(make-marker)
561 "Marker at the end of the table last aligned.
562 Used to check if cursor still is in that table, to minimize realignment.")
563 (defvar org-table-last-alignment nil
564 "List of flags for flushright alignment, from the last re-alignment.
565 This is being used to correctly align a single field after TAB or RET.")
566 (defvar org-table-last-column-widths nil
567 "List of max width of fields in each column.
568 This is being used to correctly align a single field after TAB or RET.")
569 (defvar org-table-formula-debug nil
570 "Non-nil means debug table formulas.
571 When nil, simply write \"#ERROR\" in corrupted fields.")
572 (make-variable-buffer-local 'org-table-formula-debug
)
573 (defvar org-table-overlay-coordinates nil
574 "Overlay coordinates after each align of a table.")
575 (make-variable-buffer-local 'org-table-overlay-coordinates
)
577 (defvar org-last-recalc-line nil
)
578 (defvar org-table-do-narrow t
) ; for dynamic scoping
579 (defconst org-narrow-column-arrow
"=>"
580 "Used as display property in narrowed table columns.")
582 (defun org-table-align ()
583 "Align the table at point by aligning all vertical bars."
587 (beg (org-table-begin))
588 (end (org-table-end))
589 ;; Current cursor position
590 (linepos (org-current-line))
591 (colpos (org-table-current-column))
592 (winstart (window-start))
593 (winstartline (org-current-line (min winstart
(1- (point-max)))))
594 lines
(new "") lengths l typenums ty fields maxfields i
602 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
604 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
605 emptystrings links dates emph narrow falign falign1 fmax f1 len c e
)
607 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
608 ;; Check if we have links or dates
610 (setq links
(re-search-forward org-bracket-link-regexp end t
))
612 (setq emph
(and org-hide-emphasis-markers
613 (re-search-forward org-emph-re end t
)))
615 (setq dates
(and org-display-custom-times
616 (re-search-forward org-ts-regexp-both end t
)))
617 ;; Make sure the link properties are right
618 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
619 ;; Make sure the date properties are right
620 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
621 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
623 ;; Check if we are narrowing any columns
625 (setq narrow
(and org-table-do-narrow
626 org-format-transports-properties-p
627 (re-search-forward "<[rl]?[0-9]+>" end t
)))
629 (setq falign
(re-search-forward "<[rl][0-9]*>" end t
))
632 (setq lines
(org-split-string
633 (buffer-substring beg end
) "\n"))
634 ;; Store the indentation of the first line
635 (if (string-match "^ *" (car lines
))
636 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
637 ;; Mark the hlines by setting the corresponding element to nil
638 ;; At the same time, we remove trailing space.
639 (setq lines
(mapcar (lambda (l)
640 (if (string-match "^ *|-" l
)
642 (if (string-match "[ \t]+$" l
)
643 (substring l
0 (match-beginning 0))
646 ;; Get the data fields by splitting the lines.
649 (org-split-string l
" *| *"))
650 (delq nil
(copy-sequence lines
))))
651 ;; How many fields in the longest line?
653 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
655 (kill-region beg end
)
656 (org-table-create org-table-default-size
)
657 (error "Empty table - created default table")))
658 ;; A list of empty strings to fill any short rows on output
659 (setq emptystrings
(make-list maxfields
""))
660 ;; Check for special formatting.
662 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
663 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
664 ;; Check if there is an explicit width specified
665 (when (or narrow falign
)
666 (setq c column fmax nil falign1 nil
)
669 (when (and (stringp e
) (string-match "^<\\([rl]\\)?\\([0-9]+\\)?>$" e
))
670 (if (match-end 1) (setq falign1
(match-string 1 e
)))
671 (if (and org-table-do-narrow
(match-end 2))
672 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
673 ;; Find fields that are wider than fmax, and shorten them
675 (loop for xx in column do
676 (when (and (stringp xx
)
677 (> (org-string-width xx
) fmax
))
678 (org-add-props xx nil
680 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
681 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
683 (error "Cannot narrow field starting with wide link \"%s\""
684 (match-string 0 xx
)))
685 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
686 (add-text-properties (- f1
2) f1
687 (list 'display org-narrow-column-arrow
)
689 ;; Get the maximum width for each column
690 (push (apply 'max
1 (mapcar 'org-string-width column
)) lengths
)
691 ;; Get the fraction of numbers, to decide about alignment of the column
693 (push (equal (downcase falign1
) "r") typenums
)
694 (setq cnt
0 frac
0.0)
695 (loop for x in column do
698 (setq frac
( / (+ (* frac cnt
)
699 (if (string-match org-table-number-regexp x
) 1 0))
700 (setq cnt
(1+ cnt
))))))
701 (push (>= frac org-table-number-fraction
) typenums
)))
702 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
704 ;; Store the alignment of this table, for later editing of single fields
705 (setq org-table-last-alignment typenums
706 org-table-last-column-widths lengths
)
708 ;; With invisible characters, `format' does not get the field width right
709 ;; So we need to make these fields wide by hand.
710 (when (or links emph
)
711 (loop for i from
0 upto
(1- maxfields
) do
712 (setq len
(nth i lengths
))
713 (loop for j from
0 upto
(1- (length fields
)) do
714 (setq c
(nthcdr i
(car (nthcdr j fields
))))
715 (if (and (stringp (car c
))
716 (text-property-any 0 (length (car c
)) 'invisible
'org-link
(car c
))
717 ; (string-match org-bracket-link-regexp (car c))
718 (< (org-string-width (car c
)) len
))
719 (setcar c
(concat (car c
) (make-string (- len
(org-string-width (car c
))) ?\
)))))))
721 ;; Compute the formats needed for output of the table
722 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
723 (while (setq l
(pop lengths
))
724 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
725 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
726 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
727 (setq rfmt
(concat rfmt
"\n")
728 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
732 (if l
(apply 'format rfmt
733 (append (pop fields
) emptystrings
))
736 (if (equal (char-before) ?
\n)
737 ;; This hack is for org-indent, to force redisplay of the
738 ;; line prefix of the first line. Apparently the redisplay
739 ;; is tied to the newline, which is, I think, a bug.
740 ;; To force this redisplay, we remove and re-insert the
741 ;; newline, so that the redisplay engine thinks it belongs
742 ;; to the changed text.
744 (backward-delete-char 1)
746 (move-marker org-table-aligned-begin-marker
(point))
748 ;; Replace the old one
749 (delete-region (point) end
)
750 (move-marker end nil
)
751 (move-marker org-table-aligned-end-marker
(point))
752 (when (and orgtbl-mode
(not (org-mode-p)))
753 (goto-char org-table-aligned-begin-marker
)
754 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
755 ;; Try to move to the old location
756 (org-goto-line winstartline
)
757 (setq winstart
(point-at-bol))
758 (org-goto-line linepos
)
759 (set-window-start (selected-window) winstart
'noforce
)
760 (org-table-goto-column colpos
)
761 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
762 (setq org-table-may-need-update nil
)
773 (defun org-table-begin (&optional table-type
)
774 "Find the beginning of the table and return its position.
775 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
777 (if (not (re-search-backward
778 (if table-type org-table-any-border-regexp
779 org-table-border-regexp
)
781 (progn (goto-char (point-min)) (point))
782 (goto-char (match-beginning 0))
783 (beginning-of-line 2)
786 (defun org-table-end (&optional table-type
)
787 "Find the end of the table and return its position.
788 With argument TABLE-TYPE, go to the end of a table.el-type table."
790 (if (not (re-search-forward
791 (if table-type org-table-any-border-regexp
792 org-table-border-regexp
)
794 (goto-char (point-max))
795 (goto-char (match-beginning 0)))
798 (defun org-table-justify-field-maybe (&optional new
)
799 "Justify the current field, text to left, number to right.
800 Optional argument NEW may specify text to replace the current field content."
802 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
803 ((org-at-table-hline-p))
805 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
807 (< (point) org-table-aligned-begin-marker
)
808 (>= (point) org-table-aligned-end-marker
)))
809 ;; This is not the same table, force a full re-align
810 (setq org-table-may-need-update t
))
811 (t ;; realign the current field, based on previous full realign
812 (let* ((pos (point)) s
813 (col (org-table-current-column))
814 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
817 (skip-chars-backward "^|\n")
818 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
820 (setq s
(match-string 1)
822 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
823 e
(not (= (match-beginning 2) (match-end 2))))
824 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
825 l
(if e
"|" (setq org-table-may-need-update t
) ""))
828 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
829 (setq n
(format f new
))
830 (setq n
(concat new
"|") org-table-may-need-update t
)))
832 (let (org-table-may-need-update)
833 (replace-match n t t
))))
834 (setq org-table-may-need-update t
))
837 (defun org-table-next-field ()
838 "Go to the next field in the current table, creating new lines as needed.
839 Before doing so, re-align the table if necessary."
841 (org-table-maybe-eval-formula)
842 (org-table-maybe-recalculate-line)
843 (if (and org-table-automatic-realign
844 org-table-may-need-update
)
846 (let ((end (org-table-end)))
847 (if (org-at-table-hline-p)
851 (re-search-forward "|" end
)
852 (if (looking-at "[ \t]*$")
853 (re-search-forward "|" end
))
854 (if (and (looking-at "-")
855 org-table-tab-jumps-over-hlines
856 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
857 (goto-char (match-beginning 1)))
860 (beginning-of-line 0)
861 (org-table-insert-row 'below
))
862 (if (looking-at " ") (forward-char 1))))
864 (org-table-insert-row 'below
)))))
866 (defun org-table-previous-field ()
867 "Go to the previous field in the table.
868 Before doing so, re-align the table if necessary."
870 (org-table-justify-field-maybe)
871 (org-table-maybe-recalculate-line)
872 (if (and org-table-automatic-realign
873 org-table-may-need-update
)
875 (if (org-at-table-hline-p)
879 (re-search-backward "|" (org-table-begin))
880 (re-search-backward "|" (org-table-begin)))
881 (error (error "Cannot move to previous table field")))
882 (while (looking-at "|\\(-\\|[ \t]*$\\)")
883 (re-search-backward "|" (org-table-begin)))
884 (if (looking-at "| ?")
885 (goto-char (match-end 0))))
887 (defun org-table-beginning-of-field (&optional n
)
888 "Move to the end of the current table field.
889 If already at or after the end, move to the end of the next table field.
890 With numeric argument N, move N-1 fields forward first."
895 (org-table-previous-field))
896 (if (not (re-search-backward "|" (point-at-bol 0) t
))
897 (error "No more table fields before the current")
898 (goto-char (match-end 0))
899 (and (looking-at " ") (forward-char 1)))
900 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
902 (defun org-table-end-of-field (&optional n
)
903 "Move to the beginning of the current table field.
904 If already at or before the beginning, move to the beginning of the
906 With numeric argument N, move N-1 fields backward first."
911 (org-table-next-field))
912 (when (re-search-forward "|" (point-at-eol 1) t
)
914 (skip-chars-backward " ")
915 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
917 (if (<= (point) pos
) (org-table-end-of-field 2))))
919 (defun org-table-next-row ()
920 "Go to the next row (same column) in the current table.
921 Before doing so, re-align the table if necessary."
923 (org-table-maybe-eval-formula)
924 (org-table-maybe-recalculate-line)
925 (if (or (looking-at "[ \t]*$")
926 (save-excursion (skip-chars-backward " \t") (bolp)))
928 (if (and org-table-automatic-realign
929 org-table-may-need-update
)
931 (let ((col (org-table-current-column)))
932 (beginning-of-line 2)
933 (if (or (not (org-at-table-p))
934 (org-at-table-hline-p))
936 (beginning-of-line 0)
937 (org-table-insert-row 'below
)))
938 (org-table-goto-column col
)
939 (skip-chars-backward "^|\n\r")
940 (if (looking-at " ") (forward-char 1)))))
942 (defun org-table-copy-down (n)
943 "Copy a field down in the current column.
944 If the field at the cursor is empty, copy into it the content of the nearest
945 non-empty field above. With argument N, use the Nth non-empty field.
946 If the current field is not empty, it is copied down to the next row, and
947 the cursor is moved with it. Therefore, repeating this command causes the
948 column to be filled row-by-row.
949 If the variable `org-table-copy-increment' is non-nil and the field is an
950 integer or a timestamp, it will be incremented while copying. In the case of
951 a timestamp, if the cursor is on the year, change the year. If it is on the
952 month or the day, change that. Point will stay on the current date field
953 in order to easily repeat the interval."
955 (let* ((colpos (org-table-current-column))
956 (col (current-column))
957 (field (org-table-get-field))
958 (non-empty (string-match "[^ \t]" field
))
959 (beg (org-table-begin))
962 (org-table-check-inside-data-field)
965 (setq txt
(org-trim field
))
967 (org-table-blank-field))
971 (while (progn (beginning-of-line 1)
972 (re-search-backward org-table-dataline-regexp
974 (org-table-goto-column colpos t
)
976 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
977 (<= (setq n
(1- n
)) 0))
978 (throw 'exit
(match-string 1))))))))
981 (if (and org-table-copy-increment
982 (not (equal orig-n
0))
983 (string-match "^[0-9]+$" txt
)
984 (< (string-to-number txt
) 100000000))
985 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
987 (org-move-to-column col
)
988 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
989 (org-timestamp-up-day)
990 (org-table-maybe-recalculate-line))
992 (org-move-to-column col
))
993 (error "No non-empty field found"))))
995 (defun org-table-check-inside-data-field ()
996 "Is point inside a table data field?
997 I.e. not on a hline or before the first or after the last column?
998 This actually throws an error, so it aborts the current command."
999 (if (or (not (org-at-table-p))
1000 (= (org-table-current-column) 0)
1001 (org-at-table-hline-p)
1002 (looking-at "[ \t]*$"))
1003 (error "Not in table data field")))
1005 (defvar org-table-clip nil
1006 "Clipboard for table regions.")
1008 (defun org-table-get (line column
)
1009 "Get the field in table line LINE, column COLUMN.
1010 If LINE is larger than the number of data lines in the table, the function
1011 returns nil. However, if COLUMN is too large, we will simply return an
1013 If LINE is nil, use the current line.
1014 If column is nil, use the current column."
1015 (setq column
(or column
(org-table-current-column)))
1017 (and (or (not line
) (org-table-goto-line line
))
1018 (org-trim (org-table-get-field column
)))))
1020 (defun org-table-put (line column value
&optional align
)
1021 "Put VALUE into line LINE, column COLUMN.
1022 When ALIGN is set, als realign the table."
1023 (setq column
(or column
(org-table-current-column)))
1024 (prog1 (save-excursion
1025 (and (or (not line
) (org-table-goto-line line
))
1026 (progn (org-table-goto-column column nil
'force
) t
)
1027 (org-table-get-field column value
)))
1028 (and align
(org-table-align))))
1030 (defun org-table-current-line ()
1031 "Return the index of the current data line."
1032 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1034 (goto-char (org-table-begin))
1035 (while (and (re-search-forward org-table-dataline-regexp end t
)
1037 (< (point-at-eol) pos
))))
1040 (defun org-table-goto-line (N)
1041 "Go to the Nth data line in the current table.
1042 Return t when the line exists, nil if it does not exist."
1043 (goto-char (org-table-begin))
1044 (let ((end (org-table-end)) (cnt 0))
1045 (while (and (re-search-forward org-table-dataline-regexp end t
)
1046 (< (setq cnt
(1+ cnt
)) line
)))
1049 (defun org-table-blank-field ()
1050 "Blank the current table field or active region."
1052 (org-table-check-inside-data-field)
1053 (if (and (interactive-p) (org-region-active-p))
1054 (let (org-table-clip)
1055 (org-table-cut-region (region-beginning) (region-end)))
1056 (skip-chars-backward "^|")
1058 (if (looking-at "|[^|\n]+")
1059 (let* ((pos (match-beginning 0))
1060 (match (match-string 0))
1061 (len (org-string-width match
)))
1062 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1063 (goto-char (+ 2 pos
))
1064 (substring match
1)))))
1066 (defun org-table-get-field (&optional n replace
)
1067 "Return the value of the field in column N of current row.
1068 N defaults to current field.
1069 If REPLACE is a string, replace field with this value. The return value
1070 is always the old value."
1071 (and n
(org-table-goto-column n
))
1072 (skip-chars-backward "^|\n")
1074 (if (looking-at "|[^|\r\n]*")
1075 (let* ((pos (match-beginning 0))
1076 (val (buffer-substring (1+ pos
) (match-end 0))))
1078 (replace-match (concat "|" replace
) t t
))
1079 (goto-char (min (point-at-eol) (+ 2 pos
)))
1081 (forward-char 1) ""))
1083 (defun org-table-field-info (arg)
1084 "Show info about the current field, and highlight any reference at point."
1086 (org-table-get-specials)
1088 (let* ((pos (point))
1089 (col (org-table-current-column))
1090 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1091 (name (car (rassoc (list (org-current-line) col
)
1092 org-table-named-field-locations
)))
1093 (eql (org-table-get-stored-formulas))
1094 (dline (org-table-current-dline))
1095 (ref (format "@%d$%d" dline col
))
1096 (ref1 (org-table-convert-refs-to-an ref
))
1097 (fequation (or (assoc name eql
) (assoc ref eql
)))
1098 (cequation (assoc (int-to-string col
) eql
))
1099 (eqn (or fequation cequation
)))
1102 (org-table-show-reference 'local
)
1104 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1106 (if cname
(concat " or $" cname
) "")
1108 (if name
(concat " or $" name
) "")
1109 ;; FIXME: formula info not correct if special table line
1111 (concat ", formula: "
1112 (org-table-formula-to-user
1114 (if (string-match "^[$@]"(car eqn
)) "" "$")
1115 (car eqn
) "=" (cdr eqn
))))
1118 (defun org-table-current-column ()
1119 "Find out which column we are in."
1121 (let ((cnt 0) (pos (point)))
1122 (beginning-of-line 1)
1123 (while (search-forward "|" pos t
)
1124 (setq cnt
(1+ cnt
)))
1127 (defun org-table-current-dline ()
1128 "Find out what table data line we are in.
1129 Only datalines count for this."
1131 (if (interactive-p) (org-table-check-inside-data-field))
1133 (let ((cnt 0) (pos (point)))
1134 (goto-char (org-table-begin))
1135 (while (<= (point) pos
)
1136 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1137 (beginning-of-line 2))
1138 (if (interactive-p) (message "This is table line %d" cnt
))
1141 (defun org-table-goto-column (n &optional on-delim force
)
1142 "Move the cursor to the Nth column in the current table line.
1143 With optional argument ON-DELIM, stop with point before the left delimiter
1145 If there are less than N fields, just go to after the last delimiter.
1146 However, when FORCE is non-nil, create new columns if necessary."
1148 (beginning-of-line 1)
1150 (while (and (> (setq n
(1- n
)) -
1)
1151 (or (search-forward "|" (point-at-eol) t
)
1153 (progn (end-of-line 1)
1154 (skip-chars-backward "^|")
1157 (when (and force
(not (looking-at ".*|")))
1158 (save-excursion (end-of-line 1) (insert " | ")))
1161 (if (looking-at " ") (forward-char 1)))))
1163 (defun org-table-insert-column ()
1164 "Insert a new column into the table."
1166 (if (not (org-at-table-p))
1167 (error "Not at a table"))
1168 (org-table-find-dataline)
1169 (let* ((col (max 1 (org-table-current-column)))
1170 (beg (org-table-begin))
1171 (end (org-table-end))
1172 ;; Current cursor position
1173 (linepos (org-current-line))
1176 (while (< (point) end
)
1177 (if (org-at-table-hline-p)
1179 (org-table-goto-column col t
)
1181 (beginning-of-line 2))
1182 (move-marker end nil
)
1183 (org-goto-line linepos
)
1184 (org-table-goto-column colpos
)
1186 (org-table-fix-formulas "$" nil
(1- col
) 1)
1187 (org-table-fix-formulas "$LR" nil
(1- col
) 1)))
1189 (defun org-table-find-dataline ()
1190 "Find a dataline in the current table, which is needed for column commands."
1191 (if (and (org-at-table-p)
1192 (not (org-at-table-hline-p)))
1194 (let ((col (current-column))
1195 (end (org-table-end)))
1196 (org-move-to-column col
)
1197 (while (and (< (point) end
)
1198 (or (not (= (current-column) col
))
1199 (org-at-table-hline-p)))
1200 (beginning-of-line 2)
1201 (org-move-to-column col
))
1202 (if (and (org-at-table-p)
1203 (not (org-at-table-hline-p)))
1206 "Please position cursor in a data line for column operations")))))
1208 (defun org-table-delete-column ()
1209 "Delete a column from the table."
1211 (if (not (org-at-table-p))
1212 (error "Not at a table"))
1213 (org-table-find-dataline)
1214 (org-table-check-inside-data-field)
1215 (let* ((col (org-table-current-column))
1216 (beg (org-table-begin))
1217 (end (org-table-end))
1218 ;; Current cursor position
1219 (linepos (org-current-line))
1222 (while (< (point) end
)
1223 (if (org-at-table-hline-p)
1225 (org-table-goto-column col t
)
1226 (and (looking-at "|[^|\n]+|")
1227 (replace-match "|")))
1228 (beginning-of-line 2))
1229 (move-marker end nil
)
1230 (org-goto-line linepos
)
1231 (org-table-goto-column colpos
)
1233 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1235 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1238 (defun org-table-move-column-right ()
1239 "Move column to the right."
1241 (org-table-move-column nil
))
1242 (defun org-table-move-column-left ()
1243 "Move column to the left."
1245 (org-table-move-column 'left
))
1247 (defun org-table-move-column (&optional left
)
1248 "Move the current column to the right. With arg LEFT, move to the left."
1250 (if (not (org-at-table-p))
1251 (error "Not at a table"))
1252 (org-table-find-dataline)
1253 (org-table-check-inside-data-field)
1254 (let* ((col (org-table-current-column))
1255 (col1 (if left
(1- col
) col
))
1256 (beg (org-table-begin))
1257 (end (org-table-end))
1258 ;; Current cursor position
1259 (linepos (org-current-line))
1260 (colpos (if left
(1- col
) (1+ col
))))
1261 (if (and left
(= col
1))
1262 (error "Cannot move column further left"))
1263 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1264 (error "Cannot move column further right"))
1266 (while (< (point) end
)
1267 (if (org-at-table-hline-p)
1269 (org-table-goto-column col1 t
)
1270 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1271 (replace-match "|\\2|\\1|")))
1272 (beginning-of-line 2))
1273 (move-marker end nil
)
1274 (org-goto-line linepos
)
1275 (org-table-goto-column colpos
)
1277 (org-table-fix-formulas
1278 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1279 (cons (number-to-string colpos
) (number-to-string col
))))
1280 (org-table-fix-formulas
1281 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1282 (cons (number-to-string colpos
) (number-to-string col
))))))
1284 (defun org-table-move-row-down ()
1285 "Move table row down."
1287 (org-table-move-row nil
))
1288 (defun org-table-move-row-up ()
1289 "Move table row up."
1291 (org-table-move-row 'up
))
1293 (defun org-table-move-row (&optional up
)
1294 "Move the current table line down. With arg UP, move it up."
1296 (let* ((col (current-column))
1298 (hline1p (save-excursion (beginning-of-line 1)
1299 (looking-at org-table-hline-regexp
)))
1300 (dline1 (org-table-current-dline))
1301 (dline2 (+ dline1
(if up -
1 1)))
1304 (beginning-of-line tonew
)
1305 (unless (org-at-table-p)
1307 (error "Cannot move row further"))
1308 (setq hline2p
(looking-at org-table-hline-regexp
))
1310 (beginning-of-line 1)
1312 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1313 (delete-region (point) (1+ (point-at-eol)))
1314 (beginning-of-line tonew
)
1316 (beginning-of-line 0)
1317 (org-move-to-column col
)
1318 (unless (or hline1p hline2p
)
1319 (org-table-fix-formulas
1320 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1321 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1323 (defun org-table-insert-row (&optional arg
)
1324 "Insert a new row above the current line into the table.
1325 With prefix ARG, insert below the current line."
1327 (if (not (org-at-table-p))
1328 (error "Not at a table"))
1329 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1330 (new (org-table-clean-line line
)))
1331 ;; Fix the first field if necessary
1332 (if (string-match "^[ \t]*| *[#$] *|" line
)
1333 (setq new
(replace-match (match-string 0 line
) t t new
)))
1334 (beginning-of-line (if arg
2 1))
1335 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1336 (beginning-of-line 0)
1337 (re-search-forward "| ?" (point-at-eol) t
)
1338 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1340 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1)))
1342 (defun org-table-insert-hline (&optional above
)
1343 "Insert a horizontal-line below the current line into the table.
1344 With prefix ABOVE, insert above the current line."
1346 (if (not (org-at-table-p))
1347 (error "Not at a table"))
1348 (when (eobp) (insert "\n") (backward-char 1))
1349 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1351 (let ((line (org-table-clean-line
1352 (buffer-substring (point-at-bol) (point-at-eol))))
1353 (col (current-column)))
1354 (while (string-match "|\\( +\\)|" line
)
1355 (setq line
(replace-match
1356 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1357 ?-
) "|") t t line
)))
1358 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1359 (beginning-of-line (if above
1 2))
1361 (beginning-of-line (if above
1 -
1))
1362 (org-move-to-column col
)
1363 (and org-table-overlay-coordinates
(org-table-align))))
1365 (defun org-table-hline-and-move (&optional same-column
)
1366 "Insert a hline and move to the row below that line."
1368 (let ((col (org-table-current-column)))
1369 (org-table-maybe-eval-formula)
1370 (org-table-maybe-recalculate-line)
1371 (org-table-insert-hline)
1373 (if (looking-at "\n[ \t]*|-")
1374 (progn (insert "\n|") (org-table-align))
1375 (org-table-next-field))
1376 (if same-column
(org-table-goto-column col
))))
1378 (defun org-table-clean-line (s)
1379 "Convert a table line S into a string with only \"|\" and space.
1380 In particular, this does handle wide and invisible characters."
1381 (if (string-match "^[ \t]*|-" s
)
1382 ;; It's a hline, just map the characters
1383 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1384 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1385 (setq s
(replace-match
1386 (concat "|" (make-string (org-string-width (match-string 1 s
))
1391 (defun org-table-kill-row ()
1392 "Delete the current row or horizontal line from the table."
1394 (if (not (org-at-table-p))
1395 (error "Not at a table"))
1396 (let ((col (current-column))
1397 (dline (org-table-current-dline)))
1398 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1399 (if (not (org-at-table-p)) (beginning-of-line 0))
1400 (org-move-to-column col
)
1401 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1404 (defun org-table-sort-lines (with-case &optional sorting-type
)
1405 "Sort table lines according to the column at point.
1407 The position of point indicates the column to be used for
1408 sorting, and the range of lines is the range between the nearest
1409 horizontal separator lines, or the entire table of no such lines
1410 exist. If point is before the first column, you will be prompted
1411 for the sorting column. If there is an active region, the mark
1412 specifies the first line and the sorting column, while point
1413 should be in the last line to be included into the sorting.
1415 The command then prompts for the sorting type which can be
1416 alphabetically, numerically, or by time (as given in a time stamp
1417 in the field). Sorting in reverse order is also possible.
1419 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1421 If SORTING-TYPE is specified when this function is called from a Lisp
1422 program, no prompting will take place. SORTING-TYPE must be a character,
1423 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1424 should be done in reverse order."
1426 (let* ((thisline (org-current-line))
1427 (thiscol (org-table-current-column))
1428 beg end bcol ecol tend tbeg column lns pos
)
1429 (when (equal thiscol
0)
1433 (read-string "Use column N for sorting: ")))
1435 (org-table-goto-column thiscol
))
1436 (org-table-check-inside-data-field)
1437 (if (org-region-active-p)
1439 (setq beg
(region-beginning) end
(region-end))
1441 (setq column
(org-table-current-column)
1444 (setq end
(point-at-bol 2)))
1445 (setq column
(org-table-current-column)
1447 tbeg
(org-table-begin)
1448 tend
(org-table-end))
1449 (if (re-search-backward org-table-hline-regexp tbeg t
)
1450 (setq beg
(point-at-bol 2))
1452 (setq beg
(point-at-bol 1)))
1454 (if (re-search-forward org-table-hline-regexp tend t
)
1455 (setq end
(point-at-bol 1))
1457 (setq end
(point-at-bol))))
1458 (setq beg
(move-marker (make-marker) beg
)
1459 end
(move-marker (make-marker) end
))
1462 (org-table-goto-column column
)
1463 (skip-chars-backward "^|")
1464 (setq bcol
(current-column))
1465 (org-table-goto-column (1+ column
))
1466 (skip-chars-backward "^|")
1467 (setq ecol
(1- (current-column)))
1468 (org-table-goto-column column
)
1469 (setq lns
(mapcar (lambda(x) (cons
1470 (org-sort-remove-invisible
1472 (org-split-string x
"[ \t]*|[ \t]*")))
1474 (org-split-string (buffer-substring beg end
) "\n")))
1475 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1476 (delete-region beg end
)
1477 (move-marker beg nil
)
1478 (move-marker end nil
)
1479 (insert (mapconcat 'cdr lns
"\n") "\n")
1480 (org-goto-line thisline
)
1481 (org-table-goto-column thiscol
)
1482 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1485 (defun org-table-cut-region (beg end
)
1486 "Copy region in table to the clipboard and blank all relevant fields.
1487 If there is no active region, use just the field at point."
1489 (if (org-region-active-p) (region-beginning) (point))
1490 (if (org-region-active-p) (region-end) (point))))
1491 (org-table-copy-region beg end
'cut
))
1493 (defun org-table-copy-region (beg end
&optional cut
)
1494 "Copy rectangular region in table to clipboard.
1495 A special clipboard is used which can only be accessed
1496 with `org-table-paste-rectangle'."
1498 (if (org-region-active-p) (region-beginning) (point))
1499 (if (org-region-active-p) (region-end) (point))
1500 current-prefix-arg
))
1501 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1503 (rpl (if cut
" " nil
)))
1505 (org-table-check-inside-data-field)
1506 (setq l01
(org-current-line)
1507 c01
(org-table-current-column))
1509 (org-table-check-inside-data-field)
1510 (setq l02
(org-current-line)
1511 c02
(org-table-current-column))
1512 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1513 c1
(min c01 c02
) c2
(max c01 c02
))
1517 (if (> l1 l2
) (throw 'exit t
))
1519 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1520 (setq cols nil ic1 c1 ic2 c2
)
1521 (while (< ic1
(1+ ic2
))
1522 (push (org-table-get-field ic1 rpl
) cols
)
1523 (setq ic1
(1+ ic1
)))
1524 (push (nreverse cols
) region
)
1525 (setq l1
(1+ l1
)))))
1526 (setq org-table-clip
(nreverse region
))
1527 (if cut
(org-table-align))
1530 (defun org-table-paste-rectangle ()
1531 "Paste a rectangular region into a table.
1532 The upper right corner ends up in the current field. All involved fields
1533 will be overwritten. If the rectangle does not fit into the present table,
1534 the table is enlarged as needed. The process ignores horizontal separator
1537 (unless (and org-table-clip
(listp org-table-clip
))
1538 (error "First cut/copy a region to paste!"))
1539 (org-table-check-inside-data-field)
1540 (let* ((clip org-table-clip
)
1541 (line (org-current-line))
1542 (col (org-table-current-column))
1543 (org-enable-table-editor t
)
1544 (org-table-automatic-realign nil
)
1546 (while (setq cols
(pop clip
))
1547 (while (org-at-table-hline-p) (beginning-of-line 2))
1548 (if (not (org-at-table-p))
1549 (progn (end-of-line 0) (org-table-next-field)))
1551 (while (setq field
(pop cols
))
1552 (org-table-goto-column c nil
'force
)
1553 (org-table-get-field nil field
)
1555 (beginning-of-line 2))
1556 (org-goto-line line
)
1557 (org-table-goto-column col
)
1560 (defun org-table-convert ()
1561 "Convert from `org-mode' table to table.el and back.
1562 Obviously, this only works within limits. When an Org-mode table is
1563 converted to table.el, all horizontal separator lines get lost, because
1564 table.el uses these as cell boundaries and has no notion of horizontal lines.
1565 A table.el table can be converted to an Org-mode table only if it does not
1566 do row or column spanning. Multiline cells will become multiple cells.
1567 Beware, Org-mode does not test if the table can be successfully converted - it
1568 blindly applies a recipe that works for simple tables."
1571 (if (org-at-table.el-p
)
1572 ;; convert to Org-mode table
1573 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1574 (end (move-marker (make-marker) (org-table-end t
))))
1575 (table-unrecognize-region beg end
)
1577 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1580 (if (org-at-table-p)
1581 ;; convert to table.el table
1582 (let ((beg (move-marker (make-marker) (org-table-begin)))
1583 (end (move-marker (make-marker) (org-table-end))))
1584 ;; first, get rid of all horizontal lines
1586 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1588 ;; insert a hline before first
1590 (org-table-insert-hline 'above
)
1591 (beginning-of-line -
1)
1592 ;; insert a hline after each line
1593 (while (progn (beginning-of-line 3) (< (point) end
))
1594 (org-table-insert-hline))
1596 (setq end
(move-marker end
(org-table-end)))
1597 ;; replace "+" at beginning and ending of hlines
1598 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1599 (replace-match "\\1+-"))
1601 (while (re-search-forward "-|[ \t]*$" end t
)
1602 (replace-match "-+"))
1605 (defun org-table-wrap-region (arg)
1606 "Wrap several fields in a column like a paragraph.
1607 This is useful if you'd like to spread the contents of a field over several
1608 lines, in order to keep the table compact.
1610 If there is an active region, and both point and mark are in the same column,
1611 the text in the column is wrapped to minimum width for the given number of
1612 lines. Generally, this makes the table more compact. A prefix ARG may be
1613 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1614 formats the selected text to two lines. If the region was longer than two
1615 lines, the remaining lines remain empty. A negative prefix argument reduces
1616 the current number of lines by that amount. The wrapped text is pasted back
1617 into the table. If you formatted it to more lines than it was before, fields
1618 further down in the table get overwritten - so you might need to make space in
1621 If there is no region, the current field is split at the cursor position and
1622 the text fragment to the right of the cursor is prepended to the field one
1625 If there is no region, but you specify a prefix ARG, the current field gets
1626 blank, and the content is appended to the field above."
1628 (org-table-check-inside-data-field)
1629 (if (org-region-active-p)
1630 ;; There is a region: fill as a paragraph
1631 (let* ((beg (region-beginning))
1632 (cline (save-excursion (goto-char beg
) (org-current-line)))
1633 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1635 (org-table-cut-region (region-beginning) (region-end))
1636 (if (> (length (car org-table-clip
)) 1)
1637 (error "Region must be limited to single column"))
1638 (setq nlines
(if arg
1640 (+ (length org-table-clip
) arg
)
1642 (length org-table-clip
)))
1643 (setq org-table-clip
1644 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1646 (org-goto-line cline
)
1647 (org-table-goto-column ccol
)
1648 (org-table-paste-rectangle))
1649 ;; No region, split the current field at point
1650 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1651 (skip-chars-forward "^\r\n|"))
1653 ;; combine with field above
1654 (let ((s (org-table-blank-field))
1655 (col (org-table-current-column)))
1656 (beginning-of-line 0)
1657 (while (org-at-table-hline-p) (beginning-of-line 0))
1658 (org-table-goto-column col
)
1659 (skip-chars-forward "^|")
1660 (skip-chars-backward " ")
1661 (insert " " (org-trim s
))
1664 (if (looking-at "\\([^|]+\\)+|")
1665 (let ((s (match-string 1)))
1666 (replace-match " |")
1667 (goto-char (match-beginning 0))
1668 (org-table-next-row)
1669 (insert (org-trim s
) " ")
1671 (org-table-next-row)))))
1673 (defvar org-field-marker nil
)
1675 (defun org-table-edit-field (arg)
1676 "Edit table field in a different window.
1677 This is mainly useful for fields that contain hidden parts.
1678 When called with a \\[universal-argument] prefix, just make the full field visible so that
1679 it can be edited in place."
1682 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1683 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1684 (remove-text-properties b e
'(org-cwidth t invisible t
1685 display t intangible t
))
1686 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1687 (font-lock-fontify-block)))
1688 (let ((pos (move-marker (make-marker) (point)))
1689 (field (org-table-get-field))
1690 (cw (current-window-configuration))
1692 (org-switch-to-buffer-other-window "*Org tmp*")
1694 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
1695 (let ((org-inhibit-startup t
)) (org-mode))
1696 (goto-char (setq p
(point-max)))
1697 (insert (org-trim field
))
1698 (remove-text-properties p
(point-max)
1699 '(invisible t org-cwidth t display t
1702 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1703 (org-set-local 'org-window-configuration cw
)
1704 (org-set-local 'org-field-marker pos
)
1705 (message "Edit and finish with C-c C-c"))))
1707 (defun org-table-finish-edit-field ()
1708 "Finish editing a table data field.
1709 Remove all newline characters, insert the result into the table, realign
1710 the table and kill the editing buffer."
1711 (let ((pos org-field-marker
)
1712 (cw org-window-configuration
)
1713 (cb (current-buffer))
1715 (goto-char (point-min))
1716 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1717 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1718 (replace-match " "))
1719 (setq text
(org-trim (buffer-string)))
1720 (set-window-configuration cw
)
1722 (select-window (get-buffer-window (marker-buffer pos
)))
1724 (move-marker pos nil
)
1725 (org-table-check-inside-data-field)
1726 (org-table-get-field nil text
)
1728 (message "New field value inserted")))
1747 (defvar org-timecnt
) ; dynamically scoped parameter
1749 (defun org-table-sum (&optional beg end nlast
)
1750 "Sum numbers in region of current table column.
1751 The result will be displayed in the echo area, and will be available
1752 as kill to be inserted with \\[yank].
1754 If there is an active region, it is interpreted as a rectangle and all
1755 numbers in that rectangle will be summed. If there is no active
1756 region and point is located in a table column, sum all numbers in that
1759 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1760 numbers are assumed to be times as well (in decimal hours) and the
1761 numbers are added as such.
1763 If NLAST is a number, only the NLAST fields will actually be summed."
1766 (let (col (org-timecnt 0) diff h m s org-table-clip
)
1768 ((and beg end
)) ; beg and end given explicitly
1769 ((org-region-active-p)
1770 (setq beg
(region-beginning) end
(region-end)))
1772 (setq col
(org-table-current-column))
1773 (goto-char (org-table-begin))
1774 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
1775 (error "No table data"))
1776 (org-table-goto-column col
)
1778 (goto-char (org-table-end))
1779 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
1780 (error "No table data"))
1781 (org-table-goto-column col
)
1782 (setq end
(point))))
1783 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
1784 (items1 (cond ((not nlast
) items
)
1785 ((>= nlast
(length items
)) items
)
1786 (t (setq items
(reverse items
))
1787 (setcdr (nthcdr (1- nlast
) items
) nil
)
1789 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
1791 (res (apply '+ numbers
))
1792 (sres (if (= org-timecnt
0)
1793 (number-to-string res
)
1794 (setq diff
(* 3600 res
)
1795 h
(floor (/ diff
3600)) diff
(mod diff
3600)
1796 m
(floor (/ diff
60)) diff
(mod diff
60)
1798 (format "%d:%02d:%02d" h m s
))))
1802 (substitute-command-keys
1803 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
1804 (length numbers
) sres
))))
1807 (defun org-table-get-number-for-summing (s)
1809 (if (string-match "^ *|? *" s
)
1810 (setq s
(replace-match "" nil nil s
)))
1811 (if (string-match " *|? *$" s
)
1812 (setq s
(replace-match "" nil nil s
)))
1813 (setq n
(string-to-number s
))
1815 ((and (string-match "0" s
)
1816 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
1817 ((string-match "\\`[ \t]+\\'" s
) nil
)
1818 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
1819 (let ((h (string-to-number (or (match-string 1 s
) "0")))
1820 (m (string-to-number (or (match-string 2 s
) "0")))
1821 (s (string-to-number (or (match-string 4 s
) "0"))))
1822 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
1823 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
1827 (defun org-table-current-field-formula (&optional key noerror
)
1828 "Return the formula active for the current field.
1829 Assumes that specials are in place.
1830 If KEY is given, return the key to this formula.
1831 Otherwise return the formula preceeded with \"=\" or \":=\"."
1832 (let* ((name (car (rassoc (list (org-current-line)
1833 (org-table-current-column))
1834 org-table-named-field-locations
)))
1835 (col (org-table-current-column))
1836 (scol (int-to-string col
))
1837 (ref (format "@%d$%d" (org-table-current-dline) col
))
1838 (stored-list (org-table-get-stored-formulas noerror
))
1839 (ass (or (assoc name stored-list
)
1840 (assoc ref stored-list
)
1841 (assoc scol stored-list
))))
1844 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
1847 (defun org-table-get-formula (&optional equation named
)
1848 "Read a formula from the minibuffer, offer stored formula as default.
1849 When NAMED is non-nil, look for a named equation."
1850 (let* ((stored-list (org-table-get-stored-formulas))
1851 (name (car (rassoc (list (org-current-line)
1852 (org-table-current-column))
1853 org-table-named-field-locations
)))
1854 (ref (format "@%d$%d" (org-table-current-dline)
1855 (org-table-current-column)))
1856 (refass (assoc ref stored-list
))
1857 (nameass (assoc name stored-list
))
1859 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
1862 (int-to-string (org-table-current-column))))
1863 (dummy (and (or nameass refass
) (not named
)
1864 (not (y-or-n-p "Replace existing field formula with column formula? " ))
1866 (name (or name ref
))
1867 (org-table-may-need-update nil
)
1868 (stored (cdr (assoc scol stored-list
)))
1870 ((and stored equation
(string-match "^ *=? *$" equation
))
1874 (t (org-table-formula-from-user
1876 (org-table-formula-to-user
1877 (format "%s formula %s%s="
1878 (if named
"Field" "Column")
1879 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
1881 (if stored
(org-table-formula-to-user stored
) "")
1882 'org-table-formula-history
1885 (when (not (string-match "\\S-" eq
))
1887 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
1888 (org-table-store-formulas stored-list
)
1889 (error "Formula removed"))
1890 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
1891 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
1892 (if (and name
(not named
))
1893 ;; We set the column equation, delete the named one.
1894 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
1897 (setcdr (assoc scol stored-list
) eq
)
1898 (setq stored-list
(cons (cons scol eq
) stored-list
)))
1899 (if (or mustsave
(not (equal stored eq
)))
1900 (org-table-store-formulas stored-list
))
1903 (defun org-table-store-formulas (alist)
1904 "Store the list of formulas below the current table."
1905 (setq alist
(sort alist
'org-table-formula-less-p
))
1907 (goto-char (org-table-end))
1908 (if (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM:\\(.*\n?\\)")
1910 ;; don't overwrite TBLFM, we might use text properties to store stuff
1911 (goto-char (match-beginning 2))
1912 (delete-region (match-beginning 2) (match-end 0)))
1913 (org-indent-line-function)
1914 (insert "#+TBLFM:"))
1916 (mapconcat (lambda (x)
1918 (if (equal (string-to-char (car x
)) ?
@) "" "$")
1919 (car x
) "=" (cdr x
)))
1923 (defsubst org-table-formula-make-cmp-string
(a)
1924 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a
)
1926 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a
))) "")
1927 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a
))) "")
1928 (if (match-end 5) (concat "@@" (match-string 5 a
))))))
1930 (defun org-table-formula-less-p (a b
)
1931 "Compare two formulas for sorting."
1932 (let ((as (org-table-formula-make-cmp-string (car a
)))
1933 (bs (org-table-formula-make-cmp-string (car b
))))
1934 (and as bs
(string< as bs
))))
1936 (defun org-table-get-stored-formulas (&optional noerror
)
1937 "Return an alist with the stored formulas directly after current table."
1939 (let (scol eq eq-alist strings string seen
)
1941 (goto-char (org-table-end))
1942 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
1943 (setq strings
(org-split-string (match-string 2) " *:: *"))
1944 (while (setq string
(pop strings
))
1945 (when (string-match "\\`\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
1946 (setq scol
(if (match-end 2)
1947 (match-string 2 string
)
1948 (match-string 1 string
))
1949 eq
(match-string 3 string
)
1950 eq-alist
(cons (cons scol eq
) eq-alist
))
1951 (if (member scol seen
)
1954 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
1957 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
1958 (push scol seen
))))))
1959 (nreverse eq-alist
)))
1961 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
1962 "Modify the equations after the table structure has been edited.
1963 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
1964 For all numbers larger than LIMIT, shift them by DELTA."
1966 (goto-char (org-table-end))
1967 (when (looking-at "[ \t]*#\\+TBLFM:")
1968 (let ((re (concat key
"\\([0-9]+\\)"))
1971 (if (or (equal key
"$") (equal key
"$LR"))
1972 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
1973 (regexp-quote key
) remove
)
1974 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
1977 (while (re-search-forward re2
(point-at-eol) t
)
1978 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
1979 (replace-match ""))))
1980 (while (re-search-forward re
(point-at-eol) t
)
1981 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
1982 (setq s
(match-string 1) n
(string-to-number s
))
1984 ((setq a
(assoc s replace
))
1985 (replace-match (concat key
(cdr a
)) t t
))
1986 ((and limit
(> n limit
))
1987 (replace-match (concat key
(int-to-string (+ n delta
)))
1990 (defun org-table-get-specials ()
1991 "Get the column names and local parameters for this table."
1993 (let ((beg (org-table-begin)) (end (org-table-end))
1994 names name fields fields1 field cnt
1995 c v l line col types dlines hlines last-dline
)
1996 (setq org-table-column-names nil
1997 org-table-local-parameters nil
1998 org-table-named-field-locations nil
1999 org-table-current-begin-line nil
2000 org-table-current-begin-pos nil
2001 org-table-current-line-types nil
)
2003 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2004 (setq names
(org-split-string (match-string 1) " *| *")
2006 (while (setq name
(pop names
))
2008 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name
)
2009 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2010 (setq org-table-column-names
(nreverse org-table-column-names
))
2011 (setq org-table-column-name-regexp
2012 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2014 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2015 (setq fields
(org-split-string (match-string 1) " *| *"))
2016 (while (setq field
(pop fields
))
2017 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2018 (push (cons (match-string 1 field
) (match-string 2 field
))
2019 org-table-local-parameters
))))
2021 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2022 (setq c
(match-string 1)
2023 fields
(org-split-string (match-string 2) " *| *"))
2025 (beginning-of-line (if (equal c
"_") 2 0))
2026 (setq line
(org-current-line) col
1)
2027 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2028 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2029 (while (and fields1
(setq field
(pop fields
)))
2030 (setq v
(pop fields1
) col
(1+ col
))
2031 (when (and (stringp field
) (stringp v
)
2032 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field
))
2033 (push (cons field v
) org-table-local-parameters
)
2034 (push (list field line col
) org-table-named-field-locations
))))
2035 ;; Analyse the line types
2037 (setq org-table-current-begin-line
(org-current-line)
2038 org-table-current-begin-pos
(point)
2039 l org-table-current-begin-line
)
2040 (while (looking-at "[ \t]*|\\(-\\)?")
2041 (push (if (match-end 1) 'hline
'dline
) types
)
2042 (if (match-end 1) (push l hlines
) (push l dlines
))
2043 (beginning-of-line 2)
2045 (push 'hline types
) ;; add an imaginary extra hline to the end
2046 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2047 last-dline
(car dlines
)
2048 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2049 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2050 (org-goto-line last-dline
)
2051 (let* ((l last-dline
)
2052 (fields (org-split-string
2053 (buffer-substring (point-at-bol) (point-at-eol))
2055 (nfields (length fields
))
2057 (loop for i from
1 to nfields do
2058 (push (list (format "LR%d" i
) l i
) al
)
2059 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2060 (setq org-table-named-field-locations
2061 (append org-table-named-field-locations al
))
2062 (setq org-table-local-parameters
2063 (append org-table-local-parameters al2
))))))
2066 (defun org-table-maybe-eval-formula ()
2067 "Check if the current field starts with \"=\" or \":=\".
2068 If yes, store the formula and apply it."
2069 ;; We already know we are in a table. Get field will only return a formula
2070 ;; when appropriate. It might return a separator line, but no problem.
2071 (when org-table-formula-evaluate-inline
2072 (let* ((field (org-trim (or (org-table-get-field) "")))
2074 (when (string-match "^:?=\\(.*\\)" field
)
2075 (setq named
(equal (string-to-char field
) ?
:)
2076 eq
(match-string 1 field
))
2077 (if (or (fboundp 'calc-eval
)
2078 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2079 (org-table-eval-formula (if named
'(4) nil
)
2080 (org-table-formula-from-user eq
))
2081 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2083 (defvar org-recalc-commands nil
2084 "List of commands triggering the recalculation of a line.
2085 Will be filled automatically during use.")
2087 (defvar org-recalc-marks
2088 '((" " .
"Unmarked: no special line, no automatic recalculation")
2089 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2090 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2091 ("!" .
"Column name definition line. Reference in formula as $name.")
2092 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2093 ("_" .
"Names for values in row below this one.")
2094 ("^" .
"Names for values in row above this one.")))
2096 (defun org-table-rotate-recalc-marks (&optional newchar
)
2097 "Rotate the recalculation mark in the first column.
2098 If in any row, the first field is not consistent with a mark,
2099 insert a new column for the markers.
2100 When there is an active region, change all the lines in the region,
2101 after prompting for the marking character.
2102 After each change, a message will be displayed indicating the meaning
2105 (unless (org-at-table-p) (error "Not at a table"))
2106 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2107 (beg (org-table-begin))
2108 (end (org-table-end))
2109 (l (org-current-line))
2110 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2111 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2115 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2116 (col (org-table-current-column))
2117 (forcenew (car (assoc newchar org-recalc-marks
)))
2120 (message "Change region to what mark? Type # * ! $ or SPC: ")
2121 (setq newchar
(char-to-string (read-char-exclusive))
2122 forcenew
(car (assoc newchar org-recalc-marks
))))
2123 (if (and newchar
(not forcenew
))
2124 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2126 (if l1
(org-goto-line l1
))
2128 (beginning-of-line 1)
2129 (unless (looking-at org-table-dataline-regexp
)
2130 (error "Not at a table data line")))
2132 (org-table-goto-column 1)
2133 (org-table-insert-column)
2134 (org-table-goto-column (1+ col
)))
2135 (setq epos
(point-at-eol))
2137 (beginning-of-line 1)
2138 (org-table-get-field
2139 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2141 (setq new
(or forcenew
2142 (cadr (member (match-string 1) marks
))))
2148 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2149 (and (looking-at org-table-dataline-regexp
)
2150 (org-table-get-field 1 (concat " " new
" "))))
2151 (org-goto-line l1
)))
2152 (if (not (= epos
(point-at-eol))) (org-table-align))
2154 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks
))))))
2156 (defun org-table-maybe-recalculate-line ()
2157 "Recompute the current line if marked for it, and if we haven't just done it."
2159 (and org-table-allow-automatic-line-recalculation
2160 (not (and (memq last-command org-recalc-commands
)
2161 (equal org-last-recalc-line
(org-current-line))))
2162 (save-excursion (beginning-of-line 1)
2163 (looking-at org-table-auto-recalculate-regexp
))
2164 (org-table-recalculate) t
))
2167 (defsubst org-set-calc-mode
(var &optional value
)
2169 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2170 ("R" calc-angle-mode rad
)
2171 ("F" calc-prefer-frac t
)
2172 ("S" calc-symbolic-mode t
)))
2173 value
(nth 2 var
) var
(nth 1 var
)))
2174 (if (memq var modes
)
2175 (setcar (cdr (memq var modes
)) value
)
2176 (cons var
(cons value modes
)))
2179 (defun org-table-eval-formula (&optional arg equation
2180 suppress-align suppress-const
2181 suppress-store suppress-analysis
)
2182 "Replace the table field value at the cursor by the result of a calculation.
2184 This function makes use of Dave Gillespie's Calc package, in my view the
2185 most exciting program ever written for GNU Emacs. So you need to have Calc
2186 installed in order to use this function.
2188 In a table, this command replaces the value in the current field with the
2189 result of a formula. It also installs the formula as the \"current\" column
2190 formula, by storing it in a special line below the table. When called
2191 with a `C-u' prefix, the current field must be a named field, and the
2192 formula is installed as valid in only this specific field.
2194 When called with two `C-u' prefixes, insert the active equation
2195 for the field back into the current field, so that it can be
2196 edited there. This is useful in order to use \\[org-table-show-reference]
2197 to check the referenced fields.
2199 When called, the command first prompts for a formula, which is read in
2200 the minibuffer. Previously entered formulas are available through the
2201 history list, and the last used formula is offered as a default.
2202 These stored formulas are adapted correctly when moving, inserting, or
2203 deleting columns with the corresponding commands.
2205 The formula can be any algebraic expression understood by the Calc package.
2206 For details, see the Org-mode manual.
2208 This function can also be called from Lisp programs and offers
2209 additional arguments: EQUATION can be the formula to apply. If this
2210 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2211 used to speed-up recursive calls by by-passing unnecessary aligns.
2212 SUPPRESS-CONST suppresses the interpretation of constants in the
2213 formula, assuming that this has been done already outside the function.
2214 SUPPRESS-STORE means the formula should not be stored, either because
2215 it is already stored, or because it is a modified equation that should
2216 not overwrite the stored one."
2218 (org-table-check-inside-data-field)
2219 (or suppress-analysis
(org-table-get-specials))
2220 (if (equal arg
'(16))
2221 (let ((eq (org-table-current-field-formula)))
2222 (or eq
(error "No equation active for current field"))
2223 (org-table-get-field nil eq
)
2225 (setq org-table-may-need-update t
))
2227 (ndown (if (integerp arg
) arg
1))
2228 (org-table-automatic-realign nil
)
2229 (case-fold-search nil
)
2231 (formula (if (and equation suppress-store
)
2233 (org-table-get-formula equation
(equal arg
'(4)))))
2234 (n0 (org-table-current-column))
2235 (modes (copy-sequence org-calc-default-modes
))
2236 (numbers nil
) ; was a variable, now fixed default
2238 n form form0 bw fmt x ev orig c lispp literal
)
2239 ;; Parse the format string. Since we have a lot of modes, this is
2240 ;; a lot of work. However, I think calc still uses most of the time.
2241 (if (string-match ";" formula
)
2242 (let ((tmp (org-split-string formula
";")))
2243 (setq formula
(car tmp
)
2244 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2246 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2247 (setq c
(string-to-char (match-string 1 fmt
))
2248 n
(string-to-number (match-string 2 fmt
)))
2250 (setq modes
(org-set-calc-mode 'calc-internal-prec n
))
2251 (setq modes
(org-set-calc-mode
2253 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2254 (?s . sci
) (?e . eng
))))
2256 (setq fmt
(replace-match "" t t fmt
)))
2257 (if (string-match "[NT]" fmt
)
2258 (setq numbers
(equal (match-string 0 fmt
) "N")
2259 fmt
(replace-match "" t t fmt
)))
2260 (if (string-match "L" fmt
)
2262 fmt
(replace-match "" t t fmt
)))
2263 (if (string-match "E" fmt
)
2265 fmt
(replace-match "" t t fmt
)))
2266 (while (string-match "[DRFS]" fmt
)
2267 (setq modes
(org-set-calc-mode (match-string 0 fmt
)))
2268 (setq fmt
(replace-match "" t t fmt
)))
2269 (unless (string-match "\\S-" fmt
)
2271 (if (and (not suppress-const
) org-table-formula-use-constants
)
2272 (setq formula
(org-table-formula-substitute-names formula
)))
2273 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2275 (setq fields
(org-split-string
2277 (buffer-substring (point-at-bol) (point-at-eol)))
2280 (setq fields
(mapcar
2281 (lambda (x) (number-to-string (string-to-number x
)))
2283 (setq ndown
(1- ndown
))
2284 (setq form
(copy-sequence formula
)
2285 lispp
(and (> (length form
) 2)(equal (substring form
0 2) "'(")))
2286 (if (and lispp literal
) (setq lispp
'literal
))
2288 ;; Insert row and column number of formula result field
2289 (while (string-match "[@$]#" form
)
2294 (if (equal (substring form
(match-beginning 0)
2295 (1+ (match-beginning 0)))
2297 (org-table-current-dline)
2298 (org-table-current-column))))
2301 ;; Check for old vertical references
2302 (setq form
(org-table-rewrite-old-row-references form
))
2303 ;; Insert remote references
2304 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2308 (org-table-make-reference
2309 (org-table-get-remote-range
2310 (match-string 1 form
) (match-string 2 form
))
2311 keep-empty numbers lispp
))
2313 ;; Insert complex ranges
2314 (while (and (string-match org-table-range-regexp form
)
2315 (> (length (match-string 0 form
)) 1))
2319 (org-table-make-reference
2320 (org-table-get-range (match-string 0 form
) nil n0
)
2321 keep-empty numbers lispp
))
2323 ;; Insert simple ranges
2324 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2328 (org-table-make-reference
2330 fields
(string-to-number (match-string 1 form
))
2331 (string-to-number (match-string 2 form
)))
2332 keep-empty numbers lispp
))
2335 ;; Insert the references to fields in same row
2336 (while (string-match "\\$\\([0-9]+\\)" form
)
2337 (setq n
(string-to-number (match-string 1 form
))
2338 x
(nth (1- (if (= n
0) n0 n
)) fields
))
2339 (unless x
(error "Invalid field specifier \"%s\""
2340 (match-string 0 form
)))
2341 (setq form
(replace-match
2343 (org-table-make-reference x nil numbers lispp
))
2347 (setq ev
(condition-case nil
2348 (eval (eval (read form
)))
2350 ev
(if (numberp ev
) (number-to-string ev
) ev
))
2351 (or (fboundp 'calc-eval
)
2352 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2353 (setq ev
(calc-eval (cons form modes
)
2354 (if numbers
'num
))))
2356 (when org-table-formula-debug
2357 (with-output-to-temp-buffer "*Substitution History*"
2358 (princ (format "Substitution history of formula
2362 $1-> %s\n" orig formula form0 form
))
2364 (princ (format " %s^\nError: %s"
2365 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2366 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2368 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2369 (setq bw
(get-buffer-window "*Substitution History*"))
2370 (org-fit-window-to-buffer bw
)
2371 (unless (and (interactive-p) (not ndown
))
2372 (unless (let (inhibit-redisplay)
2373 (y-or-n-p "Debugging Formula. Continue to next? "))
2378 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2379 (org-table-justify-field-maybe
2380 (if fmt
(format fmt
(string-to-number ev
)) ev
))
2381 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2382 (call-interactively 'org-return
)
2384 (and down
(org-table-maybe-recalculate-line))
2385 (or suppress-align
(and org-table-may-need-update
2386 (org-table-align))))))
2388 (defun org-table-put-field-property (prop value
)
2390 (put-text-property (progn (skip-chars-backward "^|") (point))
2391 (progn (skip-chars-forward "^|") (point))
2394 (defun org-table-get-range (desc &optional tbeg col highlight
)
2395 "Get a calc vector from a column, according to descriptor DESC.
2396 Optional arguments TBEG and COL can give the beginning of the table and
2397 the current column, to avoid unnecessary parsing.
2398 HIGHLIGHT means just highlight the range."
2399 (if (not (equal (string-to-char desc
) ?
@))
2400 (setq desc
(concat "@" desc
)))
2402 (or tbeg
(setq tbeg
(org-table-begin)))
2403 (or col
(setq col
(org-table-current-column)))
2404 (let ((thisline (org-current-line))
2405 beg end c1 c2 r1 r2 rangep tmp
)
2406 (unless (string-match org-table-range-regexp desc
)
2407 (error "Invalid table range specifier `%s'" desc
))
2408 (setq rangep
(match-end 3)
2409 r1
(and (match-end 1) (match-string 1 desc
))
2410 r2
(and (match-end 4) (match-string 4 desc
))
2411 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2412 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2414 (and c1
(setq c1
(+ (string-to-number c1
)
2415 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2416 (and c2
(setq c2
(+ (string-to-number c2
)
2417 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2418 (if (equal r1
"") (setq r1 nil
))
2419 (if (equal r2
"") (setq r2 nil
))
2420 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2421 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2422 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2423 (if (not r1
) (setq r1 thisline
))
2424 (if (not r2
) (setq r2 thisline
))
2425 (if (not c1
) (setq c1 col
))
2426 (if (not c2
) (setq c2 col
))
2427 (if (or (not rangep
) (and (= r1 r2
) (= c1 c2
)))
2431 (while (not (looking-at org-table-dataline-regexp
))
2432 (beginning-of-line 2))
2433 (prog1 (org-trim (org-table-get-field c1
))
2434 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2435 ;; A range, return a vector
2436 ;; First sort the numbers to get a regular ractangle
2437 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2438 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2440 (while (not (looking-at org-table-dataline-regexp
))
2441 (beginning-of-line 2))
2442 (org-table-goto-column c1
)
2445 (while (not (looking-at org-table-dataline-regexp
))
2446 (beginning-of-line 0))
2447 (org-table-goto-column c2
)
2450 (org-table-highlight-rectangle
2451 beg
(progn (skip-chars-forward "^|\n") (point))))
2452 ;; return string representation of calc vector
2454 (apply 'append
(org-table-copy-region beg end
)))))))
2456 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2457 "Analyze descriptor DESC and retrieve the corresponding line number.
2458 The cursor is currently in line CLINE, the table begins in line BLINE,
2459 and TABLE is a vector with line types."
2460 (if (string-match "^[0-9]+$" desc
)
2461 (aref org-table-dlines
(string-to-number desc
))
2462 (setq cline
(or cline
(org-current-line))
2463 bline
(or bline org-table-current-begin-line
)
2464 table
(or table org-table-current-line-types
))
2466 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2468 (and (not (match-end 3)) (not (match-end 6)))
2469 (and (match-end 3) (match-end 6) (not (match-end 5))))
2470 (error "invalid row descriptor `%s'" desc
))
2471 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2472 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2473 (odir (and (match-end 5) (match-string 5 desc
)))
2474 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2476 (rel (and (match-end 6)
2477 (or (and (match-end 1) (not (match-end 3)))
2479 (if (and hn
(not hdir
))
2482 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2483 (if (and (not hn
) on
(not odir
))
2484 (error "should never happen");;(aref org-table-dlines on)
2485 (if (and hn
(> hn
0))
2486 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2487 nil hn cline desc
)))
2489 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2490 rel on cline desc
)))
2493 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2494 "FIXME: Needs more documentation."
2495 (let ((l (length table
)))
2497 (while (and (setq i
(+ i
(if backwards -
1 1)))
2499 (not (eq (aref table i
) type
))
2500 (if (and relative
(eq (aref table i
) 'hline
))
2502 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2503 ((eq org-table-relative-ref-may-cross-hline
'error
)
2504 (error "Row descriptor %s used in line %d crosses hline" desc cline
))
2505 (t (setq i
(- i
(if backwards -
1 1))
2510 (if (or (< i
0) (>= i l
))
2511 (error "Row descriptor %s used in line %d leads outside table"
2515 (defun org-table-rewrite-old-row-references (s)
2516 (if (string-match "&[-+0-9I]" s
)
2517 (error "Formula contains old &row reference, please rewrite using @-syntax")
2520 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2521 "Convert list ELEMENTS to something appropriate to insert into formula.
2522 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2523 NUMBERS indicates that everything should be converted to numbers.
2524 LISPP means to return something appropriate for a Lisp list."
2525 (if (stringp elements
) ; just a single val
2527 (if (eq lispp
'literal
)
2529 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2530 (if (equal elements
"") (setq elements
"0"))
2531 (if numbers
(setq elements
(number-to-string (string-to-number elements
))))
2532 (concat "(" elements
")"))
2536 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2538 (setq elements
(or elements
'("0")))
2542 (if (eq lispp
'literal
)
2544 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2546 (concat "[" (mapconcat
2548 (if numbers
(number-to-string (string-to-number x
)) x
))
2552 (defun org-table-recalculate (&optional all noalign
)
2553 "Recalculate the current table line by applying all stored formulas.
2554 With prefix arg ALL, do this for all lines in the table.
2555 With the prefix argument ALL is `(16)' (a double `C-c C-u' prefix), or if
2556 it is the symbol `iterate', recompute the table until it no longer changes.
2557 If NOALIGN is not nil, do not re-align the table after the computations
2558 are done. This is typically used internally to save time, if it is
2559 known that the table will be realigned a little later anyway."
2561 (or (memq this-command org-recalc-commands
)
2562 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2563 (unless (org-at-table-p) (error "Not at a table"))
2564 (if (or (eq all
'iterate
) (equal all
'(16)))
2566 (org-table-get-specials)
2567 (let* ((eqlist (sort (org-table-get-stored-formulas)
2568 (lambda (a b
) (string< (car a
) (car b
)))))
2569 (inhibit-redisplay (not debug-on-error
))
2570 (line-re org-table-dataline-regexp
)
2571 (thisline (org-current-line))
2572 (thiscol (org-table-current-column))
2573 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name
)
2574 ;; Insert constants in all formulas
2577 (setcdr x
(org-table-formula-substitute-names (cdr x
)))
2580 ;; Split the equation list
2581 (while (setq eq
(pop eqlist
))
2582 (if (<= (string-to-char (car eq
)) ?
9)
2585 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
2588 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
2589 (goto-char (setq beg
(org-table-begin)))
2590 (if (re-search-forward org-table-calculate-mark-regexp end t
)
2591 ;; This is a table with marked lines, compute selected lines
2592 (setq line-re org-table-recalculate-regexp
)
2593 ;; Move forward to the first non-header line
2594 (if (and (re-search-forward org-table-dataline-regexp end t
)
2595 (re-search-forward org-table-hline-regexp end t
)
2596 (re-search-forward org-table-dataline-regexp end t
))
2597 (setq beg
(match-beginning 0))
2598 nil
))) ;; just leave beg where it is
2599 (setq beg
(point-at-bol)
2600 end
(move-marker (make-marker) (1+ (point-at-eol)))))
2602 (and all
(message "Re-applying formulas to full table..."))
2604 ;; First find the named fields, and mark them untouchable
2605 (remove-text-properties beg end
'(org-untouchable t
))
2606 (while (setq eq
(pop eqlname
))
2608 a
(assoc name org-table-named-field-locations
))
2610 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
2613 (aref org-table-dlines
2614 (string-to-number (match-string 1 name
)))
2615 (error (error "Invalid row number in %s"
2617 (string-to-number (match-string 2 name
)))))
2618 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
2619 (message "Re-applying formula to field: %s" name
)
2620 (org-goto-line (nth 1 a
))
2621 (org-table-goto-column (nth 2 a
))
2622 (push (append a
(list (cdr eq
))) eqlname1
)
2623 (org-table-put-field-property :org-untouchable t
)))
2625 ;; Now evaluate the column formulas, but skip fields covered by
2628 (while (re-search-forward line-re end t
)
2629 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2630 ;; Unprotected line, recalculate
2631 (and all
(message "Re-applying formulas to full table...(line %d)"
2632 (setq cnt
(1+ cnt
))))
2633 (setq org-last-recalc-line
(org-current-line))
2635 (while (setq entry
(pop eql
))
2636 (org-goto-line org-last-recalc-line
)
2637 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
2638 (unless (get-text-property (point) :org-untouchable
)
2639 (org-table-eval-formula nil
(cdr entry
)
2640 'noalign
'nocst
'nostore
'noanalysis
)))))
2642 ;; Now evaluate the field formulas
2643 (while (setq eq
(pop eqlname1
))
2644 (message "Re-applying formula to field: %s" (car eq
))
2645 (org-goto-line (nth 1 eq
))
2646 (org-table-goto-column (nth 2 eq
))
2647 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
2648 'nostore
'noanalysis
))
2650 (org-goto-line thisline
)
2651 (org-table-goto-column thiscol
)
2652 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
2653 (or noalign
(and org-table-may-need-update
(org-table-align))
2654 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
2656 ;; back to initial position
2657 (message "Re-applying formulas...done")
2658 (org-goto-line thisline
)
2659 (org-table-goto-column thiscol
)
2660 (or noalign
(and org-table-may-need-update
(org-table-align))
2661 (and all
(message "Re-applying formulas...done"))))))
2663 (defun org-table-iterate (&optional arg
)
2664 "Recalculate the table until it does not change anymore."
2666 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
2668 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2673 (org-table-recalculate 'all
)
2674 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
2675 (if (not (string= lasttbl thistbl
))
2676 (setq lasttbl thistbl
)
2678 (message "Convergence after %d iterations" i
)
2679 (message "Table was already stable"))
2681 (error "No convergence after %d iterations" i
))))
2683 (defun org-table-formula-substitute-names (f)
2684 "Replace $const with values in string F."
2685 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
2686 ;; First, check for column names
2687 (while (setq start
(string-match org-table-column-name-regexp f start
))
2688 (setq start
(1+ start
))
2689 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
2690 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
2691 ;; Parameters and constants
2693 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
2695 (setq start
(match-end 2))
2696 (setq start
(1+ start
))
2697 (if (setq a
(save-match-data
2698 (org-table-get-constant (match-string 1 f
))))
2699 (setq f
(replace-match
2700 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
2701 (if org-table-formula-debug
2702 (put-text-property 0 (length f
) :orig-formula f1 f
))
2705 (defun org-table-get-constant (const)
2706 "Find the value for a parameter or constant in a formula.
2707 Parameters get priority."
2708 (or (cdr (assoc const org-table-local-parameters
))
2709 (cdr (assoc const org-table-formula-constants-local
))
2710 (cdr (assoc const org-table-formula-constants
))
2711 (and (fboundp 'constants-get
) (constants-get const
))
2712 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
2713 (org-entry-get nil
(substring const
5) 'inherit
))
2716 (defvar org-table-fedit-map
2717 (let ((map (make-sparse-keymap)))
2718 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
2719 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
2720 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
2721 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
2722 (org-defkey map
"\C-c?" 'org-table-show-reference
)
2723 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
2724 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
2725 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
2726 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
2727 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
2728 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
2729 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
2730 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
2731 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
2732 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
2733 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
2734 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
2735 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
2736 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
2739 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
2741 ["Finish and Install" org-table-fedit-finish t
]
2742 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
2743 ["Abort" org-table-fedit-abort t
]
2745 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
2746 ["Complete Lisp Symbol" lisp-complete-symbol t
]
2748 "Shift Reference at Point"
2749 ["Up" org-table-fedit-ref-up t
]
2750 ["Down" org-table-fedit-ref-down t
]
2751 ["Left" org-table-fedit-ref-left t
]
2752 ["Right" org-table-fedit-ref-right t
]
2754 "Change Test Row for Column Formulas"
2755 ["Up" org-table-fedit-line-up t
]
2756 ["Down" org-table-fedit-line-down t
]
2758 ["Scroll Table Window" org-table-fedit-scroll t
]
2759 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
2760 ["Show Table Grid" org-table-fedit-toggle-coordinates
2761 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
2762 org-table-overlay-coordinates
)]
2764 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
2765 :style toggle
:selected org-table-buffer-is-an
]))
2769 (defun org-table-edit-formulas ()
2770 "Edit the formulas of the current table in a separate buffer."
2772 (when (save-excursion (beginning-of-line 1) (looking-at "[ \t]*#\\+TBLFM"))
2773 (beginning-of-line 0))
2774 (unless (org-at-table-p) (error "Not at a table"))
2775 (org-table-get-specials)
2776 (let ((key (org-table-current-field-formula 'key
'noerror
))
2777 (eql (sort (org-table-get-stored-formulas 'noerror
)
2778 'org-table-formula-less-p
))
2779 (pos (move-marker (make-marker) (point)))
2781 (wc (current-window-configuration))
2782 (sel-win (selected-window))
2783 (titles '((column .
"# Column Formulas\n")
2784 (field .
"# Field Formulas\n")
2785 (named .
"# Named Field Formulas\n")))
2787 (org-switch-to-buffer-other-window "*Edit Formulas*")
2789 ;; Keep global-font-lock-mode from turning on font-lock-mode
2790 (let ((font-lock-global-modes '(not fundamental-mode
)))
2792 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
2793 (org-set-local 'org-pos pos
)
2794 (org-set-local 'org-window-configuration wc
)
2795 (org-set-local 'org-selected-window sel-win
)
2796 (use-local-map org-table-fedit-map
)
2797 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
2798 (easy-menu-add org-table-fedit-menu
)
2799 (setq startline
(org-current-line))
2800 (while (setq entry
(pop eql
))
2802 ((equal (string-to-char (car entry
)) ?
@) 'field
)
2803 ((string-match "^[0-9]" (car entry
)) 'column
)
2805 (when (setq title
(assq type titles
))
2806 (or (bobp) (insert "\n"))
2807 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
2808 (setq titles
(delq title titles
)))
2809 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
2810 (setq s
(concat (if (equal (string-to-char (car entry
)) ?
@) "" "$")
2811 (car entry
) " = " (cdr entry
) "\n"))
2812 (remove-text-properties 0 (length s
) '(face nil
) s
)
2814 (if (eq org-table-use-standard-references t
)
2815 (org-table-fedit-toggle-ref-type))
2816 (org-goto-line startline
)
2817 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
2819 (defun org-table-fedit-post-command ()
2820 (when (not (memq this-command
'(lisp-complete-symbol)))
2821 (let ((win (selected-window)))
2824 (org-table-show-reference)
2826 (select-window win
)))))
2828 (defun org-table-formula-to-user (s)
2829 "Convert a formula from internal to user representation."
2830 (if (eq org-table-use-standard-references t
)
2831 (org-table-convert-refs-to-an s
)
2834 (defun org-table-formula-from-user (s)
2835 "Convert a formula from user to internal representation."
2836 (if org-table-use-standard-references
2837 (org-table-convert-refs-to-rc s
)
2840 (defun org-table-convert-refs-to-rc (s)
2841 "Convert spreadsheet references from AB7 to @7$28.
2842 Works for single references, but also for entire formulas and even the
2845 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^)]*)\\)" s start
)
2848 ;; format match, just advance
2849 (setq start
(match-end 0)))
2850 ((and (> (match-beginning 0) 0)
2851 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
2852 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
2853 ;; 3.e5 or something like this.
2854 (setq start
(match-end 0)))
2855 ((or (> (- (match-end 1) (match-beginning 1)) 2)
2856 ;; (member (match-string 1 s)
2857 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
2859 ;; function name, just advance
2860 (setq start
(match-end 0)))
2862 (setq start
(match-beginning 0)
2864 (if (equal (match-string 2 s
) "&")
2865 (format "$%d" (org-letters-to-number (match-string 1 s
)))
2867 (string-to-number (match-string 2 s
))
2868 (org-letters-to-number (match-string 1 s
))))
2872 (defun org-table-convert-refs-to-an (s)
2873 "Convert spreadsheet references from to @7$28 to AB7.
2874 Works for single references, but also for entire formulas and even the
2876 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
2877 (setq s
(replace-match
2879 (org-number-to-letters
2880 (string-to-number (match-string 2 s
)))
2881 (string-to-number (match-string 1 s
)))
2883 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
2884 (setq s
(replace-match (concat "\\1"
2885 (org-number-to-letters
2886 (string-to-number (match-string 2 s
))) "&")
2890 (defun org-letters-to-number (s)
2891 "Convert a base 26 number represented by letters into an integer.
2892 For example: AB -> 28."
2895 (while (> (length s
) 0)
2896 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
2900 (defun org-number-to-letters (n)
2901 "Convert an integer into a base 26 number represented by letters.
2902 For example: 28 -> AB."
2905 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
2909 (defun org-table-fedit-convert-buffer (function)
2910 "Convert all references in this buffer, using FUNCTION."
2911 (let ((line (org-current-line)))
2912 (goto-char (point-min))
2914 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
2915 (delete-region (point) (point-at-eol))
2916 (or (eobp) (forward-char 1)))
2917 (org-goto-line line
)))
2919 (defun org-table-fedit-toggle-ref-type ()
2920 "Convert all references in the buffer from B3 to @3$2 and back."
2922 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
2923 (org-table-fedit-convert-buffer
2924 (if org-table-buffer-is-an
2925 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
2926 (message "Reference type switched to %s"
2927 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
2929 (defun org-table-fedit-ref-up ()
2930 "Shift the reference at point one row/hline up."
2932 (org-table-fedit-shift-reference 'up
))
2933 (defun org-table-fedit-ref-down ()
2934 "Shift the reference at point one row/hline down."
2936 (org-table-fedit-shift-reference 'down
))
2937 (defun org-table-fedit-ref-left ()
2938 "Shift the reference at point one field to the left."
2940 (org-table-fedit-shift-reference 'left
))
2941 (defun org-table-fedit-ref-right ()
2942 "Shift the reference at point one field to the right."
2944 (org-table-fedit-shift-reference 'right
))
2946 (defun org-table-fedit-shift-reference (dir)
2948 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
2949 (if (memq dir
'(left right
))
2950 (org-rematch-and-replace 1 (eq dir
'left
))
2951 (error "Cannot shift reference in this direction")))
2952 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
2953 ;; A B3-like reference
2954 (if (memq dir
'(up down
))
2955 (org-rematch-and-replace 2 (eq dir
'up
))
2956 (org-rematch-and-replace 1 (eq dir
'left
))))
2958 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
2959 ;; An internal reference
2960 (if (memq dir
'(up down
))
2961 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
2962 (org-rematch-and-replace 5 (eq dir
'left
))))))
2964 (defun org-rematch-and-replace (n &optional decr hline
)
2965 "Re-match the group N, and replace it with the shifted refrence."
2966 (or (match-end n
) (error "Cannot shift reference in this direction"))
2967 (goto-char (match-beginning n
))
2968 (and (looking-at (regexp-quote (match-string n
)))
2969 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
2972 (defun org-table-shift-refpart (ref &optional decr hline
)
2973 "Shift a refrence part REF.
2974 If DECR is set, decrease the references row/column, else increase.
2975 If HLINE is set, this may be a hline reference, it certainly is not
2976 a translation reference."
2978 (let* ((sign (string-match "^[-+]" ref
)) n
)
2980 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
2982 ((and hline
(string-match "^I+" ref
))
2983 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
2984 (setq n
(+ n
(if decr -
1 1)))
2985 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
2987 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
2989 (concat sign
(make-string n ?I
)))
2991 ((string-match "^[0-9]+" ref
)
2992 (setq n
(string-to-number (concat sign ref
)))
2993 (setq n
(+ n
(if decr -
1 1)))
2995 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
2996 (number-to-string (max 1 n
))))
2998 ((string-match "^[a-zA-Z]+" ref
)
2999 (org-number-to-letters
3000 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3002 (t (error "Cannot shift reference"))))))
3004 (defun org-table-fedit-toggle-coordinates ()
3005 "Toggle the display of coordinates in the referenced table."
3007 (let ((pos (marker-position org-pos
)))
3008 (with-current-buffer (marker-buffer org-pos
)
3011 (org-table-toggle-coordinate-overlays)))))
3013 (defun org-table-fedit-finish (&optional arg
)
3014 "Parse the buffer for formula definitions and install them.
3015 With prefix ARG, apply the new formulas to the table."
3017 (org-table-remove-rectangle-highlight)
3018 (if org-table-use-standard-references
3020 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3021 (setq org-table-buffer-is-an nil
)))
3022 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3023 (goto-char (point-min))
3024 (while (re-search-forward
3025 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3027 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3028 form
(match-string 3))
3029 (setq form
(org-trim form
))
3030 (when (not (equal form
""))
3031 (while (string-match "[ \t]*\n[ \t]*" form
)
3032 (setq form
(replace-match " " t t form
)))
3033 (when (assoc var eql
)
3034 (error "Double formulas for %s" var
))
3035 (push (cons var form
) eql
)))
3037 (set-window-configuration org-window-configuration
)
3038 (select-window sel-win
)
3040 (unless (org-at-table-p)
3041 (error "Lost table position - cannot install formulae"))
3042 (org-table-store-formulas eql
)
3043 (move-marker pos nil
)
3044 (kill-buffer "*Edit Formulas*")
3046 (org-table-recalculate 'all
)
3047 (message "New formulas installed - press C-u C-c C-c to apply."))))
3049 (defun org-table-fedit-abort ()
3050 "Abort editing formulas, without installing the changes."
3052 (org-table-remove-rectangle-highlight)
3053 (let ((pos org-pos
) (sel-win org-selected-window
))
3054 (set-window-configuration org-window-configuration
)
3055 (select-window sel-win
)
3057 (move-marker pos nil
)
3058 (message "Formula editing aborted without installing changes")))
3060 (defun org-table-fedit-lisp-indent ()
3061 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3063 (let ((pos (point)) beg end ind
)
3064 (beginning-of-line 1)
3066 ((looking-at "[ \t]")
3068 (call-interactively 'lisp-indent-line
))
3069 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3070 ((not (fboundp 'pp-buffer
))
3071 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3072 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3073 (goto-char (- (match-end 0) 2))
3075 (setq ind
(make-string (current-column) ?\
))
3076 (condition-case nil
(forward-sexp 1)
3078 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3081 (narrow-to-region beg end
)
3082 (if (eq last-command this-command
)
3084 (goto-char (point-min))
3085 (setq this-command nil
)
3086 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3087 (replace-match " ")))
3089 (untabify (point-min) (point-max))
3090 (goto-char (1+ (point-min)))
3091 (while (re-search-forward "^." nil t
)
3092 (beginning-of-line 1)
3094 (goto-char (point-max))
3095 (backward-delete-char 1)))
3099 (defvar org-show-positions nil
)
3101 (defun org-table-show-reference (&optional local
)
3102 "Show the location/value of the $ expression at point."
3104 (org-table-remove-rectangle-highlight)
3106 (let ((pos (if local
(point) org-pos
))
3108 (org-inhibit-highlight-removal t
)
3109 (win (selected-window))
3110 (org-show-positions nil
)
3111 var name e what match dest
)
3112 (if local
(org-table-get-specials))
3114 ((or (org-at-regexp-p org-table-range-regexp2
)
3115 (org-at-regexp-p org-table-translate-regexp
)
3116 (org-at-regexp-p org-table-range-regexp
))
3119 (org-table-convert-refs-to-rc (match-string 0))))
3121 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3122 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3124 (t (error "No reference at point")))
3125 match
(and what
(or match
(match-string 0))))
3126 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3127 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3128 'secondary-selection
))
3129 (org-add-hook 'before-change-functions
3130 'org-table-remove-rectangle-highlight
)
3131 (if (eq what
'name
) (setq var
(substring match
1)))
3132 (when (eq what
'range
)
3133 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3134 (setq match
(org-table-formula-substitute-names match
)))
3138 (re-search-backward "^\\S-" nil t
)
3139 (beginning-of-line 1)
3140 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3143 (org-table-convert-refs-to-rc (match-string 1))))
3144 (org-table-add-rectangle-overlay
3145 (match-beginning 1) (match-end 1) face2
))))
3146 (if (and (markerp pos
) (marker-buffer pos
))
3147 (if (get-buffer-window (marker-buffer pos
))
3148 (select-window (get-buffer-window (marker-buffer pos
)))
3149 (org-switch-to-buffer-other-window (get-buffer-window
3150 (marker-buffer pos
)))))
3152 (org-table-force-dataline)
3154 (setq name
(substring dest
1))
3156 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3157 (setq e
(assoc name org-table-named-field-locations
))
3158 (org-goto-line (nth 1 e
))
3159 (org-table-goto-column (nth 2 e
)))
3160 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3161 (let ((l (string-to-number (match-string 1 dest
)))
3162 (c (string-to-number (match-string 2 dest
))))
3163 (org-goto-line (aref org-table-dlines l
))
3164 (org-table-goto-column c
)))
3165 (t (org-table-goto-column (string-to-number name
))))
3166 (move-marker pos
(point))
3167 (org-table-highlight-rectangle nil nil face2
))
3169 ((equal dest match
))
3174 (org-table-get-range match nil nil
'highlight
))
3176 ((setq e
(assoc var org-table-named-field-locations
))
3177 (org-goto-line (nth 1 e
))
3178 (org-table-goto-column (nth 2 e
))
3179 (org-table-highlight-rectangle (point) (point))
3180 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3181 ((setq e
(assoc var org-table-column-names
))
3182 (org-table-goto-column (string-to-number (cdr e
)))
3183 (org-table-highlight-rectangle (point) (point))
3184 (goto-char (org-table-begin))
3185 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3188 (goto-char (match-beginning 1))
3189 (org-table-highlight-rectangle)
3190 (message "Named column (column %s)" (cdr e
)))
3191 (error "Column name not found")))
3194 (org-table-goto-column (string-to-number (substring match
1)))
3195 (org-table-highlight-rectangle (point) (point))
3196 (message "Column %s" (substring match
1)))
3197 ((setq e
(assoc var org-table-local-parameters
))
3198 (goto-char (org-table-begin))
3199 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3201 (goto-char (match-beginning 1))
3202 (org-table-highlight-rectangle)
3203 (message "Local parameter."))
3204 (error "Parameter not found")))
3207 ((not var
) (error "No reference at point"))
3208 ((setq e
(assoc var org-table-formula-constants-local
))
3209 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3211 ((setq e
(assoc var org-table-formula-constants
))
3212 (message "Constant: $%s=%s in `org-table-formula-constants'."
3214 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3215 (message "Constant: $%s=%s, from `constants.el'%s."
3216 var e
(format " (%s units)" constants-unit-system
)))
3217 (t (error "Undefined name $%s" var
)))))
3219 (when (and org-show-positions
3220 (not (memq this-command
'(org-table-fedit-scroll
3221 org-table-fedit-scroll-down
))))
3222 (push pos org-show-positions
)
3223 (push org-table-current-begin-pos org-show-positions
)
3224 (let ((min (apply 'min org-show-positions
))
3225 (max (apply 'max org-show-positions
)))
3226 (goto-char min
) (recenter 0)
3228 (or (pos-visible-in-window-p max
) (recenter -
1))))
3229 (select-window win
))))
3231 (defun org-table-force-dataline ()
3232 "Make sure the cursor is in a dataline in a table."
3233 (unless (save-excursion
3234 (beginning-of-line 1)
3235 (looking-at org-table-dataline-regexp
))
3236 (let* ((re org-table-dataline-regexp
)
3237 (p1 (save-excursion (re-search-forward re nil
'move
)))
3238 (p2 (save-excursion (re-search-backward re nil
'move
))))
3240 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3242 ((or p1 p2
) (goto-char (or p1 p2
)))
3243 (t (error "No table dataline around here"))))))
3245 (defun org-table-fedit-line-up ()
3246 "Move cursor one line up in the window showing the table."
3248 (org-table-fedit-move 'previous-line
))
3250 (defun org-table-fedit-line-down ()
3251 "Move cursor one line down in the window showing the table."
3253 (org-table-fedit-move 'next-line
))
3255 (defun org-table-fedit-move (command)
3256 "Move the cursor in the window showing the table.
3257 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3258 (let ((org-table-allow-automatic-line-recalculation nil
)
3259 (pos org-pos
) (win (selected-window)) p
)
3260 (select-window (get-buffer-window (marker-buffer org-pos
)))
3262 (call-interactively command
)
3263 (while (and (org-at-table-p)
3264 (org-at-table-hline-p))
3265 (call-interactively command
))
3266 (or (org-at-table-p) (goto-char p
))
3267 (move-marker pos
(point))
3268 (select-window win
)))
3270 (defun org-table-fedit-scroll (N)
3272 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3273 (scroll-other-window N
)))
3275 (defun org-table-fedit-scroll-down (N)
3277 (org-table-fedit-scroll (- N
)))
3279 (defvar org-table-rectangle-overlays nil
)
3281 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3282 "Add a new overlay."
3283 (let ((ov (org-make-overlay beg end
)))
3284 (org-overlay-put ov
'face
(or face
'secondary-selection
))
3285 (push ov org-table-rectangle-overlays
)))
3287 (defun org-table-highlight-rectangle (&optional beg end face
)
3288 "Highlight rectangular region in a table."
3289 (setq beg
(or beg
(point)) end
(or end
(point)))
3290 (let ((b (min beg end
))
3293 (and (boundp 'org-show-positions
)
3294 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3295 (goto-char (min beg end
))
3296 (setq l1
(org-current-line)
3297 c1
(org-table-current-column))
3298 (goto-char (max beg end
))
3299 (setq l2
(org-current-line)
3300 c2
(org-table-current-column))
3301 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3303 (beginning-of-line 1)
3304 (loop for line from l1 to l2 do
3305 (when (looking-at org-table-dataline-regexp
)
3306 (org-table-goto-column c1
)
3307 (skip-chars-backward "^|\n") (setq beg
(point))
3308 (org-table-goto-column c2
)
3309 (skip-chars-forward "^|\n") (setq end
(point))
3310 (org-table-add-rectangle-overlay beg end face
))
3311 (beginning-of-line 2))
3313 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3315 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3316 "Remove the rectangle overlays."
3317 (unless org-inhibit-highlight-removal
3318 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3319 (mapc 'org-delete-overlay org-table-rectangle-overlays
)
3320 (setq org-table-rectangle-overlays nil
)))
3322 (defvar org-table-coordinate-overlays nil
3323 "Collects the coordinate grid overlays, so that they can be removed.")
3324 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3326 (defun org-table-overlay-coordinates ()
3327 "Add overlays to the table at point, to show row/column coordinates."
3329 (mapc 'org-delete-overlay org-table-coordinate-overlays
)
3330 (setq org-table-coordinate-overlays nil
)
3332 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3333 (goto-char (org-table-begin))
3334 (while (org-at-table-p)
3335 (setq eol
(point-at-eol))
3336 (setq ov
(org-make-overlay (point-at-bol) (1+ (point-at-bol))))
3337 (push ov org-table-coordinate-overlays
)
3338 (setq hline
(looking-at org-table-hline-regexp
))
3339 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3340 (format "%4d" (setq id
(1+ id
)))))
3341 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3344 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3345 (setq beg
(1+ (match-beginning 0))
3347 s1
(concat "$" (int-to-string ic
))
3348 s2
(org-number-to-letters ic
)
3349 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3350 (setq ov
(org-make-overlay beg
(+ beg
(length str
))))
3351 (push ov org-table-coordinate-overlays
)
3352 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3353 (beginning-of-line 2)))))
3355 (defun org-table-toggle-coordinate-overlays ()
3356 "Toggle the display of Row/Column numbers in tables."
3358 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3359 (message "Row/Column number display turned %s"
3360 (if org-table-overlay-coordinates
"on" "off"))
3361 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3363 (unless org-table-overlay-coordinates
3364 (mapc 'org-delete-overlay org-table-coordinate-overlays
)
3365 (setq org-table-coordinate-overlays nil
)))
3367 (defun org-table-toggle-formula-debugger ()
3368 "Toggle the formula debugger in tables."
3370 (setq org-table-formula-debug
(not org-table-formula-debug
))
3371 (message "Formula debugging has been turned %s"
3372 (if org-table-formula-debug
"on" "off")))
3374 ;;; The orgtbl minor mode
3376 ;; Define a minor mode which can be used in other modes in order to
3377 ;; integrate the org-mode table editor.
3379 ;; This is really a hack, because the org-mode table editor uses several
3380 ;; keys which normally belong to the major mode, for example the TAB and
3381 ;; RET keys. Here is how it works: The minor mode defines all the keys
3382 ;; necessary to operate the table editor, but wraps the commands into a
3383 ;; function which tests if the cursor is currently inside a table. If that
3384 ;; is the case, the table editor command is executed. However, when any of
3385 ;; those keys is used outside a table, the function uses `key-binding' to
3386 ;; look up if the key has an associated command in another currently active
3387 ;; keymap (minor modes, major mode, global), and executes that command.
3388 ;; There might be problems if any of the keys used by the table editor is
3389 ;; otherwise used as a prefix key.
3391 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3392 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3393 ;; addresses this by checking explicitly for both bindings.
3395 ;; The optimized version (see variable `orgtbl-optimized') takes over
3396 ;; all keys which are bound to `self-insert-command' in the *global map*.
3397 ;; Some modes bind other commands to simple characters, for example
3398 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3399 ;; active, this binding is ignored inside tables and replaced with a
3400 ;; modified self-insert.
3402 (defvar orgtbl-mode nil
3403 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
3404 table editor in arbitrary modes.")
3405 (make-variable-buffer-local 'orgtbl-mode
)
3407 (defvar orgtbl-mode-map
(make-keymap)
3408 "Keymap for `orgtbl-mode'.")
3411 (defun turn-on-orgtbl ()
3412 "Unconditionally turn on `orgtbl-mode'."
3415 (defvar org-old-auto-fill-inhibit-regexp nil
3416 "Local variable used by `orgtbl-mode'")
3418 (defconst orgtbl-line-start-regexp
3419 "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\|TBLNAME\\):\\)"
3420 "Matches a line belonging to an orgtbl.")
3422 (defconst orgtbl-extra-font-lock-keywords
3423 (list (list (concat "^" orgtbl-line-start-regexp
".*")
3424 0 (quote 'org-table
) 'prepend
))
3425 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
3428 (defun orgtbl-mode (&optional arg
)
3429 "The `org-mode' table editor as a minor mode for use in other modes."
3431 (org-load-modules-maybe)
3433 ;; Exit without error, in case some hook functions calls this
3434 ;; by accident in org-mode.
3435 (message "Orgtbl-mode is not useful in org-mode, command ignored")
3437 (if arg
(> (prefix-numeric-value arg
) 0) (not orgtbl-mode
)))
3440 (and (orgtbl-setup) (defun orgtbl-setup () nil
))
3441 ;; Make sure we are first in minor-mode-map-alist
3442 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
3443 (and c
(setq minor-mode-map-alist
3444 (cons c
(delq c minor-mode-map-alist
)))))
3445 (org-set-local (quote org-table-may-need-update
) t
)
3446 (org-add-hook 'before-change-functions
'org-before-change-function
3448 (org-set-local 'org-old-auto-fill-inhibit-regexp
3449 auto-fill-inhibit-regexp
)
3450 (org-set-local 'auto-fill-inhibit-regexp
3451 (if auto-fill-inhibit-regexp
3452 (concat orgtbl-line-start-regexp
"\\|"
3453 auto-fill-inhibit-regexp
)
3454 orgtbl-line-start-regexp
))
3455 (org-add-to-invisibility-spec '(org-cwidth))
3456 (when (fboundp 'font-lock-add-keywords
)
3457 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
3458 (org-restart-font-lock))
3459 (easy-menu-add orgtbl-mode-menu
)
3460 (run-hooks 'orgtbl-mode-hook
))
3461 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
3462 (org-table-cleanup-narrow-column-properties)
3463 (org-remove-from-invisibility-spec '(org-cwidth))
3464 (remove-hook 'before-change-functions
'org-before-change-function t
)
3465 (when (fboundp 'font-lock-remove-keywords
)
3466 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
3467 (org-restart-font-lock))
3468 (easy-menu-remove orgtbl-mode-menu
)
3469 (force-mode-line-update 'all
))))
3471 (defun org-table-cleanup-narrow-column-properties ()
3472 "Remove all properties related to narrow-column invisibility."
3474 (while (setq s
(text-property-any s
(point-max)
3475 'display org-narrow-column-arrow
))
3476 (remove-text-properties s
(1+ s
) '(display t
)))
3478 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
3479 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
3481 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
3482 (remove-text-properties s
(1+ s
) '(invisible t
)))))
3484 ;; Install it as a minor mode.
3485 (put 'orgtbl-mode
:included t
)
3486 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
3487 (add-minor-mode 'orgtbl-mode
" OrgTbl" orgtbl-mode-map
)
3489 (defun orgtbl-make-binding (fun n
&rest keys
)
3490 "Create a function for binding in the table minor mode.
3491 FUN is the command to call inside a table. N is used to create a unique
3492 command name. KEYS are keys that should be checked in for a command
3493 to execute outside of tables."
3496 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
3498 (concat "In tables, run `" (symbol-name fun
) "'.\n"
3499 "Outside of tables, run the binding of `"
3500 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
3505 (list 'call-interactively
(list 'quote fun
))
3506 (list 'let
'(orgtbl-mode)
3507 (list 'call-interactively
3510 (list 'key-binding k
))
3512 '('orgtbl-error
))))))))
3514 (defun orgtbl-error ()
3515 "Error when there is no default binding for a table key."
3517 (error "This key has no function outside tables"))
3519 (defun orgtbl-setup ()
3520 "Setup orgtbl keymaps."
3524 '([(meta shift left
)] org-table-delete-column
)
3525 '([(meta left
)] org-table-move-column-left
)
3526 '([(meta right
)] org-table-move-column-right
)
3527 '([(meta shift right
)] org-table-insert-column
)
3528 '([(meta shift up
)] org-table-kill-row
)
3529 '([(meta shift down
)] org-table-insert-row
)
3530 '([(meta up
)] org-table-move-row-up
)
3531 '([(meta down
)] org-table-move-row-down
)
3532 '("\C-c\C-w" org-table-cut-region
)
3533 '("\C-c\M-w" org-table-copy-region
)
3534 '("\C-c\C-y" org-table-paste-rectangle
)
3535 '("\C-c-" org-table-insert-hline
)
3536 '("\C-c}" org-table-toggle-coordinate-overlays
)
3537 '("\C-c{" org-table-toggle-formula-debugger
)
3538 '("\C-m" org-table-next-row
)
3539 '([(shift return
)] org-table-copy-down
)
3540 '("\C-c?" org-table-field-info
)
3541 '("\C-c " org-table-blank-field
)
3542 '("\C-c+" org-table-sum
)
3543 '("\C-c=" org-table-eval-formula
)
3544 '("\C-c'" org-table-edit-formulas
)
3545 '("\C-c`" org-table-edit-field
)
3546 '("\C-c*" org-table-recalculate
)
3547 '("\C-c^" org-table-sort-lines
)
3548 '("\M-a" org-table-beginning-of-field
)
3549 '("\M-e" org-table-end-of-field
)
3550 '([(control ?
#)] org-table-rotate-recalc-marks
)))
3552 (while (setq elt
(pop bindings
))
3553 (setq nfunc
(1+ nfunc
))
3554 (setq key
(org-key (car elt
))
3556 cmd
(orgtbl-make-binding fun nfunc key
))
3557 (org-defkey orgtbl-mode-map key cmd
))
3559 ;; Special treatment needed for TAB and RET
3560 (org-defkey orgtbl-mode-map
[(return)]
3561 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
3562 (org-defkey orgtbl-mode-map
"\C-m"
3563 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
3565 (org-defkey orgtbl-mode-map
[(tab)]
3566 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
3567 (org-defkey orgtbl-mode-map
"\C-i"
3568 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
3570 (org-defkey orgtbl-mode-map
[(shift tab
)]
3571 (orgtbl-make-binding 'org-table-previous-field
104
3572 [(shift tab
)] [(tab)] "\C-i"))
3575 (unless (featurep 'xemacs
)
3576 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
3577 (orgtbl-make-binding 'org-table-previous-field
107
3578 [S-iso-lefttab
] [backtab] [(shift tab)]
3581 (org-defkey orgtbl-mode-map [backtab]
3582 (orgtbl-make-binding 'org-table-previous-field
108
3583 [backtab] [S-iso-lefttab] [(shift tab)]
3586 (org-defkey orgtbl-mode-map "\M-\C-m"
3587 (orgtbl-make-binding 'org-table-wrap-region 105
3588 "\M-\C-m" [(meta return)]))
3589 (org-defkey orgtbl-mode-map [(meta return)]
3590 (orgtbl-make-binding 'org-table-wrap-region 106
3591 [(meta return)] "\M-\C-m"))
3593 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
3594 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
3596 (when orgtbl-optimized
3597 ;; If the user wants maximum table support, we need to hijack
3598 ;; some standard editing functions
3599 (org-remap orgtbl-mode-map
3600 'self-insert-command 'orgtbl-self-insert-command
3601 'delete-char 'org-delete-char
3602 'delete-backward-char 'org-delete-backward-char)
3603 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
3604 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
3606 ["Create or convert" org-table-create-or-convert-from-region
3607 :active (not (org-at-table-p)) :keys "C-c |" ]
3609 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
3610 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
3611 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
3612 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
3614 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
3615 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
3616 ["Copy Field from Above"
3617 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
3620 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
3621 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
3622 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
3623 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
3625 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
3626 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
3627 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
3628 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
3629 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
3631 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
3633 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
3634 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
3635 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
3636 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
3639 ["Insert table template" orgtbl-insert-radio-table
3640 (assq major-mode orgtbl-radio-table-templates)]
3641 ["Comment/uncomment table" orgtbl-toggle-comment t])
3643 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
3644 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
3645 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
3646 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
3647 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
3648 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
3649 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
3650 ["Sum Column/Rectangle" org-table-sum
3651 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
3652 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
3654 org-table-toggle-formula-debugger :active (org-at-table-p)
3656 :style toggle :selected org-table-formula-debug]
3657 ["Show Col/Row Numbers"
3658 org-table-toggle-coordinate-overlays :active (org-at-table-p)
3660 :style toggle :selected org-table-overlay-coordinates]
3664 (defun orgtbl-ctrl-c-ctrl-c (arg)
3665 "If the cursor is inside a table, realign the table.
3666 If it is a table to be sent away to a receiver, do it.
3667 With prefix arg, also recompute table."
3669 (let ((pos (point)) action)
3671 (beginning-of-line 1)
3672 (setq action (cond ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
3673 ((looking-at "[ \t]*|") pos)
3674 ((looking-at "[ \t]*#\\+TBLFM:") 'recalc))))
3678 (org-table-maybe-eval-formula)
3680 (call-interactively 'org-table-recalculate)
3681 (org-table-maybe-recalculate-line))
3682 (call-interactively 'org-table-align)
3683 (orgtbl-send-table 'maybe))
3684 ((eq action 'recalc)
3686 (beginning-of-line 1)
3687 (skip-chars-backward " \r\n\t")
3688 (if (org-at-table-p)
3689 (org-call-with-arg 'org-table-recalculate t))))
3690 (t (let (orgtbl-mode)
3691 (call-interactively (key-binding "\C-c\C-c")))))))
3693 (defun orgtbl-create-or-convert-from-region (arg)
3694 "Create table or convert region to table, if no conflicting binding.
3695 This installs the table binding `C-c |', but only if there is no
3696 conflicting binding to this key outside orgtbl-mode."
3698 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
3700 (call-interactively cmd)
3701 (call-interactively 'org-table-create-or-convert-from-region))))
3703 (defun orgtbl-tab (arg)
3704 "Justification and field motion for `orgtbl-mode'."
3706 (if arg (org-table-edit-field t)
3707 (org-table-justify-field-maybe)
3708 (org-table-next-field)))
3710 (defun orgtbl-ret ()
3711 "Justification and field motion for `orgtbl-mode'."
3715 (org-table-justify-field-maybe)
3716 (org-table-next-row)))
3718 (defun orgtbl-self-insert-command (N)
3719 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
3720 If the cursor is in a table looking at whitespace, the whitespace is
3721 overwritten, and the table is not marked as requiring realignment."
3723 (if (and (org-at-table-p)
3725 (and org-table-auto-blank-field
3726 (member last-command
3727 '(orgtbl-hijacker-command-100
3728 orgtbl-hijacker-command-101
3729 orgtbl-hijacker-command-102
3730 orgtbl-hijacker-command-103
3731 orgtbl-hijacker-command-104
3732 orgtbl-hijacker-command-105
3734 (org-table-blank-field))
3737 (looking-at "[^|\n]* +|"))
3738 (let (org-table-may-need-update)
3739 (goto-char (1- (match-end 0)))
3740 (delete-backward-char 1)
3741 (goto-char (match-beginning 0))
3742 (self-insert-command N))
3743 (setq org-table-may-need-update t)
3746 (cmd (or (key-binding
3747 (or (and (listp function-key-map)
3748 (setq a (assoc last-input-event function-key-map))
3750 (vector last-input-event)))
3751 'self-insert-command)))
3752 (call-interactively cmd)
3753 (if (and org-self-insert-cluster-for-undo
3754 (eq cmd 'self-insert-command))
3755 (if (not (eq last-command 'orgtbl-self-insert-command))
3756 (setq org-self-insert-command-undo-counter 1)
3757 (if (>= org-self-insert-command-undo-counter 20)
3758 (setq org-self-insert-command-undo-counter 1)
3759 (and (> org-self-insert-command-undo-counter 0)
3761 (not (cadr buffer-undo-list)) ; remove nil entry
3762 (setcdr buffer-undo-list (cddr buffer-undo-list)))
3763 (setq org-self-insert-command-undo-counter
3764 (1+ org-self-insert-command-undo-counter))))))))
3766 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
3767 "Regular expression matching exponentials as produced by calc.")
3769 (defun orgtbl-export (table target)
3771 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
3772 (lines (org-split-string table "[ \t]*\n[ \t]*"))
3773 org-table-last-alignment org-table-last-column-widths
3775 (if (not (fboundp func))
3776 (error "Cannot export orgtbl table to %s" target))
3777 (setq lines (org-table-clean-before-export lines))
3781 (if (string-match org-table-hline-regexp x)
3783 (org-split-string (org-trim x) "\\s-*|\\s-*")))
3785 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
3787 (loop for i from (1- maxcol) downto 0 do
3788 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
3789 (setq column (delq nil column))
3790 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
3791 (push (> (/ (apply '+ (mapcar (lambda (x) (if (string-match org-table-number-regexp x) 1 0)) column)) maxcol) org-table-number-fraction) org-table-last-alignment))
3792 (funcall func table nil)))
3794 (defun orgtbl-gather-send-defs ()
3795 "Gathers a plist of :name, :transform, :params for each destination before
3798 (goto-char (org-table-begin))
3800 (beginning-of-line 0)
3801 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
3802 (let ((name (org-no-properties (match-string 1)))
3803 (transform (intern (match-string 2)))
3804 (params (if (match-end 3)
3805 (read (concat "(" (match-string 3) ")")))))
3806 (push (list :name name :transform transform :params params)
3808 (beginning-of-line 0)))
3811 (defun orgtbl-send-replace-tbl (name txt)
3812 "Find and replace table NAME with TXT."
3814 (goto-char (point-min))
3815 (unless (re-search-forward
3816 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
3817 (error "Don't know where to insert translated table"))
3818 (goto-char (match-beginning 0))
3819 (beginning-of-line 2)
3821 (let ((beg (point)))
3822 (unless (re-search-forward
3823 (concat "END RECEIVE ORGTBL +" name) nil t)
3824 (error "Cannot find end of insertion region"))
3825 (beginning-of-line 1)
3826 (delete-region beg (point))))
3830 (defun org-table-to-lisp (&optional txt)
3831 "Convert the table at point to a Lisp structure.
3832 The structure will be a list. Each item is either the symbol `hline'
3833 for a horizontal separator line, or a list of field values as strings.
3834 The table is taken from the parameter TXT, or from the buffer at point."
3836 (unless (org-at-table-p)
3837 (error "No table at point")))
3839 (buffer-substring-no-properties (org-table-begin)
3841 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
3845 (if (string-match org-table-hline-regexp x)
3847 (org-split-string (org-trim x) "\\s-*|\\s-*")))
3850 (defun orgtbl-send-table (&optional maybe)
3851 "Send a transformed version of this table to the receiver position.
3852 With argument MAYBE, fail quietly if no transformation is defined for
3856 (unless (org-at-table-p) (error "Not at a table"))
3857 ;; when non-interactive, we assume align has just happened.
3858 (when (interactive-p) (org-table-align))
3859 (let ((dests (orgtbl-gather-send-defs))
3860 (txt (buffer-substring-no-properties (org-table-begin)
3863 (unless dests (if maybe (throw 'exit nil)
3864 (error "Don't know how to transform this table")))
3865 (dolist (dest dests)
3866 (let* ((name (plist-get dest :name))
3867 (transform (plist-get dest :transform))
3868 (params (plist-get dest :params))
3869 (skip (plist-get params :skip))
3870 (skipcols (plist-get params :skipcols))
3872 (lines (org-table-clean-before-export
3874 (org-split-string txt "[ \t]*\n[ \t]*"))))
3875 (i0 (if org-table-clean-did-remove-column 2 1))
3878 (if (string-match org-table-hline-regexp x)
3880 (org-remove-by-index
3881 (org-split-string (org-trim x) "\\s-*|\\s-*")
3884 (fun (if (= i0 2) 'cdr 'identity))
3885 (org-table-last-alignment
3886 (org-remove-by-index (funcall fun org-table-last-alignment)
3888 (org-table-last-column-widths
3889 (org-remove-by-index (funcall fun org-table-last-column-widths)
3891 (txt (if (fboundp transform)
3892 (funcall transform table params)
3893 (error "No such transformation function %s" transform))))
3894 (orgtbl-send-replace-tbl name txt))
3895 (setq ntbl (1+ ntbl)))
3896 (message "Table converted and installed at %d receiver location%s"
3897 ntbl (if (> ntbl 1) "s" "")))))
3899 (defun org-remove-by-index (list indices &optional i0)
3900 "Remove the elements in LIST with indices in INDICES.
3901 First element has index 0, or I0 if given."
3904 (if (integerp indices) (setq indices (list indices)))
3905 (setq i0 (1- (or i0 0)))
3906 (delq :rm (mapcar (lambda (x)
3908 (if (memq i0 indices) :rm x))
3911 (defun orgtbl-toggle-comment ()
3912 "Comment or uncomment the orgtbl at point."
3914 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
3915 (re2 (concat "^" orgtbl-line-start-regexp))
3916 (commented (save-excursion (beginning-of-line 1)
3917 (cond ((looking-at re1) t)
3918 ((looking-at re2) nil)
3919 (t (error "Not at an org table")))))
3920 (re (if commented re1 re2))
3923 (beginning-of-line 1)
3924 (while (looking-at re) (beginning-of-line 0))
3925 (beginning-of-line 2)
3927 (while (looking-at re) (beginning-of-line 2))
3929 (comment-region beg end (if commented '(4) nil))))
3931 (defun orgtbl-insert-radio-table ()
3932 "Insert a radio table template appropriate for this major mode."
3934 (let* ((e (assq major-mode orgtbl-radio-table-templates))
3937 (unless e (error "No radio table setup defined for %s" major-mode))
3938 (setq name (read-string "Table name: "))
3939 (while (string-match "%n" txt)
3940 (setq txt (replace-match name t t txt)))
3941 (or (bolp) (insert "\n"))
3946 ;; Dynamically bound input and output for table formatting.
3947 (defvar *orgtbl-table* nil
3948 "Carries the current table through formatting routines.")
3949 (defvar *orgtbl-rtn* nil
3950 "Formatting routines push the output lines here.")
3951 ;; Formatting parameters for the current table section.
3952 (defvar *orgtbl-hline* nil "Text used for horizontal lines")
3953 (defvar *orgtbl-sep* nil "Text used as a column separator")
3954 (defvar *orgtbl-default-fmt* nil "Default format for each entry")
3955 (defvar *orgtbl-fmt* nil "Format for each entry")
3956 (defvar *orgtbl-efmt* nil "Format for numbers")
3957 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt")
3958 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row")
3959 (defvar *orgtbl-lstart* nil "Text starting a row")
3960 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row")
3961 (defvar *orgtbl-lend* nil "Text ending a row")
3962 (defvar *orgtbl-llend* nil "Specializes lend for the last row")
3964 (defsubst orgtbl-get-fmt (fmt i)
3965 "Retrieve the format from FMT corresponding to the Ith column."
3966 (if (and (not (functionp fmt)) (consp fmt))
3970 (defsubst orgtbl-apply-fmt (fmt &rest args)
3971 "Apply format FMT to the arguments. NIL FMTs return the first argument."
3972 (cond ((functionp fmt) (apply fmt args))
3973 (fmt (apply 'format fmt args))
3977 (defsubst orgtbl-eval-str (str)
3978 "If STR is a function, evaluate it with no arguments."
3983 (defun orgtbl-format-line (line)
3984 "Format LINE as a table row."
3985 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
3991 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
3992 (f (if (and efmt (string-match orgtbl-exp-regexp f))
3993 (orgtbl-apply-fmt efmt (match-string 1 f)
3996 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
3997 *orgtbl-default-fmt*)
4000 (push (if *orgtbl-lfmt*
4001 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4002 (concat (orgtbl-eval-str *orgtbl-lstart*)
4003 (mapconcat 'identity line *orgtbl-sep*)
4004 (orgtbl-eval-str *orgtbl-lend*)))
4007 (defun orgtbl-format-section (section-stopper)
4008 "Format lines until the first occurrence of SECTION-STOPPER."
4011 (while (not (eq (car *orgtbl-table*) section-stopper))
4012 (if prevline (orgtbl-format-line prevline))
4013 (setq prevline (pop *orgtbl-table*)))
4014 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4015 (*orgtbl-lend* *orgtbl-llend*)
4016 (*orgtbl-lfmt* *orgtbl-llfmt*))
4017 (orgtbl-format-line prevline))))))
4019 (defun orgtbl-to-generic (table params)
4020 "Convert the orgtbl-mode TABLE to some other format.
4021 This generic routine can be used for many standard cases.
4022 TABLE is a list, each entry either the symbol `hline' for a horizontal
4023 separator line, or a list of fields for that line.
4024 PARAMS is a property list of parameters that can influence the conversion.
4025 For the generic converter, some parameters are obligatory: You need to
4026 specify either :lfmt, or all of (:lstart :lend :sep).
4028 Valid parameters are
4030 :splice When set to t, return only table body lines, don't wrap
4031 them into :tstart and :tend. Default is nil. When :splice
4032 is non-nil, this also means that the exporter should not look
4033 for and interpret header and footer sections.
4035 :hline String to be inserted on horizontal separation lines.
4036 May be nil to ignore hlines.
4038 :sep Separator between two fields
4039 :remove-nil-lines Do not include lines that evaluate to nil.
4042 Each in the following group may be either a string or a function
4043 of no arguments returning a string:
4044 :tstart String to start the table. Ignored when :splice is t.
4045 :tend String to end the table. Ignored when :splice is t.
4046 :lstart String to start a new table line.
4047 :llstart String to start the last table line, defaults to :lstart.
4048 :lend String to end a table line
4049 :llend String to end the last table line, defaults to :lend.
4051 Each in the following group may be a string, a function of one
4052 argument (the field or line) returning a string, or a plist
4053 mapping columns to either of the above:
4054 :lfmt Format for entire line, with enough %s to capture all fields.
4055 If this is present, :lstart, :lend, and :sep are ignored.
4056 :llfmt Format for the entire last line, defaults to :lfmt.
4057 :fmt A format to be used to wrap the field, should contain
4058 %s for the original field value. For example, to wrap
4059 everything in dollars, you could use :fmt \"$%s$\".
4060 This may also be a property list with column numbers and
4061 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4063 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4064 Same as above, specific for the header lines in the table.
4065 All lines before the first hline are treated as header.
4066 If any of these is not present, the data line value is used.
4068 This may be either a string or a function of two arguments:
4069 :efmt Use this format to print numbers with exponentials.
4070 The format should have %s twice for inserting mantissa
4071 and exponent, for example \"%s\\\\times10^{%s}\". This
4072 may also be a property list with column numbers and
4073 formats. :fmt will still be applied after :efmt.
4075 In addition to this, the parameters :skip and :skipcols are always handled
4076 directly by `orgtbl-send-table'. See manual."
4079 (let* ((splicep (plist-get params :splice))
4080 (hline (plist-get params :hline))
4081 (remove-nil-linesp (plist-get params :remove-nil-lines))
4082 (*orgtbl-hline* hline)
4083 (*orgtbl-table* table)
4084 (*orgtbl-sep* (plist-get params :sep))
4085 (*orgtbl-efmt* (plist-get params :efmt))
4086 (*orgtbl-lstart* (plist-get params :lstart))
4087 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4088 (*orgtbl-lend* (plist-get params :lend))
4089 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4090 (*orgtbl-lfmt* (plist-get params :lfmt))
4091 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4092 (*orgtbl-fmt* (plist-get params :fmt))
4097 (when (plist-member params :tstart)
4098 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4099 (if tstart (push tstart *orgtbl-rtn*)))))
4101 ;; Do we have a heading section? If so, format it and handle the
4103 (if (and (not splicep)
4104 (or (consp (car *orgtbl-table*))
4105 (consp (nth 1 *orgtbl-table*)))
4106 (memq 'hline (cdr *orgtbl-table*)))
4108 (when (eq 'hline (car *orgtbl-table*))
4109 ;; there is a hline before the first data line
4110 (and hline (push hline *orgtbl-rtn*))
4111 (pop *orgtbl-table*))
4112 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4114 (*orgtbl-llstart* (or (plist-get params :hllstart)
4116 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4117 (*orgtbl-llend* (or (plist-get params :hllend)
4118 (plist-get params :hlend) *orgtbl-llend*))
4119 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4120 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4121 (plist-get params :hlfmt) *orgtbl-llfmt*))
4122 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4123 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4124 (orgtbl-format-section 'hline))
4125 (if hline (push hline *orgtbl-rtn*))
4126 (pop *orgtbl-table*)))
4128 ;; Now format the main section.
4129 (orgtbl-format-section nil)
4132 (when (plist-member params :tend)
4133 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4134 (if tend (push tend *orgtbl-rtn*)))))
4136 (mapconcat 'identity (nreverse (if remove-nil-linesp
4137 (remq nil *orgtbl-rtn*)
4138 *orgtbl-rtn*)) "\n")))
4140 (defun orgtbl-to-tsv (table params)
4141 "Convert the orgtbl-mode table to TAB separated material."
4142 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4143 (defun orgtbl-to-csv (table params)
4144 "Convert the orgtbl-mode table to CSV material.
4145 This does take care of the proper quoting of fields with comma or quotes."
4146 (orgtbl-to-generic table (org-combine-plists
4147 '(:sep "," :fmt org-quote-csv-field)
4150 (defun orgtbl-to-latex (table params)
4151 "Convert the orgtbl-mode TABLE to LaTeX.
4152 TABLE is a list, each entry either the symbol `hline' for a horizontal
4153 separator line, or a list of fields for that line.
4154 PARAMS is a property list of parameters that can influence the conversion.
4155 Supports all parameters from `orgtbl-to-generic'. Most important for
4158 :splice When set to t, return only table body lines, don't wrap
4159 them into a tabular environment. Default is nil.
4161 :fmt A format to be used to wrap the field, should contain %s for the
4162 original field value. For example, to wrap everything in dollars,
4163 use :fmt \"$%s$\". This may also be a property list with column
4164 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4165 The format may also be a function that formats its one argument.
4167 :efmt Format for transforming numbers with exponentials. The format
4168 should have %s twice for inserting mantissa and exponent, for
4169 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4170 This may also be a property list with column numbers and formats.
4171 The format may also be a function that formats its two arguments.
4173 :llend If you find too much space below the last line of a table,
4174 pass a value of \"\" for :llend to suppress the final \\\\.
4176 The general parameters :skip and :skipcols have already been applied when
4177 this function is called."
4178 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4179 org-table-last-alignment ""))
4182 :tstart (concat "\\begin{tabular}{" alignment "}")
4183 :tend "\\end{tabular}"
4184 :lstart "" :lend " \\\\" :sep " & "
4185 :efmt "%s\\,(%s)" :hline "\\hline")))
4186 (orgtbl-to-generic table (org-combine-plists params2 params))))
4188 (defun orgtbl-to-html (table params)
4189 "Convert the orgtbl-mode TABLE to LaTeX.
4190 TABLE is a list, each entry either the symbol `hline' for a horizontal
4191 separator line, or a list of fields for that line.
4192 PARAMS is a property list of parameters that can influence the conversion.
4193 Currently this function recognizes the following parameters:
4195 :splice When set to t, return only table body lines, don't wrap
4196 them into a <table> environment. Default is nil.
4198 The general parameters :skip and :skipcols have already been applied when
4199 this function is called. The function does *not* use `orgtbl-to-generic',
4200 so you cannot specify parameters for it."
4201 (let* ((splicep (plist-get params :splice))
4202 (html-table-tag org-export-html-table-tag)
4204 ;; Just call the formatter we already have
4205 ;; We need to make text lines for it, so put the fields back together.
4206 (setq html (org-format-org-table-html
4211 (concat "| " (mapconcat 'identity x " | ") " |")))
4214 (if (string-match "\n+\\'" html)
4215 (setq html (replace-match "" t t html)))
4218 (defun orgtbl-to-texinfo (table params)
4219 "Convert the orgtbl-mode TABLE to TeXInfo.
4220 TABLE is a list, each entry either the symbol `hline' for a horizontal
4221 separator line, or a list of fields for that line.
4222 PARAMS is a property list of parameters that can influence the conversion.
4223 Supports all parameters from `orgtbl-to-generic'. Most important for
4226 :splice nil/t When set to t, return only table body lines, don't wrap
4227 them into a multitable environment. Default is nil.
4229 :fmt fmt A format to be used to wrap the field, should contain
4230 %s for the original field value. For example, to wrap
4231 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4232 This may also be a property list with column numbers and
4233 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4234 Each format also may be a function that formats its one
4237 :cf \"f1 f2..\" The column fractions for the table. By default these
4238 are computed automatically from the width of the columns
4241 The general parameters :skip and :skipcols have already been applied when
4242 this function is called."
4243 (let* ((total (float (apply '+ org-table-last-column-widths)))
4244 (colfrac (or (plist-get params :cf)
4246 (lambda (x) (format "%.3f" (/ (float x) total)))
4247 org-table-last-column-widths " ")))
4250 :tstart (concat "@multitable @columnfractions " colfrac)
4251 :tend "@end multitable"
4252 :lstart "@item " :lend "" :sep " @tab "
4253 :hlstart "@headitem ")))
4254 (orgtbl-to-generic table (org-combine-plists params2 params))))
4256 (defun orgtbl-to-orgtbl (table params)
4257 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4258 Useful when slicing one table into many. The :hline, :sep,
4259 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4260 and :tend suppress strings without splicing; they can be set to
4261 provide ORGTBL directives for the generated table."
4264 :tstart nil :tend nil
4269 (params (org-combine-plists params2 params)))
4270 (orgtbl-to-generic table params)))
4272 (defun org-table-get-remote-range (name-or-id form)
4273 "Get a field value or a list of values in a range from table at ID.
4275 NAME-OR-ID may be the name of a table in the current file as set by
4276 a \"#+TBLNAME:\" directive. The first table following this line
4277 will then be used. Alternatively, it may be an ID referring to
4278 any entry, also in a different file. In this case, the first table
4279 in that entry will be referenced.
4280 FORM is a field or range descriptor like \"@2$3\" or or \"B3\" or
4281 \"@I$2..@II$2\". All the references must be absolute, not relative.
4283 The return value is either a single string for a single field, or a
4284 list of the fields in the rectangle ."
4287 org-table-column-names org-table-column-name-regexp
4288 org-table-local-parameters org-table-named-field-locations
4289 org-table-current-line-types org-table-current-begin-line
4290 org-table-current-begin-pos org-table-dlines
4291 org-table-hlines org-table-last-alignment
4292 org-table-last-column-widths org-table-last-alignment
4293 org-table-last-column-widths tbeg
4295 (setq form (org-table-convert-refs-to-rc form))
4300 (goto-char (point-min))
4301 (if (re-search-forward
4302 (concat "^[ \t]*#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4304 (setq buffer (current-buffer) loc (match-beginning 0))
4305 (setq id-loc (org-id-find name-or-id 'marker))
4306 (unless (and id-loc (markerp id-loc))
4307 (error "Can't find remote table \"%s\"" name-or-id))
4308 (setq buffer (marker-buffer id-loc)
4309 loc (marker-position id-loc))
4310 (move-marker id-loc nil)))
4311 (switch-to-buffer buffer)
4317 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4318 (not (match-beginning 1)))
4319 (error "Cannot find a table at NAME or ID %s" name-or-id))
4320 (setq tbeg (point-at-bol))
4321 (org-table-get-specials)
4322 (setq form (org-table-formula-substitute-names form))
4323 (if (and (string-match org-table-range-regexp form)
4324 (> (length (match-string 0 form)) 1))
4326 (org-table-get-range (match-string 0 form) tbeg 1))
4329 (provide 'org-table)
4331 ;; arch-tag: 4d21cfdd-0268-440a-84b0-09237a0fe0ef
4333 ;;; org-table.el ends here