1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
29 ;; This file contains the table editor and spreadsheet for Org-mode.
31 ;; Watch out: Here we are talking about two different kind of tables.
32 ;; Most of the code is for the tables created with the Org-mode table editor.
33 ;; Sometimes, we talk about tables created and edited with the table.el
34 ;; Emacs package. We call the former org-type tables, and the latter
35 ;; table.el-type tables.
43 (declare-function org-table-clean-before-export
"org-exp"
44 (lines &optional maybe-quoted
))
45 (declare-function org-format-org-table-html
"org-html" (lines &optional splice
))
46 (defvar orgtbl-mode
) ; defined below
47 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
48 (defvar org-export-html-table-tag
) ; defined in org-exp.el
49 (defvar constants-unit-system
)
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'.
280 These can be overridden for a specific table by setting the
281 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
282 radio tables for the different export transformations and
283 available parameters."
284 :group
'org-table-import-export
287 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
288 "Detects a table line marked for automatic recalculation.")
289 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
290 "Detects a table line marked for automatic recalculation.")
291 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
292 "Detects a table line marked for automatic recalculation.")
293 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
294 "Searching from within a table (any type) this finds the first line outside the table.")
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 command.")
309 (defvar org-table-current-begin-line nil
310 "Table begin line, non-nil only for the duration of a command.")
311 (defvar org-table-current-begin-pos nil
312 "Table begin position, non-nil only for the duration of a command.")
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 (defun org-table-colgroup-line-p (line)
331 "Is this a table line colgroup information?"
333 (and (string-match "[<>]\\|&[lg]t;" line
)
334 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
340 (not (member s
'("" "<" ">" "<>" "<" ">" "<>"))))
341 (org-split-string (match-string 1 line
) "[ \t]*|[ \t]*")))))))
343 (defun org-table-cookie-line-p (line)
344 "Is this a table line with only alignment/width cookies?"
346 (and (string-match "[<>]\\|&[lg]t;" line
)
348 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line
)
349 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line
))
350 (not (delq nil
(mapcar
352 (not (or (equal s
"")
354 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s
)
356 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'"
358 (org-split-string (match-string 1 line
)
359 "[ \t]*|[ \t]*")))))))
361 (defconst org-table-translate-regexp
362 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
363 "Match a reference that needs translation, for reference display.")
365 (defun org-table-create-with-table.el
()
366 "Use the table.el package to insert a new table.
367 If there is already a table at point, convert between Org-mode tables
368 and table.el tables."
373 (if (y-or-n-p "Convert table to Org-mode table? ")
374 (org-table-convert)))
376 (when (y-or-n-p "Convert table to table.el table? ")
378 (org-table-convert)))
379 (t (call-interactively 'table-insert
))))
381 (defun org-table-create-or-convert-from-region (arg)
382 "Convert region to table, or create an empty table.
383 If there is an active region, convert it to a table, using the function
384 `org-table-convert-region'. See the documentation of that function
385 to learn how the prefix argument is interpreted to determine the field
387 If there is no such region, create an empty table with `org-table-create'."
389 (if (org-region-active-p)
390 (org-table-convert-region (region-beginning) (region-end) arg
)
391 (org-table-create arg
)))
393 (defun org-table-create (&optional size
)
394 "Query for a size and insert a table skeleton.
395 SIZE is a string Columns x Rows like for example \"3x2\"."
398 (setq size
(read-string
399 (concat "Table size Columns x Rows [e.g. "
400 org-table-default-size
"]: ")
401 "" nil org-table-default-size
)))
404 (indent (make-string (current-column) ?\
))
405 (split (org-split-string size
" *x *"))
406 (rows (string-to-number (nth 1 split
)))
407 (columns (string-to-number (car split
)))
408 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
410 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
411 (point-at-bol) (point)))
412 (beginning-of-line 1)
414 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
415 (dotimes (i rows
) (insert line
))
418 ;; Insert a hline after the first row.
425 (defun org-table-convert-region (beg0 end0
&optional separator
)
426 "Convert region to a table.
427 The region goes from BEG0 to END0, but these borders will be moved
428 slightly, to make sure a beginning of line in the first line is included.
430 SEPARATOR specifies the field separator in the lines. It can have the
433 '(4) Use the comma as a field separator
434 '(16) Use a TAB as field separator
435 integer When a number, use that many spaces as field separator
436 nil When nil, the command tries to be smart and figure out the
437 separator in the following way:
438 - when each line contains a TAB, assume TAB-separated material
439 - when each line contains a comma, assume CSV material
440 - else, assume one or more SPACE characters as separator."
442 (let* ((beg (min beg0 end0
))
443 (end (max beg0 end0
))
446 (beginning-of-line 1)
447 (setq beg
(move-marker (make-marker) (point)))
449 (if (bolp) (backward-char 1) (end-of-line 1))
450 (setq end
(move-marker (make-marker) (point)))
451 ;; Get the right field separator
456 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
457 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
460 (if (equal separator
'(4))
461 (while (< (point) end
)
462 ;; parse the csv stuff
464 ((looking-at "^") (insert "| "))
465 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
466 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
467 (replace-match "\\1")
468 (if (looking-at "\"") (insert "\"")))
469 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
470 ((looking-at "[ \t]*,") (replace-match " | "))
471 (t (beginning-of-line 2))))
473 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
474 ((equal separator
'(16)) "^\\|\t")
475 ((integerp separator
)
476 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
))
477 (t (error "This should not happen"))))
478 (while (re-search-forward re end t
)
479 (replace-match "| " t t
)))
483 (defun org-table-import (file arg
)
484 "Import FILE as a table.
485 The file is assumed to be tab-separated. Such files can be produced by most
486 spreadsheet and database applications. If no tabs (at least one per line)
487 are found, lines will be split on whitespace into fields."
489 (or (bolp) (newline))
492 (insert-file-contents file
)
493 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
496 (defvar org-table-last-alignment
)
497 (defvar org-table-last-column-widths
)
498 (defun org-table-export (&optional file format
)
499 "Export table to a file, with configurable format.
500 Such a file can be imported into a spreadsheet program like Excel.
501 FILE can be the output file name. If not given, it will be taken from
502 a TABLE_EXPORT_FILE property in the current entry or higher up in the
503 hierarchy, or the user will be prompted for a file name.
504 FORMAT can be an export format, of the same kind as it used when
505 `orgtbl-mode' sends a table in a different format. The default format can
506 be found in the variable `org-table-export-default-format', but the function
507 first checks if there is an export format specified in a TABLE_EXPORT_FORMAT
508 property, locally or anywhere up in the hierarchy."
510 (unless (org-at-table-p)
511 (error "No table at point"))
513 (org-table-align) ;; make sure we have everything we need
514 (let* ((beg (org-table-begin))
515 (end (org-table-end))
516 (txt (buffer-substring-no-properties beg end
))
519 (org-entry-get beg
"TABLE_EXPORT_FILE" t
)
523 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)
527 (setq file
(read-file-name "Export table to: "))
528 (unless (or (not (file-exists-p file
))
529 (y-or-n-p (format "Overwrite file %s? " file
)))
531 (if (file-directory-p file
)
532 (error "This is a directory path, not a file"))
533 (if (and (buffer-file-name)
534 (equal (file-truename file
)
535 (file-truename (buffer-file-name))))
536 (error "Please specify a file name that is different from current"))
538 (setq deffmt-readable org-table-export-default-format
)
539 (while (string-match "\t" deffmt-readable
)
540 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
541 (while (string-match "\n" deffmt-readable
)
542 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
543 (setq format
(org-completing-read
545 '("orgtbl-to-tsv" "orgtbl-to-csv"
546 "orgtbl-to-latex" "orgtbl-to-html"
547 "orgtbl-to-generic" "orgtbl-to-texinfo"
548 "orgtbl-to-orgtbl") nil nil
550 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
551 (let* ((transform (intern (match-string 1 format
)))
552 (params (if (match-end 2)
553 (read (concat "(" (match-string 2 format
) ")"))))
554 (skip (plist-get params
:skip
))
555 (skipcols (plist-get params
:skipcols
))
556 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
557 (lines (org-table-clean-before-export lines
))
558 (i0 (if org-table-clean-did-remove-column
2 1))
561 (if (string-match org-table-hline-regexp x
)
564 (org-split-string (org-trim x
) "\\s-*|\\s-*")
567 (fun (if (= i0
2) 'cdr
'identity
))
568 (org-table-last-alignment
569 (org-remove-by-index (funcall fun org-table-last-alignment
)
571 (org-table-last-column-widths
572 (org-remove-by-index (funcall fun org-table-last-column-widths
)
575 (unless (fboundp transform
)
576 (error "No such transformation function %s" transform
))
577 (setq txt
(funcall transform table params
))
579 (with-current-buffer (find-file-noselect file
)
580 (setq buf
(current-buffer))
586 (message "Export done."))
587 (error "TABLE_EXPORT_FORMAT invalid"))))
589 (defvar org-table-aligned-begin-marker
(make-marker)
590 "Marker at the beginning of the table last aligned.
591 Used to check if cursor still is in that table, to minimize realignment.")
592 (defvar org-table-aligned-end-marker
(make-marker)
593 "Marker at the end of the table last aligned.
594 Used to check if cursor still is in that table, to minimize realignment.")
595 (defvar org-table-last-alignment nil
596 "List of flags for flushright alignment, from the last re-alignment.
597 This is being used to correctly align a single field after TAB or RET.")
598 (defvar org-table-last-column-widths nil
599 "List of max width of fields in each column.
600 This is being used to correctly align a single field after TAB or RET.")
601 (defvar org-table-formula-debug nil
602 "Non-nil means debug table formulas.
603 When nil, simply write \"#ERROR\" in corrupted fields.")
604 (make-variable-buffer-local 'org-table-formula-debug
)
605 (defvar org-table-overlay-coordinates nil
606 "Overlay coordinates after each align of a table.")
607 (make-variable-buffer-local 'org-table-overlay-coordinates
)
609 (defvar org-last-recalc-line nil
)
610 (defvar org-table-do-narrow t
) ; for dynamic scoping
611 (defconst org-narrow-column-arrow
"=>"
612 "Used as display property in narrowed table columns.")
614 (defun org-table-align ()
615 "Align the table at point by aligning all vertical bars."
619 (beg (org-table-begin))
620 (end (org-table-end))
621 ;; Current cursor position
622 (linepos (org-current-line))
623 (colpos (org-table-current-column))
624 (winstart (window-start))
625 (winstartline (org-current-line (min winstart
(1- (point-max)))))
626 lines
(new "") lengths l typenums ty fields maxfields i
634 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
636 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
637 emptystrings links dates emph raise narrow
638 falign falign1 fmax f1 len c e space
)
640 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
641 ;; Check if we have links or dates
643 (setq links
(re-search-forward org-bracket-link-regexp end t
))
645 (setq emph
(and org-hide-emphasis-markers
646 (re-search-forward org-emph-re end t
)))
648 (setq raise
(and org-use-sub-superscripts
649 (re-search-forward org-match-substring-regexp end t
)))
651 (setq dates
(and org-display-custom-times
652 (re-search-forward org-ts-regexp-both end t
)))
653 ;; Make sure the link properties are right
654 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
655 ;; Make sure the date properties are right
656 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
657 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
658 (when raise
(goto-char beg
) (while (org-raise-scripts end
)))
660 ;; Check if we are narrowing any columns
662 (setq narrow
(and org-table-do-narrow
663 org-format-transports-properties-p
664 (re-search-forward "<[lrc]?[0-9]+>" end t
)))
666 (setq falign
(re-search-forward "<[lrc][0-9]*>" end t
))
669 (setq lines
(org-split-string
670 (buffer-substring beg end
) "\n"))
671 ;; Store the indentation of the first line
672 (if (string-match "^ *" (car lines
))
673 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
674 ;; Mark the hlines by setting the corresponding element to nil
675 ;; At the same time, we remove trailing space.
676 (setq lines
(mapcar (lambda (l)
677 (if (string-match "^ *|-" l
)
679 (if (string-match "[ \t]+$" l
)
680 (substring l
0 (match-beginning 0))
683 ;; Get the data fields by splitting the lines.
686 (org-split-string l
" *| *"))
687 (delq nil
(copy-sequence lines
))))
688 ;; How many fields in the longest line?
690 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
692 (kill-region beg end
)
693 (org-table-create org-table-default-size
)
694 (error "Empty table - created default table")))
695 ;; A list of empty strings to fill any short rows on output
696 (setq emptystrings
(make-list maxfields
""))
697 ;; Check for special formatting.
699 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
700 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
701 ;; Check if there is an explicit width specified
703 (when (or narrow falign
)
704 (setq c column fmax nil falign1 nil
)
707 (when (and (stringp e
) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e
))
708 (if (match-end 1) (setq falign1
(match-string 1 e
)))
709 (if (and org-table-do-narrow
(match-end 2))
710 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
711 ;; Find fields that are wider than fmax, and shorten them
713 (loop for xx in column do
714 (when (and (stringp xx
)
715 (> (org-string-width xx
) fmax
))
716 (org-add-props xx nil
718 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
719 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
721 (error "Cannot narrow field starting with wide link \"%s\""
722 (match-string 0 xx
)))
723 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
724 (add-text-properties (- f1
2) f1
725 (list 'display org-narrow-column-arrow
)
727 ;; Get the maximum width for each column
728 (push (apply 'max
(or fmax
1) 1 (mapcar 'org-string-width column
))
730 ;; Get the fraction of numbers, to decide about alignment of the column
732 (push (equal (downcase falign1
) "r") typenums
)
733 (setq cnt
0 frac
0.0)
734 (loop for x in column do
737 (setq frac
( / (+ (* frac cnt
)
738 (if (string-match org-table-number-regexp x
) 1 0))
739 (setq cnt
(1+ cnt
))))))
740 (push (>= frac org-table-number-fraction
) typenums
)))
741 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
743 ;; Store the alignment of this table, for later editing of single fields
744 (setq org-table-last-alignment typenums
745 org-table-last-column-widths lengths
)
747 ;; With invisible characters, `format' does not get the field width right
748 ;; So we need to make these fields wide by hand.
749 (when (or links emph raise
)
750 (loop for i from
0 upto
(1- maxfields
) do
751 (setq len
(nth i lengths
))
752 (loop for j from
0 upto
(1- (length fields
)) do
753 (setq c
(nthcdr i
(car (nthcdr j fields
))))
754 (if (and (stringp (car c
))
755 (or (text-property-any 0 (length (car c
))
756 'invisible
'org-link
(car c
))
757 (text-property-any 0 (length (car c
))
758 'org-dwidth t
(car c
)))
759 (< (org-string-width (car c
)) len
))
761 (setq space
(make-string (- len
(org-string-width (car c
))) ?\
))
762 (setcar c
(if (nth i typenums
)
763 (concat space
(car c
))
764 (concat (car c
) space
))))))))
766 ;; Compute the formats needed for output of the table
767 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
768 (while (setq l
(pop lengths
))
769 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
770 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
771 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
772 (setq rfmt
(concat rfmt
"\n")
773 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
777 (if l
(apply 'format rfmt
778 (append (pop fields
) emptystrings
))
781 (if (equal (char-before) ?
\n)
782 ;; This hack is for org-indent, to force redisplay of the
783 ;; line prefix of the first line. Apparently the redisplay
784 ;; is tied to the newline, which is, I think, a bug.
785 ;; To force this redisplay, we remove and re-insert the
786 ;; newline, so that the redisplay engine thinks it belongs
787 ;; to the changed text.
789 (backward-delete-char 1)
791 (move-marker org-table-aligned-begin-marker
(point))
793 ;; Replace the old one
794 (delete-region (point) end
)
795 (move-marker end nil
)
796 (move-marker org-table-aligned-end-marker
(point))
797 (when (and orgtbl-mode
(not (org-mode-p)))
798 (goto-char org-table-aligned-begin-marker
)
799 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
800 ;; Try to move to the old location
801 (org-goto-line winstartline
)
802 (setq winstart
(point-at-bol))
803 (org-goto-line linepos
)
804 (set-window-start (selected-window) winstart
'noforce
)
805 (org-table-goto-column colpos
)
806 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
807 (setq org-table-may-need-update nil
)
810 (defun org-table-begin (&optional table-type
)
811 "Find the beginning of the table and return its position.
812 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
814 (if (not (re-search-backward
815 (if table-type org-table-any-border-regexp
816 org-table-border-regexp
)
818 (progn (goto-char (point-min)) (point))
819 (goto-char (match-beginning 0))
820 (beginning-of-line 2)
823 (defun org-table-end (&optional table-type
)
824 "Find the end of the table and return its position.
825 With argument TABLE-TYPE, go to the end of a table.el-type table."
827 (if (not (re-search-forward
828 (if table-type org-table-any-border-regexp
829 org-table-border-regexp
)
831 (goto-char (point-max))
832 (goto-char (match-beginning 0)))
835 (defun org-table-justify-field-maybe (&optional new
)
836 "Justify the current field, text to left, number to right.
837 Optional argument NEW may specify text to replace the current field content."
839 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
840 ((org-at-table-hline-p))
842 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
844 (< (point) org-table-aligned-begin-marker
)
845 (>= (point) org-table-aligned-end-marker
)))
846 ;; This is not the same table, force a full re-align
847 (setq org-table-may-need-update t
))
848 (t ;; realign the current field, based on previous full realign
849 (let* ((pos (point)) s
850 (col (org-table-current-column))
851 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
854 (skip-chars-backward "^|\n")
855 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
857 (setq s
(match-string 1)
859 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
860 e
(not (= (match-beginning 2) (match-end 2))))
861 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
862 l
(if e
"|" (setq org-table-may-need-update t
) ""))
865 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
866 (setq n
(format f new
))
867 (setq n
(concat new
"|") org-table-may-need-update t
)))
868 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
870 (let (org-table-may-need-update)
871 (replace-match n t t
))))
872 (setq org-table-may-need-update t
))
875 (defun org-table-next-field ()
876 "Go to the next field in the current table, creating new lines as needed.
877 Before doing so, re-align the table if necessary."
879 (org-table-maybe-eval-formula)
880 (org-table-maybe-recalculate-line)
881 (if (and org-table-automatic-realign
882 org-table-may-need-update
)
884 (let ((end (org-table-end)))
885 (if (org-at-table-hline-p)
889 (re-search-forward "|" end
)
890 (if (looking-at "[ \t]*$")
891 (re-search-forward "|" end
))
892 (if (and (looking-at "-")
893 org-table-tab-jumps-over-hlines
894 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
895 (goto-char (match-beginning 1)))
898 (beginning-of-line 0)
899 (org-table-insert-row 'below
))
900 (if (looking-at " ") (forward-char 1))))
902 (org-table-insert-row 'below
)))))
904 (defun org-table-previous-field ()
905 "Go to the previous field in the table.
906 Before doing so, re-align the table if necessary."
908 (org-table-justify-field-maybe)
909 (org-table-maybe-recalculate-line)
910 (if (and org-table-automatic-realign
911 org-table-may-need-update
)
913 (if (org-at-table-hline-p)
917 (re-search-backward "|" (org-table-begin))
918 (re-search-backward "|" (org-table-begin)))
919 (error (error "Cannot move to previous table field")))
920 (while (looking-at "|\\(-\\|[ \t]*$\\)")
921 (re-search-backward "|" (org-table-begin)))
922 (if (looking-at "| ?")
923 (goto-char (match-end 0))))
925 (defun org-table-beginning-of-field (&optional n
)
926 "Move to the end of the current table field.
927 If already at or after the end, move to the end of the next table field.
928 With numeric argument N, move N-1 fields forward first."
933 (org-table-previous-field))
934 (if (not (re-search-backward "|" (point-at-bol 0) t
))
935 (error "No more table fields before the current")
936 (goto-char (match-end 0))
937 (and (looking-at " ") (forward-char 1)))
938 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
940 (defun org-table-end-of-field (&optional n
)
941 "Move to the beginning of the current table field.
942 If already at or before the beginning, move to the beginning of the
944 With numeric argument N, move N-1 fields backward first."
949 (org-table-next-field))
950 (when (re-search-forward "|" (point-at-eol 1) t
)
952 (skip-chars-backward " ")
953 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
955 (if (<= (point) pos
) (org-table-end-of-field 2))))
957 (defun org-table-next-row ()
958 "Go to the next row (same column) in the current table.
959 Before doing so, re-align the table if necessary."
961 (org-table-maybe-eval-formula)
962 (org-table-maybe-recalculate-line)
963 (if (or (looking-at "[ \t]*$")
964 (save-excursion (skip-chars-backward " \t") (bolp)))
966 (if (and org-table-automatic-realign
967 org-table-may-need-update
)
969 (let ((col (org-table-current-column)))
970 (beginning-of-line 2)
971 (if (or (not (org-at-table-p))
972 (org-at-table-hline-p))
974 (beginning-of-line 0)
975 (org-table-insert-row 'below
)))
976 (org-table-goto-column col
)
977 (skip-chars-backward "^|\n\r")
978 (if (looking-at " ") (forward-char 1)))))
980 (defun org-table-copy-down (n)
981 "Copy a field down in the current column.
982 If the field at the cursor is empty, copy into it the content of the nearest
983 non-empty field above. With argument N, use the Nth non-empty field.
984 If the current field is not empty, it is copied down to the next row, and
985 the cursor is moved with it. Therefore, repeating this command causes the
986 column to be filled row-by-row.
987 If the variable `org-table-copy-increment' is non-nil and the field is an
988 integer or a timestamp, it will be incremented while copying. In the case of
989 a timestamp, if the cursor is on the year, change the year. If it is on the
990 month or the day, change that. Point will stay on the current date field
991 in order to easily repeat the interval."
993 (let* ((colpos (org-table-current-column))
994 (col (current-column))
995 (field (org-table-get-field))
996 (non-empty (string-match "[^ \t]" field
))
997 (beg (org-table-begin))
1000 (org-table-check-inside-data-field)
1003 (setq txt
(org-trim field
))
1004 (org-table-next-row)
1005 (org-table-blank-field))
1009 (while (progn (beginning-of-line 1)
1010 (re-search-backward org-table-dataline-regexp
1012 (org-table-goto-column colpos t
)
1013 (if (and (looking-at
1014 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1015 (<= (setq n
(1- n
)) 0))
1016 (throw 'exit
(match-string 1))))))))
1019 (if (and org-table-copy-increment
1020 (not (equal orig-n
0))
1021 (string-match "^[0-9]+$" txt
)
1022 (< (string-to-number txt
) 100000000))
1023 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
1025 (org-move-to-column col
)
1026 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1027 (org-timestamp-up-day)
1028 (org-table-maybe-recalculate-line))
1030 (org-move-to-column col
))
1031 (error "No non-empty field found"))))
1033 (defun org-table-check-inside-data-field ()
1034 "Is point inside a table data field?
1035 I.e. not on a hline or before the first or after the last column?
1036 This actually throws an error, so it aborts the current command."
1037 (if (or (not (org-at-table-p))
1038 (= (org-table-current-column) 0)
1039 (org-at-table-hline-p)
1040 (looking-at "[ \t]*$"))
1041 (error "Not in table data field")))
1043 (defvar org-table-clip nil
1044 "Clipboard for table regions.")
1046 (defun org-table-get (line column
)
1047 "Get the field in table line LINE, column COLUMN.
1048 If LINE is larger than the number of data lines in the table, the function
1049 returns nil. However, if COLUMN is too large, we will simply return an
1051 If LINE is nil, use the current line.
1052 If column is nil, use the current column."
1053 (setq column
(or column
(org-table-current-column)))
1055 (and (or (not line
) (org-table-goto-line line
))
1056 (org-trim (org-table-get-field column
)))))
1058 (defun org-table-put (line column value
&optional align
)
1059 "Put VALUE into line LINE, column COLUMN.
1060 When ALIGN is set, also realign the table."
1061 (setq column
(or column
(org-table-current-column)))
1062 (prog1 (save-excursion
1063 (and (or (not line
) (org-table-goto-line line
))
1064 (progn (org-table-goto-column column nil
'force
) t
)
1065 (org-table-get-field column value
)))
1066 (and align
(org-table-align))))
1068 (defun org-table-current-line ()
1069 "Return the index of the current data line."
1070 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1072 (goto-char (org-table-begin))
1073 (while (and (re-search-forward org-table-dataline-regexp end t
)
1075 (< (point-at-eol) pos
))))
1078 (defun org-table-goto-line (N)
1079 "Go to the Nth data line in the current table.
1080 Return t when the line exists, nil if it does not exist."
1081 (goto-char (org-table-begin))
1082 (let ((end (org-table-end)) (cnt 0))
1083 (while (and (re-search-forward org-table-dataline-regexp end t
)
1084 (< (setq cnt
(1+ cnt
)) N
)))
1087 (defun org-table-blank-field ()
1088 "Blank the current table field or active region."
1090 (org-table-check-inside-data-field)
1091 (if (and (interactive-p) (org-region-active-p))
1092 (let (org-table-clip)
1093 (org-table-cut-region (region-beginning) (region-end)))
1094 (skip-chars-backward "^|")
1096 (if (looking-at "|[^|\n]+")
1097 (let* ((pos (match-beginning 0))
1098 (match (match-string 0))
1099 (len (org-string-width match
)))
1100 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1101 (goto-char (+ 2 pos
))
1102 (substring match
1)))))
1104 (defun org-table-get-field (&optional n replace
)
1105 "Return the value of the field in column N of current row.
1106 N defaults to current field.
1107 If REPLACE is a string, replace field with this value. The return value
1108 is always the old value."
1109 (and n
(org-table-goto-column n
))
1110 (skip-chars-backward "^|\n")
1112 (if (looking-at "|[^|\r\n]*")
1113 (let* ((pos (match-beginning 0))
1114 (val (buffer-substring (1+ pos
) (match-end 0))))
1116 (replace-match (concat "|" replace
) t t
))
1117 (goto-char (min (point-at-eol) (+ 2 pos
)))
1119 (forward-char 1) ""))
1121 (defun org-table-field-info (arg)
1122 "Show info about the current field, and highlight any reference at point."
1124 (org-table-get-specials)
1126 (let* ((pos (point))
1127 (col (org-table-current-column))
1128 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1129 (name (car (rassoc (list (org-current-line) col
)
1130 org-table-named-field-locations
)))
1131 (eql (org-table-get-stored-formulas))
1132 (dline (org-table-current-dline))
1133 (ref (format "@%d$%d" dline col
))
1134 (ref1 (org-table-convert-refs-to-an ref
))
1135 (fequation (or (assoc name eql
) (assoc ref eql
)))
1136 (cequation (assoc (int-to-string col
) eql
))
1137 (eqn (or fequation cequation
)))
1140 (org-table-show-reference 'local
)
1142 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1144 (if cname
(concat " or $" cname
) "")
1146 (if name
(concat " or $" name
) "")
1147 ;; FIXME: formula info not correct if special table line
1149 (concat ", formula: "
1150 (org-table-formula-to-user
1152 (if (string-match "^[$@]"(car eqn
)) "" "$")
1153 (car eqn
) "=" (cdr eqn
))))
1156 (defun org-table-current-column ()
1157 "Find out which column we are in."
1159 (if (interactive-p) (org-table-check-inside-data-field))
1161 (let ((cnt 0) (pos (point)))
1162 (beginning-of-line 1)
1163 (while (search-forward "|" pos t
)
1164 (setq cnt
(1+ cnt
)))
1165 (if (interactive-p) (message "In table column %d" cnt
))
1168 (defun org-table-current-dline ()
1169 "Find out what table data line we are in.
1170 Only data lines count for this."
1172 (if (interactive-p) (org-table-check-inside-data-field))
1174 (let ((cnt 0) (pos (point)))
1175 (goto-char (org-table-begin))
1176 (while (<= (point) pos
)
1177 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1178 (beginning-of-line 2))
1179 (if (interactive-p) (message "This is table line %d" cnt
))
1182 (defun org-table-goto-column (n &optional on-delim force
)
1183 "Move the cursor to the Nth column in the current table line.
1184 With optional argument ON-DELIM, stop with point before the left delimiter
1186 If there are less than N fields, just go to after the last delimiter.
1187 However, when FORCE is non-nil, create new columns if necessary."
1189 (beginning-of-line 1)
1191 (while (and (> (setq n
(1- n
)) -
1)
1192 (or (search-forward "|" (point-at-eol) t
)
1194 (progn (end-of-line 1)
1195 (skip-chars-backward "^|")
1198 (when (and force
(not (looking-at ".*|")))
1199 (save-excursion (end-of-line 1) (insert " | ")))
1202 (if (looking-at " ") (forward-char 1)))))
1204 (defun org-table-insert-column ()
1205 "Insert a new column into the table."
1207 (if (not (org-at-table-p))
1208 (error "Not at a table"))
1209 (org-table-find-dataline)
1210 (let* ((col (max 1 (org-table-current-column)))
1211 (beg (org-table-begin))
1212 (end (org-table-end))
1213 ;; Current cursor position
1214 (linepos (org-current-line))
1217 (while (< (point) end
)
1218 (if (org-at-table-hline-p)
1220 (org-table-goto-column col t
)
1222 (beginning-of-line 2))
1223 (move-marker end nil
)
1224 (org-goto-line linepos
)
1225 (org-table-goto-column colpos
)
1227 (org-table-fix-formulas "$" nil
(1- col
) 1)
1228 (org-table-fix-formulas "$LR" nil
(1- col
) 1)))
1230 (defun org-table-find-dataline ()
1231 "Find a data line in the current table, which is needed for column commands."
1232 (if (and (org-at-table-p)
1233 (not (org-at-table-hline-p)))
1235 (let ((col (current-column))
1236 (end (org-table-end)))
1237 (org-move-to-column col
)
1238 (while (and (< (point) end
)
1239 (or (not (= (current-column) col
))
1240 (org-at-table-hline-p)))
1241 (beginning-of-line 2)
1242 (org-move-to-column col
))
1243 (if (and (org-at-table-p)
1244 (not (org-at-table-hline-p)))
1247 "Please position cursor in a data line for column operations")))))
1249 (defun org-table-delete-column ()
1250 "Delete a column from the table."
1252 (if (not (org-at-table-p))
1253 (error "Not at a table"))
1254 (org-table-find-dataline)
1255 (org-table-check-inside-data-field)
1256 (let* ((col (org-table-current-column))
1257 (beg (org-table-begin))
1258 (end (org-table-end))
1259 ;; Current cursor position
1260 (linepos (org-current-line))
1263 (while (< (point) end
)
1264 (if (org-at-table-hline-p)
1266 (org-table-goto-column col t
)
1267 (and (looking-at "|[^|\n]+|")
1268 (replace-match "|")))
1269 (beginning-of-line 2))
1270 (move-marker end nil
)
1271 (org-goto-line linepos
)
1272 (org-table-goto-column colpos
)
1274 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1276 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1279 (defun org-table-move-column-right ()
1280 "Move column to the right."
1282 (org-table-move-column nil
))
1283 (defun org-table-move-column-left ()
1284 "Move column to the left."
1286 (org-table-move-column 'left
))
1288 (defun org-table-move-column (&optional left
)
1289 "Move the current column to the right. With arg LEFT, move to the left."
1291 (if (not (org-at-table-p))
1292 (error "Not at a table"))
1293 (org-table-find-dataline)
1294 (org-table-check-inside-data-field)
1295 (let* ((col (org-table-current-column))
1296 (col1 (if left
(1- col
) col
))
1297 (beg (org-table-begin))
1298 (end (org-table-end))
1299 ;; Current cursor position
1300 (linepos (org-current-line))
1301 (colpos (if left
(1- col
) (1+ col
))))
1302 (if (and left
(= col
1))
1303 (error "Cannot move column further left"))
1304 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1305 (error "Cannot move column further right"))
1307 (while (< (point) end
)
1308 (if (org-at-table-hline-p)
1310 (org-table-goto-column col1 t
)
1311 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1312 (replace-match "|\\2|\\1|")))
1313 (beginning-of-line 2))
1314 (move-marker end nil
)
1315 (org-goto-line linepos
)
1316 (org-table-goto-column colpos
)
1318 (org-table-fix-formulas
1319 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1320 (cons (number-to-string colpos
) (number-to-string col
))))
1321 (org-table-fix-formulas
1322 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1323 (cons (number-to-string colpos
) (number-to-string col
))))))
1325 (defun org-table-move-row-down ()
1326 "Move table row down."
1328 (org-table-move-row nil
))
1329 (defun org-table-move-row-up ()
1330 "Move table row up."
1332 (org-table-move-row 'up
))
1334 (defun org-table-move-row (&optional up
)
1335 "Move the current table line down. With arg UP, move it up."
1337 (let* ((col (current-column))
1339 (hline1p (save-excursion (beginning-of-line 1)
1340 (looking-at org-table-hline-regexp
)))
1341 (dline1 (org-table-current-dline))
1342 (dline2 (+ dline1
(if up -
1 1)))
1345 (beginning-of-line tonew
)
1346 (unless (org-at-table-p)
1348 (error "Cannot move row further"))
1349 (setq hline2p
(looking-at org-table-hline-regexp
))
1351 (beginning-of-line 1)
1353 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1354 (delete-region (point) (1+ (point-at-eol)))
1355 (beginning-of-line tonew
)
1357 (beginning-of-line 0)
1358 (org-move-to-column col
)
1359 (unless (or hline1p hline2p
)
1360 (org-table-fix-formulas
1361 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1362 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1364 (defun org-table-insert-row (&optional arg
)
1365 "Insert a new row above the current line into the table.
1366 With prefix ARG, insert below the current line."
1368 (if (not (org-at-table-p))
1369 (error "Not at a table"))
1370 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1371 (new (org-table-clean-line line
)))
1372 ;; Fix the first field if necessary
1373 (if (string-match "^[ \t]*| *[#$] *|" line
)
1374 (setq new
(replace-match (match-string 0 line
) t t new
)))
1375 (beginning-of-line (if arg
2 1))
1376 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1377 (beginning-of-line 0)
1378 (re-search-forward "| ?" (point-at-eol) t
)
1379 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1381 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1)))
1383 (defun org-table-insert-hline (&optional above
)
1384 "Insert a horizontal-line below the current line into the table.
1385 With prefix ABOVE, insert above the current line."
1387 (if (not (org-at-table-p))
1388 (error "Not at a table"))
1389 (when (eobp) (insert "\n") (backward-char 1))
1390 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1392 (let ((line (org-table-clean-line
1393 (buffer-substring (point-at-bol) (point-at-eol))))
1394 (col (current-column)))
1395 (while (string-match "|\\( +\\)|" line
)
1396 (setq line
(replace-match
1397 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1398 ?-
) "|") t t line
)))
1399 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1400 (beginning-of-line (if above
1 2))
1402 (beginning-of-line (if above
1 -
1))
1403 (org-move-to-column col
)
1404 (and org-table-overlay-coordinates
(org-table-align))))
1406 (defun org-table-hline-and-move (&optional same-column
)
1407 "Insert a hline and move to the row below that line."
1409 (let ((col (org-table-current-column)))
1410 (org-table-maybe-eval-formula)
1411 (org-table-maybe-recalculate-line)
1412 (org-table-insert-hline)
1414 (if (looking-at "\n[ \t]*|-")
1415 (progn (insert "\n|") (org-table-align))
1416 (org-table-next-field))
1417 (if same-column
(org-table-goto-column col
))))
1419 (defun org-table-clean-line (s)
1420 "Convert a table line S into a string with only \"|\" and space.
1421 In particular, this does handle wide and invisible characters."
1422 (if (string-match "^[ \t]*|-" s
)
1423 ;; It's a hline, just map the characters
1424 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1425 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1426 (setq s
(replace-match
1427 (concat "|" (make-string (org-string-width (match-string 1 s
))
1432 (defun org-table-kill-row ()
1433 "Delete the current row or horizontal line from the table."
1435 (if (not (org-at-table-p))
1436 (error "Not at a table"))
1437 (let ((col (current-column))
1438 (dline (org-table-current-dline)))
1439 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1440 (if (not (org-at-table-p)) (beginning-of-line 0))
1441 (org-move-to-column col
)
1442 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1445 (defun org-table-sort-lines (with-case &optional sorting-type
)
1446 "Sort table lines according to the column at point.
1448 The position of point indicates the column to be used for
1449 sorting, and the range of lines is the range between the nearest
1450 horizontal separator lines, or the entire table of no such lines
1451 exist. If point is before the first column, you will be prompted
1452 for the sorting column. If there is an active region, the mark
1453 specifies the first line and the sorting column, while point
1454 should be in the last line to be included into the sorting.
1456 The command then prompts for the sorting type which can be
1457 alphabetically, numerically, or by time (as given in a time stamp
1458 in the field). Sorting in reverse order is also possible.
1460 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1462 If SORTING-TYPE is specified when this function is called from a Lisp
1463 program, no prompting will take place. SORTING-TYPE must be a character,
1464 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1465 should be done in reverse order."
1467 (let* ((thisline (org-current-line))
1468 (thiscol (org-table-current-column))
1469 beg end bcol ecol tend tbeg column lns pos
)
1470 (when (equal thiscol
0)
1474 (read-string "Use column N for sorting: ")))
1476 (org-table-goto-column thiscol
))
1477 (org-table-check-inside-data-field)
1478 (if (org-region-active-p)
1480 (setq beg
(region-beginning) end
(region-end))
1482 (setq column
(org-table-current-column)
1485 (setq end
(point-at-bol 2)))
1486 (setq column
(org-table-current-column)
1488 tbeg
(org-table-begin)
1489 tend
(org-table-end))
1490 (if (re-search-backward org-table-hline-regexp tbeg t
)
1491 (setq beg
(point-at-bol 2))
1493 (setq beg
(point-at-bol 1)))
1495 (if (re-search-forward org-table-hline-regexp tend t
)
1496 (setq end
(point-at-bol 1))
1498 (setq end
(point-at-bol))))
1499 (setq beg
(move-marker (make-marker) beg
)
1500 end
(move-marker (make-marker) end
))
1503 (org-table-goto-column column
)
1504 (skip-chars-backward "^|")
1505 (setq bcol
(current-column))
1506 (org-table-goto-column (1+ column
))
1507 (skip-chars-backward "^|")
1508 (setq ecol
(1- (current-column)))
1509 (org-table-goto-column column
)
1510 (setq lns
(mapcar (lambda(x) (cons
1511 (org-sort-remove-invisible
1513 (org-split-string x
"[ \t]*|[ \t]*")))
1515 (org-split-string (buffer-substring beg end
) "\n")))
1516 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1517 (delete-region beg end
)
1518 (move-marker beg nil
)
1519 (move-marker end nil
)
1520 (insert (mapconcat 'cdr lns
"\n") "\n")
1521 (org-goto-line thisline
)
1522 (org-table-goto-column thiscol
)
1523 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1526 (defun org-table-cut-region (beg end
)
1527 "Copy region in table to the clipboard and blank all relevant fields.
1528 If there is no active region, use just the field at point."
1530 (if (org-region-active-p) (region-beginning) (point))
1531 (if (org-region-active-p) (region-end) (point))))
1532 (org-table-copy-region beg end
'cut
))
1534 (defun org-table-copy-region (beg end
&optional cut
)
1535 "Copy rectangular region in table to clipboard.
1536 A special clipboard is used which can only be accessed
1537 with `org-table-paste-rectangle'."
1539 (if (org-region-active-p) (region-beginning) (point))
1540 (if (org-region-active-p) (region-end) (point))
1541 current-prefix-arg
))
1542 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1544 (rpl (if cut
" " nil
)))
1546 (org-table-check-inside-data-field)
1547 (setq l01
(org-current-line)
1548 c01
(org-table-current-column))
1550 (org-table-check-inside-data-field)
1551 (setq l02
(org-current-line)
1552 c02
(org-table-current-column))
1553 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1554 c1
(min c01 c02
) c2
(max c01 c02
))
1558 (if (> l1 l2
) (throw 'exit t
))
1560 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1561 (setq cols nil ic1 c1 ic2 c2
)
1562 (while (< ic1
(1+ ic2
))
1563 (push (org-table-get-field ic1 rpl
) cols
)
1564 (setq ic1
(1+ ic1
)))
1565 (push (nreverse cols
) region
)
1566 (setq l1
(1+ l1
)))))
1567 (setq org-table-clip
(nreverse region
))
1568 (if cut
(org-table-align))
1571 (defun org-table-paste-rectangle ()
1572 "Paste a rectangular region into a table.
1573 The upper right corner ends up in the current field. All involved fields
1574 will be overwritten. If the rectangle does not fit into the present table,
1575 the table is enlarged as needed. The process ignores horizontal separator
1578 (unless (and org-table-clip
(listp org-table-clip
))
1579 (error "First cut/copy a region to paste!"))
1580 (org-table-check-inside-data-field)
1581 (let* ((clip org-table-clip
)
1582 (line (org-current-line))
1583 (col (org-table-current-column))
1584 (org-enable-table-editor t
)
1585 (org-table-automatic-realign nil
)
1587 (while (setq cols
(pop clip
))
1588 (while (org-at-table-hline-p) (beginning-of-line 2))
1589 (if (not (org-at-table-p))
1590 (progn (end-of-line 0) (org-table-next-field)))
1592 (while (setq field
(pop cols
))
1593 (org-table-goto-column c nil
'force
)
1594 (org-table-get-field nil field
)
1596 (beginning-of-line 2))
1597 (org-goto-line line
)
1598 (org-table-goto-column col
)
1601 (defun org-table-convert ()
1602 "Convert from `org-mode' table to table.el and back.
1603 Obviously, this only works within limits. When an Org-mode table is
1604 converted to table.el, all horizontal separator lines get lost, because
1605 table.el uses these as cell boundaries and has no notion of horizontal lines.
1606 A table.el table can be converted to an Org-mode table only if it does not
1607 do row or column spanning. Multiline cells will become multiple cells.
1608 Beware, Org-mode does not test if the table can be successfully converted - it
1609 blindly applies a recipe that works for simple tables."
1612 (if (org-at-table.el-p
)
1613 ;; convert to Org-mode table
1614 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1615 (end (move-marker (make-marker) (org-table-end t
))))
1616 (table-unrecognize-region beg end
)
1618 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1621 (if (org-at-table-p)
1622 ;; convert to table.el table
1623 (let ((beg (move-marker (make-marker) (org-table-begin)))
1624 (end (move-marker (make-marker) (org-table-end))))
1625 ;; first, get rid of all horizontal lines
1627 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1629 ;; insert a hline before first
1631 (org-table-insert-hline 'above
)
1632 (beginning-of-line -
1)
1633 ;; insert a hline after each line
1634 (while (progn (beginning-of-line 3) (< (point) end
))
1635 (org-table-insert-hline))
1637 (setq end
(move-marker end
(org-table-end)))
1638 ;; replace "+" at beginning and ending of hlines
1639 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1640 (replace-match "\\1+-"))
1642 (while (re-search-forward "-|[ \t]*$" end t
)
1643 (replace-match "-+"))
1646 (defun org-table-wrap-region (arg)
1647 "Wrap several fields in a column like a paragraph.
1648 This is useful if you'd like to spread the contents of a field over several
1649 lines, in order to keep the table compact.
1651 If there is an active region, and both point and mark are in the same column,
1652 the text in the column is wrapped to minimum width for the given number of
1653 lines. Generally, this makes the table more compact. A prefix ARG may be
1654 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1655 formats the selected text to two lines. If the region was longer than two
1656 lines, the remaining lines remain empty. A negative prefix argument reduces
1657 the current number of lines by that amount. The wrapped text is pasted back
1658 into the table. If you formatted it to more lines than it was before, fields
1659 further down in the table get overwritten - so you might need to make space in
1662 If there is no region, the current field is split at the cursor position and
1663 the text fragment to the right of the cursor is prepended to the field one
1666 If there is no region, but you specify a prefix ARG, the current field gets
1667 blank, and the content is appended to the field above."
1669 (org-table-check-inside-data-field)
1670 (if (org-region-active-p)
1671 ;; There is a region: fill as a paragraph
1672 (let* ((beg (region-beginning))
1673 (cline (save-excursion (goto-char beg
) (org-current-line)))
1674 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1676 (org-table-cut-region (region-beginning) (region-end))
1677 (if (> (length (car org-table-clip
)) 1)
1678 (error "Region must be limited to single column"))
1679 (setq nlines
(if arg
1681 (+ (length org-table-clip
) arg
)
1683 (length org-table-clip
)))
1684 (setq org-table-clip
1685 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1687 (org-goto-line cline
)
1688 (org-table-goto-column ccol
)
1689 (org-table-paste-rectangle))
1690 ;; No region, split the current field at point
1691 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1692 (skip-chars-forward "^\r\n|"))
1694 ;; combine with field above
1695 (let ((s (org-table-blank-field))
1696 (col (org-table-current-column)))
1697 (beginning-of-line 0)
1698 (while (org-at-table-hline-p) (beginning-of-line 0))
1699 (org-table-goto-column col
)
1700 (skip-chars-forward "^|")
1701 (skip-chars-backward " ")
1702 (insert " " (org-trim s
))
1705 (if (looking-at "\\([^|]+\\)+|")
1706 (let ((s (match-string 1)))
1707 (replace-match " |")
1708 (goto-char (match-beginning 0))
1709 (org-table-next-row)
1710 (insert (org-trim s
) " ")
1712 (org-table-next-row)))))
1714 (defvar org-field-marker nil
)
1716 (defun org-table-edit-field (arg)
1717 "Edit table field in a different window.
1718 This is mainly useful for fields that contain hidden parts.
1719 When called with a \\[universal-argument] prefix, just make the full field visible so that
1720 it can be edited in place."
1723 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1724 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1725 (remove-text-properties b e
'(org-cwidth t invisible t
1726 display t intangible t
))
1727 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1728 (font-lock-fontify-block)))
1729 (let ((pos (move-marker (make-marker) (point)))
1730 (field (org-table-get-field))
1731 (cw (current-window-configuration))
1733 (org-switch-to-buffer-other-window "*Org tmp*")
1735 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
1736 (let ((org-inhibit-startup t
)) (org-mode))
1737 (goto-char (setq p
(point-max)))
1738 (insert (org-trim field
))
1739 (remove-text-properties p
(point-max)
1740 '(invisible t org-cwidth t display t
1743 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1744 (org-set-local 'org-window-configuration cw
)
1745 (org-set-local 'org-field-marker pos
)
1746 (message "Edit and finish with C-c C-c"))))
1748 (defun org-table-finish-edit-field ()
1749 "Finish editing a table data field.
1750 Remove all newline characters, insert the result into the table, realign
1751 the table and kill the editing buffer."
1752 (let ((pos org-field-marker
)
1753 (cw org-window-configuration
)
1754 (cb (current-buffer))
1756 (goto-char (point-min))
1757 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1758 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1759 (replace-match " "))
1760 (setq text
(org-trim (buffer-string)))
1761 (set-window-configuration cw
)
1763 (select-window (get-buffer-window (marker-buffer pos
)))
1765 (move-marker pos nil
)
1766 (org-table-check-inside-data-field)
1767 (org-table-get-field nil text
)
1769 (message "New field value inserted")))
1771 (defvar org-timecnt
) ; dynamically scoped parameter
1773 (defun org-table-sum (&optional beg end nlast
)
1774 "Sum numbers in region of current table column.
1775 The result will be displayed in the echo area, and will be available
1776 as kill to be inserted with \\[yank].
1778 If there is an active region, it is interpreted as a rectangle and all
1779 numbers in that rectangle will be summed. If there is no active
1780 region and point is located in a table column, sum all numbers in that
1783 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1784 numbers are assumed to be times as well (in decimal hours) and the
1785 numbers are added as such.
1787 If NLAST is a number, only the NLAST fields will actually be summed."
1790 (let (col (org-timecnt 0) diff h m s org-table-clip
)
1792 ((and beg end
)) ; beg and end given explicitly
1793 ((org-region-active-p)
1794 (setq beg
(region-beginning) end
(region-end)))
1796 (setq col
(org-table-current-column))
1797 (goto-char (org-table-begin))
1798 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
1799 (error "No table data"))
1800 (org-table-goto-column col
)
1802 (goto-char (org-table-end))
1803 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
1804 (error "No table data"))
1805 (org-table-goto-column col
)
1806 (setq end
(point))))
1807 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
1808 (items1 (cond ((not nlast
) items
)
1809 ((>= nlast
(length items
)) items
)
1810 (t (setq items
(reverse items
))
1811 (setcdr (nthcdr (1- nlast
) items
) nil
)
1813 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
1815 (res (apply '+ numbers
))
1816 (sres (if (= org-timecnt
0)
1817 (number-to-string res
)
1818 (setq diff
(* 3600 res
)
1819 h
(floor (/ diff
3600)) diff
(mod diff
3600)
1820 m
(floor (/ diff
60)) diff
(mod diff
60)
1822 (format "%d:%02d:%02d" h m s
))))
1826 (substitute-command-keys
1827 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
1828 (length numbers
) sres
))))
1831 (defun org-table-get-number-for-summing (s)
1833 (if (string-match "^ *|? *" s
)
1834 (setq s
(replace-match "" nil nil s
)))
1835 (if (string-match " *|? *$" s
)
1836 (setq s
(replace-match "" nil nil s
)))
1837 (setq n
(string-to-number s
))
1839 ((and (string-match "0" s
)
1840 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
1841 ((string-match "\\`[ \t]+\\'" s
) nil
)
1842 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
1843 (let ((h (string-to-number (or (match-string 1 s
) "0")))
1844 (m (string-to-number (or (match-string 2 s
) "0")))
1845 (s (string-to-number (or (match-string 4 s
) "0"))))
1846 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
1847 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
1851 (defun org-table-current-field-formula (&optional key noerror
)
1852 "Return the formula active for the current field.
1853 Assumes that specials are in place.
1854 If KEY is given, return the key to this formula.
1855 Otherwise return the formula preceded with \"=\" or \":=\"."
1856 (let* ((name (car (rassoc (list (org-current-line)
1857 (org-table-current-column))
1858 org-table-named-field-locations
)))
1859 (col (org-table-current-column))
1860 (scol (int-to-string col
))
1861 (ref (format "@%d$%d" (org-table-current-dline) col
))
1862 (stored-list (org-table-get-stored-formulas noerror
))
1863 (ass (or (assoc name stored-list
)
1864 (assoc ref stored-list
)
1865 (assoc scol stored-list
))))
1868 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
1871 (defun org-table-get-formula (&optional equation named
)
1872 "Read a formula from the minibuffer, offer stored formula as default.
1873 When NAMED is non-nil, look for a named equation."
1874 (let* ((stored-list (org-table-get-stored-formulas))
1875 (name (car (rassoc (list (org-current-line)
1876 (org-table-current-column))
1877 org-table-named-field-locations
)))
1878 (ref (format "@%d$%d" (org-table-current-dline)
1879 (org-table-current-column)))
1880 (refass (assoc ref stored-list
))
1881 (nameass (assoc name stored-list
))
1883 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
1886 (int-to-string (org-table-current-column))))
1887 (dummy (and (or nameass refass
) (not named
)
1888 (not (y-or-n-p "Replace existing field formula with column formula? " ))
1890 (name (or name ref
))
1891 (org-table-may-need-update nil
)
1892 (stored (cdr (assoc scol stored-list
)))
1894 ((and stored equation
(string-match "^ *=? *$" equation
))
1898 (t (org-table-formula-from-user
1900 (org-table-formula-to-user
1901 (format "%s formula %s%s="
1902 (if named
"Field" "Column")
1903 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
1905 (if stored
(org-table-formula-to-user stored
) "")
1906 'org-table-formula-history
1909 (when (not (string-match "\\S-" eq
))
1911 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
1912 (org-table-store-formulas stored-list
)
1913 (error "Formula removed"))
1914 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
1915 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
1916 (if (and name
(not named
))
1917 ;; We set the column equation, delete the named one.
1918 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
1921 (setcdr (assoc scol stored-list
) eq
)
1922 (setq stored-list
(cons (cons scol eq
) stored-list
)))
1923 (if (or mustsave
(not (equal stored eq
)))
1924 (org-table-store-formulas stored-list
))
1927 (defun org-table-store-formulas (alist)
1928 "Store the list of formulas below the current table."
1929 (setq alist
(sort alist
'org-table-formula-less-p
))
1931 (goto-char (org-table-end))
1932 (if (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM:\\(.*\n?\\)")
1934 ;; don't overwrite TBLFM, we might use text properties to store stuff
1935 (goto-char (match-beginning 2))
1936 (delete-region (match-beginning 2) (match-end 0)))
1937 (org-indent-line-function)
1938 (insert "#+TBLFM:"))
1940 (mapconcat (lambda (x)
1942 (if (equal (string-to-char (car x
)) ?
@) "" "$")
1943 (car x
) "=" (cdr x
)))
1947 (defsubst org-table-formula-make-cmp-string
(a)
1948 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a
)
1950 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a
))) "")
1951 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a
))) "")
1952 (if (match-end 5) (concat "@@" (match-string 5 a
))))))
1954 (defun org-table-formula-less-p (a b
)
1955 "Compare two formulas for sorting."
1956 (let ((as (org-table-formula-make-cmp-string (car a
)))
1957 (bs (org-table-formula-make-cmp-string (car b
))))
1958 (and as bs
(string< as bs
))))
1960 (defun org-table-get-stored-formulas (&optional noerror
)
1961 "Return an alist with the stored formulas directly after current table."
1963 (let (scol eq eq-alist strings string seen
)
1965 (goto-char (org-table-end))
1966 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
1967 (setq strings
(org-split-string (match-string 2) " *:: *"))
1968 (while (setq string
(pop strings
))
1969 (when (string-match "\\`\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
1970 (setq scol
(if (match-end 2)
1971 (match-string 2 string
)
1972 (match-string 1 string
))
1973 eq
(match-string 3 string
)
1974 eq-alist
(cons (cons scol eq
) eq-alist
))
1975 (if (member scol seen
)
1978 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
1981 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
1982 (push scol seen
))))))
1983 (nreverse eq-alist
)))
1985 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
1986 "Modify the equations after the table structure has been edited.
1987 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
1988 For all numbers larger than LIMIT, shift them by DELTA."
1990 (goto-char (org-table-end))
1991 (when (looking-at "[ \t]*#\\+TBLFM:")
1992 (let ((re (concat key
"\\([0-9]+\\)"))
1995 (if (or (equal key
"$") (equal key
"$LR"))
1996 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
1997 (regexp-quote key
) remove
)
1998 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2001 (while (re-search-forward re2
(point-at-eol) t
)
2002 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2003 (replace-match ""))))
2004 (while (re-search-forward re
(point-at-eol) t
)
2005 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2006 (setq s
(match-string 1) n
(string-to-number s
))
2008 ((setq a
(assoc s replace
))
2009 (replace-match (concat key
(cdr a
)) t t
))
2010 ((and limit
(> n limit
))
2011 (replace-match (concat key
(int-to-string (+ n delta
)))
2014 (defun org-table-get-specials ()
2015 "Get the column names and local parameters for this table."
2017 (let ((beg (org-table-begin)) (end (org-table-end))
2018 names name fields fields1 field cnt
2019 c v l line col types dlines hlines last-dline
)
2020 (setq org-table-column-names nil
2021 org-table-local-parameters nil
2022 org-table-named-field-locations nil
2023 org-table-current-begin-line nil
2024 org-table-current-begin-pos nil
2025 org-table-current-line-types nil
)
2027 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2028 (setq names
(org-split-string (match-string 1) " *| *")
2030 (while (setq name
(pop names
))
2032 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name
)
2033 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2034 (setq org-table-column-names
(nreverse org-table-column-names
))
2035 (setq org-table-column-name-regexp
2036 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2038 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2039 (setq fields
(org-split-string (match-string 1) " *| *"))
2040 (while (setq field
(pop fields
))
2041 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2042 (push (cons (match-string 1 field
) (match-string 2 field
))
2043 org-table-local-parameters
))))
2045 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2046 (setq c
(match-string 1)
2047 fields
(org-split-string (match-string 2) " *| *"))
2049 (beginning-of-line (if (equal c
"_") 2 0))
2050 (setq line
(org-current-line) col
1)
2051 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2052 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2053 (while (and fields1
(setq field
(pop fields
)))
2054 (setq v
(pop fields1
) col
(1+ col
))
2055 (when (and (stringp field
) (stringp v
)
2056 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field
))
2057 (push (cons field v
) org-table-local-parameters
)
2058 (push (list field line col
) org-table-named-field-locations
))))
2059 ;; Analyse the line types
2061 (setq org-table-current-begin-line
(org-current-line)
2062 org-table-current-begin-pos
(point)
2063 l org-table-current-begin-line
)
2064 (while (looking-at "[ \t]*|\\(-\\)?")
2065 (push (if (match-end 1) 'hline
'dline
) types
)
2066 (if (match-end 1) (push l hlines
) (push l dlines
))
2067 (beginning-of-line 2)
2069 (push 'hline types
) ;; add an imaginary extra hline to the end
2070 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2071 last-dline
(car dlines
)
2072 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2073 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2074 (org-goto-line last-dline
)
2075 (let* ((l last-dline
)
2076 (fields (org-split-string
2077 (buffer-substring (point-at-bol) (point-at-eol))
2079 (nfields (length fields
))
2081 (loop for i from
1 to nfields do
2082 (push (list (format "LR%d" i
) l i
) al
)
2083 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2084 (setq org-table-named-field-locations
2085 (append org-table-named-field-locations al
))
2086 (setq org-table-local-parameters
2087 (append org-table-local-parameters al2
))))))
2090 (defun org-table-maybe-eval-formula ()
2091 "Check if the current field starts with \"=\" or \":=\".
2092 If yes, store the formula and apply it."
2093 ;; We already know we are in a table. Get field will only return a formula
2094 ;; when appropriate. It might return a separator line, but no problem.
2095 (when org-table-formula-evaluate-inline
2096 (let* ((field (org-trim (or (org-table-get-field) "")))
2098 (when (string-match "^:?=\\(.*\\)" field
)
2099 (setq named
(equal (string-to-char field
) ?
:)
2100 eq
(match-string 1 field
))
2101 (if (or (fboundp 'calc-eval
)
2102 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2103 (org-table-eval-formula (if named
'(4) nil
)
2104 (org-table-formula-from-user eq
))
2105 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2107 (defvar org-recalc-commands nil
2108 "List of commands triggering the recalculation of a line.
2109 Will be filled automatically during use.")
2111 (defvar org-recalc-marks
2112 '((" " .
"Unmarked: no special line, no automatic recalculation")
2113 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2114 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2115 ("!" .
"Column name definition line. Reference in formula as $name.")
2116 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2117 ("_" .
"Names for values in row below this one.")
2118 ("^" .
"Names for values in row above this one.")))
2120 (defun org-table-rotate-recalc-marks (&optional newchar
)
2121 "Rotate the recalculation mark in the first column.
2122 If in any row, the first field is not consistent with a mark,
2123 insert a new column for the markers.
2124 When there is an active region, change all the lines in the region,
2125 after prompting for the marking character.
2126 After each change, a message will be displayed indicating the meaning
2129 (unless (org-at-table-p) (error "Not at a table"))
2130 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2131 (beg (org-table-begin))
2132 (end (org-table-end))
2133 (l (org-current-line))
2134 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2135 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2139 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2140 (col (org-table-current-column))
2141 (forcenew (car (assoc newchar org-recalc-marks
)))
2144 (message "Change region to what mark? Type # * ! $ or SPC: ")
2145 (setq newchar
(char-to-string (read-char-exclusive))
2146 forcenew
(car (assoc newchar org-recalc-marks
))))
2147 (if (and newchar
(not forcenew
))
2148 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2150 (if l1
(org-goto-line l1
))
2152 (beginning-of-line 1)
2153 (unless (looking-at org-table-dataline-regexp
)
2154 (error "Not at a table data line")))
2156 (org-table-goto-column 1)
2157 (org-table-insert-column)
2158 (org-table-goto-column (1+ col
)))
2159 (setq epos
(point-at-eol))
2161 (beginning-of-line 1)
2162 (org-table-get-field
2163 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2165 (setq new
(or forcenew
2166 (cadr (member (match-string 1) marks
))))
2172 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2173 (and (looking-at org-table-dataline-regexp
)
2174 (org-table-get-field 1 (concat " " new
" "))))
2175 (org-goto-line l1
)))
2176 (if (not (= epos
(point-at-eol))) (org-table-align))
2178 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks
))))))
2180 (defun org-table-maybe-recalculate-line ()
2181 "Recompute the current line if marked for it, and if we haven't just done it."
2183 (and org-table-allow-automatic-line-recalculation
2184 (not (and (memq last-command org-recalc-commands
)
2185 (equal org-last-recalc-line
(org-current-line))))
2186 (save-excursion (beginning-of-line 1)
2187 (looking-at org-table-auto-recalculate-regexp
))
2188 (org-table-recalculate) t
))
2191 (defsubst org-set-calc-mode
(var &optional value
)
2193 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2194 ("R" calc-angle-mode rad
)
2195 ("F" calc-prefer-frac t
)
2196 ("S" calc-symbolic-mode t
)))
2197 value
(nth 2 var
) var
(nth 1 var
)))
2198 (if (memq var modes
)
2199 (setcar (cdr (memq var modes
)) value
)
2200 (cons var
(cons value modes
)))
2203 (defun org-table-eval-formula (&optional arg equation
2204 suppress-align suppress-const
2205 suppress-store suppress-analysis
)
2206 "Replace the table field value at the cursor by the result of a calculation.
2208 This function makes use of Dave Gillespie's Calc package, in my view the
2209 most exciting program ever written for GNU Emacs. So you need to have Calc
2210 installed in order to use this function.
2212 In a table, this command replaces the value in the current field with the
2213 result of a formula. It also installs the formula as the \"current\" column
2214 formula, by storing it in a special line below the table. When called
2215 with a `C-u' prefix, the current field must be a named field, and the
2216 formula is installed as valid in only this specific field.
2218 When called with two `C-u' prefixes, insert the active equation
2219 for the field back into the current field, so that it can be
2220 edited there. This is useful in order to use \\[org-table-show-reference]
2221 to check the referenced fields.
2223 When called, the command first prompts for a formula, which is read in
2224 the minibuffer. Previously entered formulas are available through the
2225 history list, and the last used formula is offered as a default.
2226 These stored formulas are adapted correctly when moving, inserting, or
2227 deleting columns with the corresponding commands.
2229 The formula can be any algebraic expression understood by the Calc package.
2230 For details, see the Org-mode manual.
2232 This function can also be called from Lisp programs and offers
2233 additional arguments: EQUATION can be the formula to apply. If this
2234 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2235 used to speed-up recursive calls by by-passing unnecessary aligns.
2236 SUPPRESS-CONST suppresses the interpretation of constants in the
2237 formula, assuming that this has been done already outside the function.
2238 SUPPRESS-STORE means the formula should not be stored, either because
2239 it is already stored, or because it is a modified equation that should
2240 not overwrite the stored one."
2242 (org-table-check-inside-data-field)
2243 (or suppress-analysis
(org-table-get-specials))
2244 (if (equal arg
'(16))
2245 (let ((eq (org-table-current-field-formula)))
2246 (or eq
(error "No equation active for current field"))
2247 (org-table-get-field nil eq
)
2249 (setq org-table-may-need-update t
))
2251 (ndown (if (integerp arg
) arg
1))
2252 (org-table-automatic-realign nil
)
2253 (case-fold-search nil
)
2255 (formula (if (and equation suppress-store
)
2257 (org-table-get-formula equation
(equal arg
'(4)))))
2258 (n0 (org-table-current-column))
2259 (modes (copy-sequence org-calc-default-modes
))
2260 (numbers nil
) ; was a variable, now fixed default
2262 n form form0 bw fmt x ev orig c lispp literal
)
2263 ;; Parse the format string. Since we have a lot of modes, this is
2264 ;; a lot of work. However, I think calc still uses most of the time.
2265 (if (string-match ";" formula
)
2266 (let ((tmp (org-split-string formula
";")))
2267 (setq formula
(car tmp
)
2268 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2270 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2271 (setq c
(string-to-char (match-string 1 fmt
))
2272 n
(string-to-number (match-string 2 fmt
)))
2274 (setq modes
(org-set-calc-mode 'calc-internal-prec n
))
2275 (setq modes
(org-set-calc-mode
2277 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2278 (?s . sci
) (?e . eng
))))
2280 (setq fmt
(replace-match "" t t fmt
)))
2281 (if (string-match "[NT]" fmt
)
2282 (setq numbers
(equal (match-string 0 fmt
) "N")
2283 fmt
(replace-match "" t t fmt
)))
2284 (if (string-match "L" fmt
)
2286 fmt
(replace-match "" t t fmt
)))
2287 (if (string-match "E" fmt
)
2289 fmt
(replace-match "" t t fmt
)))
2290 (while (string-match "[DRFS]" fmt
)
2291 (setq modes
(org-set-calc-mode (match-string 0 fmt
)))
2292 (setq fmt
(replace-match "" t t fmt
)))
2293 (unless (string-match "\\S-" fmt
)
2295 (if (and (not suppress-const
) org-table-formula-use-constants
)
2296 (setq formula
(org-table-formula-substitute-names formula
)))
2297 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2299 (setq fields
(org-split-string
2301 (buffer-substring (point-at-bol) (point-at-eol)))
2304 (setq fields
(mapcar
2305 (lambda (x) (number-to-string (string-to-number x
)))
2307 (setq ndown
(1- ndown
))
2308 (setq form
(copy-sequence formula
)
2309 lispp
(and (> (length form
) 2)(equal (substring form
0 2) "'(")))
2310 (if (and lispp literal
) (setq lispp
'literal
))
2312 ;; Insert row and column number of formula result field
2313 (while (string-match "[@$]#" form
)
2318 (if (equal (substring form
(match-beginning 0)
2319 (1+ (match-beginning 0)))
2321 (org-table-current-dline)
2322 (org-table-current-column))))
2325 ;; Check for old vertical references
2326 (setq form
(org-table-rewrite-old-row-references form
))
2327 ;; Insert remote references
2328 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2332 (org-table-make-reference
2333 (org-table-get-remote-range
2334 (match-string 1 form
) (match-string 2 form
))
2335 keep-empty numbers lispp
))
2337 ;; Insert complex ranges
2338 (while (and (string-match org-table-range-regexp form
)
2339 (> (length (match-string 0 form
)) 1))
2343 (org-table-make-reference
2344 (org-table-get-range (match-string 0 form
) nil n0
)
2345 keep-empty numbers lispp
))
2347 ;; Insert simple ranges
2348 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2352 (org-table-make-reference
2354 fields
(string-to-number (match-string 1 form
))
2355 (string-to-number (match-string 2 form
)))
2356 keep-empty numbers lispp
))
2359 ;; Insert the references to fields in same row
2360 (while (string-match "\\$\\([0-9]+\\)" form
)
2361 (setq n
(string-to-number (match-string 1 form
))
2362 x
(nth (1- (if (= n
0) n0 n
)) fields
))
2363 (unless x
(error "Invalid field specifier \"%s\""
2364 (match-string 0 form
)))
2365 (setq form
(replace-match
2367 (org-table-make-reference x nil numbers lispp
))
2371 (setq ev
(condition-case nil
2372 (eval (eval (read form
)))
2374 ev
(if (numberp ev
) (number-to-string ev
) ev
))
2375 (or (fboundp 'calc-eval
)
2376 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2377 (setq ev
(calc-eval (cons form modes
)
2378 (if numbers
'num
))))
2380 (when org-table-formula-debug
2381 (with-output-to-temp-buffer "*Substitution History*"
2382 (princ (format "Substitution history of formula
2386 $1-> %s\n" orig formula form0 form
))
2388 (princ (format " %s^\nError: %s"
2389 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2390 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2392 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2393 (setq bw
(get-buffer-window "*Substitution History*"))
2394 (org-fit-window-to-buffer bw
)
2395 (unless (and (interactive-p) (not ndown
))
2396 (unless (let (inhibit-redisplay)
2397 (y-or-n-p "Debugging Formula. Continue to next? "))
2402 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2403 (org-table-justify-field-maybe
2404 (if fmt
(format fmt
(string-to-number ev
)) ev
))
2405 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2406 (call-interactively 'org-return
)
2408 (and down
(org-table-maybe-recalculate-line))
2409 (or suppress-align
(and org-table-may-need-update
2410 (org-table-align))))))
2412 (defun org-table-put-field-property (prop value
)
2414 (put-text-property (progn (skip-chars-backward "^|") (point))
2415 (progn (skip-chars-forward "^|") (point))
2418 (defun org-table-get-range (desc &optional tbeg col highlight
)
2419 "Get a calc vector from a column, according to descriptor DESC.
2420 Optional arguments TBEG and COL can give the beginning of the table and
2421 the current column, to avoid unnecessary parsing.
2422 HIGHLIGHT means just highlight the range."
2423 (if (not (equal (string-to-char desc
) ?
@))
2424 (setq desc
(concat "@" desc
)))
2426 (or tbeg
(setq tbeg
(org-table-begin)))
2427 (or col
(setq col
(org-table-current-column)))
2428 (let ((thisline (org-current-line))
2429 beg end c1 c2 r1 r2 rangep tmp
)
2430 (unless (string-match org-table-range-regexp desc
)
2431 (error "Invalid table range specifier `%s'" desc
))
2432 (setq rangep
(match-end 3)
2433 r1
(and (match-end 1) (match-string 1 desc
))
2434 r2
(and (match-end 4) (match-string 4 desc
))
2435 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2436 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2438 (and c1
(setq c1
(+ (string-to-number c1
)
2439 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2440 (and c2
(setq c2
(+ (string-to-number c2
)
2441 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2442 (if (equal r1
"") (setq r1 nil
))
2443 (if (equal r2
"") (setq r2 nil
))
2444 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2445 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2446 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2447 (if (not r1
) (setq r1 thisline
))
2448 (if (not r2
) (setq r2 thisline
))
2449 (if (not c1
) (setq c1 col
))
2450 (if (not c2
) (setq c2 col
))
2451 (if (or (not rangep
) (and (= r1 r2
) (= c1 c2
)))
2455 (while (not (looking-at org-table-dataline-regexp
))
2456 (beginning-of-line 2))
2457 (prog1 (org-trim (org-table-get-field c1
))
2458 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2459 ;; A range, return a vector
2460 ;; First sort the numbers to get a regular ractangle
2461 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2462 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2464 (while (not (looking-at org-table-dataline-regexp
))
2465 (beginning-of-line 2))
2466 (org-table-goto-column c1
)
2469 (while (not (looking-at org-table-dataline-regexp
))
2470 (beginning-of-line 0))
2471 (org-table-goto-column c2
)
2474 (org-table-highlight-rectangle
2475 beg
(progn (skip-chars-forward "^|\n") (point))))
2476 ;; return string representation of calc vector
2478 (apply 'append
(org-table-copy-region beg end
)))))))
2480 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2481 "Analyze descriptor DESC and retrieve the corresponding line number.
2482 The cursor is currently in line CLINE, the table begins in line BLINE,
2483 and TABLE is a vector with line types."
2484 (if (string-match "^[0-9]+$" desc
)
2485 (aref org-table-dlines
(string-to-number desc
))
2486 (setq cline
(or cline
(org-current-line))
2487 bline
(or bline org-table-current-begin-line
)
2488 table
(or table org-table-current-line-types
))
2490 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2492 (and (not (match-end 3)) (not (match-end 6)))
2493 (and (match-end 3) (match-end 6) (not (match-end 5))))
2494 (error "Invalid row descriptor `%s'" desc
))
2495 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2496 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2497 (odir (and (match-end 5) (match-string 5 desc
)))
2498 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2500 (rel (and (match-end 6)
2501 (or (and (match-end 1) (not (match-end 3)))
2503 (if (and hn
(not hdir
))
2506 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2507 (if (and (not hn
) on
(not odir
))
2508 (error "Should never happen");;(aref org-table-dlines on)
2509 (if (and hn
(> hn
0))
2510 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2511 nil hn cline desc
)))
2513 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2514 rel on cline desc
)))
2517 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2518 "FIXME: Needs more documentation."
2519 (let ((l (length table
)))
2521 (while (and (setq i
(+ i
(if backwards -
1 1)))
2523 (not (eq (aref table i
) type
))
2524 (if (and relative
(eq (aref table i
) 'hline
))
2526 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2527 ((eq org-table-relative-ref-may-cross-hline
'error
)
2528 (error "Row descriptor %s used in line %d crosses hline" desc cline
))
2529 (t (setq i
(- i
(if backwards -
1 1))
2534 (if (or (< i
0) (>= i l
))
2535 (error "Row descriptor %s used in line %d leads outside table"
2539 (defun org-table-rewrite-old-row-references (s)
2540 (if (string-match "&[-+0-9I]" s
)
2541 (error "Formula contains old &row reference, please rewrite using @-syntax")
2544 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2545 "Convert list ELEMENTS to something appropriate to insert into formula.
2546 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2547 NUMBERS indicates that everything should be converted to numbers.
2548 LISPP means to return something appropriate for a Lisp list."
2549 (if (stringp elements
) ; just a single val
2551 (if (eq lispp
'literal
)
2553 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2554 (if (equal elements
"") (setq elements
"0"))
2555 (if numbers
(setq elements
(number-to-string (string-to-number elements
))))
2556 (concat "(" elements
")"))
2560 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2562 (setq elements
(or elements
'("0")))
2566 (if (eq lispp
'literal
)
2568 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2570 (concat "[" (mapconcat
2572 (if numbers
(number-to-string (string-to-number x
)) x
))
2576 (defun org-table-recalculate (&optional all noalign
)
2577 "Recalculate the current table line by applying all stored formulas.
2578 With prefix arg ALL, do this for all lines in the table.
2579 With the prefix argument ALL is `(16)' \
2580 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2581 it is the symbol `iterate', recompute the table until it no longer changes.
2582 If NOALIGN is not nil, do not re-align the table after the computations
2583 are done. This is typically used internally to save time, if it is
2584 known that the table will be realigned a little later anyway."
2586 (or (memq this-command org-recalc-commands
)
2587 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2588 (unless (org-at-table-p) (error "Not at a table"))
2589 (if (or (eq all
'iterate
) (equal all
'(16)))
2591 (org-table-get-specials)
2592 (let* ((eqlist (sort (org-table-get-stored-formulas)
2593 (lambda (a b
) (string< (car a
) (car b
)))))
2594 (inhibit-redisplay (not debug-on-error
))
2595 (line-re org-table-dataline-regexp
)
2596 (thisline (org-current-line))
2597 (thiscol (org-table-current-column))
2598 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name
)
2599 ;; Insert constants in all formulas
2602 (setcdr x
(org-table-formula-substitute-names (cdr x
)))
2605 ;; Split the equation list
2606 (while (setq eq
(pop eqlist
))
2607 (if (<= (string-to-char (car eq
)) ?
9)
2610 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
2613 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
2614 (goto-char (setq beg
(org-table-begin)))
2615 (if (re-search-forward org-table-calculate-mark-regexp end t
)
2616 ;; This is a table with marked lines, compute selected lines
2617 (setq line-re org-table-recalculate-regexp
)
2618 ;; Move forward to the first non-header line
2619 (if (and (re-search-forward org-table-dataline-regexp end t
)
2620 (re-search-forward org-table-hline-regexp end t
)
2621 (re-search-forward org-table-dataline-regexp end t
))
2622 (setq beg
(match-beginning 0))
2623 nil
))) ;; just leave beg where it is
2624 (setq beg
(point-at-bol)
2625 end
(move-marker (make-marker) (1+ (point-at-eol)))))
2627 (and all
(message "Re-applying formulas to full table..."))
2629 ;; First find the named fields, and mark them untouchable
2630 (remove-text-properties beg end
'(org-untouchable t
))
2631 (while (setq eq
(pop eqlname
))
2633 a
(assoc name org-table-named-field-locations
))
2635 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
2638 (aref org-table-dlines
2639 (string-to-number (match-string 1 name
)))
2640 (error (error "Invalid row number in %s"
2642 (string-to-number (match-string 2 name
)))))
2643 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
2644 (message "Re-applying formula to field: %s" name
)
2645 (org-goto-line (nth 1 a
))
2646 (org-table-goto-column (nth 2 a
))
2647 (push (append a
(list (cdr eq
))) eqlname1
)
2648 (org-table-put-field-property :org-untouchable t
)))
2650 ;; Now evaluate the column formulas, but skip fields covered by
2653 (while (re-search-forward line-re end t
)
2654 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2655 ;; Unprotected line, recalculate
2656 (and all
(message "Re-applying formulas to full table...(line %d)"
2657 (setq cnt
(1+ cnt
))))
2658 (setq org-last-recalc-line
(org-current-line))
2660 (while (setq entry
(pop eql
))
2661 (org-goto-line org-last-recalc-line
)
2662 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
2663 (unless (get-text-property (point) :org-untouchable
)
2664 (org-table-eval-formula nil
(cdr entry
)
2665 'noalign
'nocst
'nostore
'noanalysis
)))))
2667 ;; Now evaluate the field formulas
2668 (while (setq eq
(pop eqlname1
))
2669 (message "Re-applying formula to field: %s" (car eq
))
2670 (org-goto-line (nth 1 eq
))
2671 (org-table-goto-column (nth 2 eq
))
2672 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
2673 'nostore
'noanalysis
))
2675 (org-goto-line thisline
)
2676 (org-table-goto-column thiscol
)
2677 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
2678 (or noalign
(and org-table-may-need-update
(org-table-align))
2679 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
2681 ;; back to initial position
2682 (message "Re-applying formulas...done")
2683 (org-goto-line thisline
)
2684 (org-table-goto-column thiscol
)
2685 (or noalign
(and org-table-may-need-update
(org-table-align))
2686 (and all
(message "Re-applying formulas...done"))))))
2688 (defun org-table-iterate (&optional arg
)
2689 "Recalculate the table until it does not change anymore."
2691 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
2693 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2698 (org-table-recalculate 'all
)
2699 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
2700 (if (not (string= lasttbl thistbl
))
2701 (setq lasttbl thistbl
)
2703 (message "Convergence after %d iterations" i
)
2704 (message "Table was already stable"))
2706 (error "No convergence after %d iterations" i
))))
2708 (defun org-table-recalculate-buffer-tables ()
2709 "Recalculate all tables in the current buffer."
2714 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
2716 (defun org-table-iterate-buffer-tables ()
2717 "Iterate all tables in the buffer, to converge inter-table dependencies."
2720 (checksum (md5 (buffer-string)))
2730 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
2731 (if (equal checksum
(setq c1
(md5 (buffer-string))))
2733 (message "Convergence after %d iterations" (- imax i
))
2735 (setq checksum c1
)))
2736 (error "No convergence after %d iterations" imax
))))))
2738 (defun org-table-formula-substitute-names (f)
2739 "Replace $const with values in string F."
2740 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
2741 ;; First, check for column names
2742 (while (setq start
(string-match org-table-column-name-regexp f start
))
2743 (setq start
(1+ start
))
2744 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
2745 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
2746 ;; Parameters and constants
2748 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
2750 (setq start
(match-end 2))
2751 (setq start
(1+ start
))
2752 (if (setq a
(save-match-data
2753 (org-table-get-constant (match-string 1 f
))))
2754 (setq f
(replace-match
2755 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
2756 (if org-table-formula-debug
2757 (put-text-property 0 (length f
) :orig-formula f1 f
))
2760 (defun org-table-get-constant (const)
2761 "Find the value for a parameter or constant in a formula.
2762 Parameters get priority."
2763 (or (cdr (assoc const org-table-local-parameters
))
2764 (cdr (assoc const org-table-formula-constants-local
))
2765 (cdr (assoc const org-table-formula-constants
))
2766 (and (fboundp 'constants-get
) (constants-get const
))
2767 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
2768 (org-entry-get nil
(substring const
5) 'inherit
))
2771 (defvar org-table-fedit-map
2772 (let ((map (make-sparse-keymap)))
2773 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
2774 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
2775 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
2776 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
2777 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
2778 (org-defkey map
"\C-c?" 'org-table-show-reference
)
2779 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
2780 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
2781 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
2782 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
2783 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
2784 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
2785 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
2786 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
2787 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
2788 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
2789 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
2790 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
2791 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
2792 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
2795 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
2797 ["Finish and Install" org-table-fedit-finish t
]
2798 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
2799 ["Abort" org-table-fedit-abort t
]
2801 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
2802 ["Complete Lisp Symbol" lisp-complete-symbol t
]
2804 "Shift Reference at Point"
2805 ["Up" org-table-fedit-ref-up t
]
2806 ["Down" org-table-fedit-ref-down t
]
2807 ["Left" org-table-fedit-ref-left t
]
2808 ["Right" org-table-fedit-ref-right t
]
2810 "Change Test Row for Column Formulas"
2811 ["Up" org-table-fedit-line-up t
]
2812 ["Down" org-table-fedit-line-down t
]
2814 ["Scroll Table Window" org-table-fedit-scroll t
]
2815 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
2816 ["Show Table Grid" org-table-fedit-toggle-coordinates
2817 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
2818 org-table-overlay-coordinates
)]
2820 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
2821 :style toggle
:selected org-table-buffer-is-an
]))
2825 (defun org-table-edit-formulas ()
2826 "Edit the formulas of the current table in a separate buffer."
2828 (when (save-excursion (beginning-of-line 1) (looking-at "[ \t]*#\\+TBLFM"))
2829 (beginning-of-line 0))
2830 (unless (org-at-table-p) (error "Not at a table"))
2831 (org-table-get-specials)
2832 (let ((key (org-table-current-field-formula 'key
'noerror
))
2833 (eql (sort (org-table-get-stored-formulas 'noerror
)
2834 'org-table-formula-less-p
))
2835 (pos (move-marker (make-marker) (point)))
2837 (wc (current-window-configuration))
2838 (sel-win (selected-window))
2839 (titles '((column .
"# Column Formulas\n")
2840 (field .
"# Field Formulas\n")
2841 (named .
"# Named Field Formulas\n")))
2843 (org-switch-to-buffer-other-window "*Edit Formulas*")
2845 ;; Keep global-font-lock-mode from turning on font-lock-mode
2846 (let ((font-lock-global-modes '(not fundamental-mode
)))
2848 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
2849 (org-set-local 'org-pos pos
)
2850 (org-set-local 'org-window-configuration wc
)
2851 (org-set-local 'org-selected-window sel-win
)
2852 (use-local-map org-table-fedit-map
)
2853 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
2854 (easy-menu-add org-table-fedit-menu
)
2855 (setq startline
(org-current-line))
2856 (while (setq entry
(pop eql
))
2858 ((equal (string-to-char (car entry
)) ?
@) 'field
)
2859 ((string-match "^[0-9]" (car entry
)) 'column
)
2861 (when (setq title
(assq type titles
))
2862 (or (bobp) (insert "\n"))
2863 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
2864 (setq titles
(delq title titles
)))
2865 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
2866 (setq s
(concat (if (equal (string-to-char (car entry
)) ?
@) "" "$")
2867 (car entry
) " = " (cdr entry
) "\n"))
2868 (remove-text-properties 0 (length s
) '(face nil
) s
)
2870 (if (eq org-table-use-standard-references t
)
2871 (org-table-fedit-toggle-ref-type))
2872 (org-goto-line startline
)
2873 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
2875 (defun org-table-fedit-post-command ()
2876 (when (not (memq this-command
'(lisp-complete-symbol)))
2877 (let ((win (selected-window)))
2880 (org-table-show-reference)
2882 (select-window win
)))))
2884 (defun org-table-formula-to-user (s)
2885 "Convert a formula from internal to user representation."
2886 (if (eq org-table-use-standard-references t
)
2887 (org-table-convert-refs-to-an s
)
2890 (defun org-table-formula-from-user (s)
2891 "Convert a formula from user to internal representation."
2892 (if org-table-use-standard-references
2893 (org-table-convert-refs-to-rc s
)
2896 (defun org-table-convert-refs-to-rc (s)
2897 "Convert spreadsheet references from AB7 to @7$28.
2898 Works for single references, but also for entire formulas and even the
2901 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^)]*)\\)" s start
)
2904 ;; format match, just advance
2905 (setq start
(match-end 0)))
2906 ((and (> (match-beginning 0) 0)
2907 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
2908 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
2909 ;; 3.e5 or something like this.
2910 (setq start
(match-end 0)))
2911 ((or (> (- (match-end 1) (match-beginning 1)) 2)
2912 ;; (member (match-string 1 s)
2913 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
2915 ;; function name, just advance
2916 (setq start
(match-end 0)))
2918 (setq start
(match-beginning 0)
2920 (if (equal (match-string 2 s
) "&")
2921 (format "$%d" (org-letters-to-number (match-string 1 s
)))
2923 (string-to-number (match-string 2 s
))
2924 (org-letters-to-number (match-string 1 s
))))
2928 (defun org-table-convert-refs-to-an (s)
2929 "Convert spreadsheet references from to @7$28 to AB7.
2930 Works for single references, but also for entire formulas and even the
2932 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
2933 (setq s
(replace-match
2935 (org-number-to-letters
2936 (string-to-number (match-string 2 s
)))
2937 (string-to-number (match-string 1 s
)))
2939 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
2940 (setq s
(replace-match (concat "\\1"
2941 (org-number-to-letters
2942 (string-to-number (match-string 2 s
))) "&")
2946 (defun org-letters-to-number (s)
2947 "Convert a base 26 number represented by letters into an integer.
2948 For example: AB -> 28."
2951 (while (> (length s
) 0)
2952 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
2956 (defun org-number-to-letters (n)
2957 "Convert an integer into a base 26 number represented by letters.
2958 For example: 28 -> AB."
2961 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
2965 (defun org-table-fedit-convert-buffer (function)
2966 "Convert all references in this buffer, using FUNCTION."
2967 (let ((line (org-current-line)))
2968 (goto-char (point-min))
2970 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
2971 (delete-region (point) (point-at-eol))
2972 (or (eobp) (forward-char 1)))
2973 (org-goto-line line
)))
2975 (defun org-table-fedit-toggle-ref-type ()
2976 "Convert all references in the buffer from B3 to @3$2 and back."
2978 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
2979 (org-table-fedit-convert-buffer
2980 (if org-table-buffer-is-an
2981 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
2982 (message "Reference type switched to %s"
2983 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
2985 (defun org-table-fedit-ref-up ()
2986 "Shift the reference at point one row/hline up."
2988 (org-table-fedit-shift-reference 'up
))
2989 (defun org-table-fedit-ref-down ()
2990 "Shift the reference at point one row/hline down."
2992 (org-table-fedit-shift-reference 'down
))
2993 (defun org-table-fedit-ref-left ()
2994 "Shift the reference at point one field to the left."
2996 (org-table-fedit-shift-reference 'left
))
2997 (defun org-table-fedit-ref-right ()
2998 "Shift the reference at point one field to the right."
3000 (org-table-fedit-shift-reference 'right
))
3002 (defun org-table-fedit-shift-reference (dir)
3004 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3005 (if (memq dir
'(left right
))
3006 (org-rematch-and-replace 1 (eq dir
'left
))
3007 (error "Cannot shift reference in this direction")))
3008 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3009 ;; A B3-like reference
3010 (if (memq dir
'(up down
))
3011 (org-rematch-and-replace 2 (eq dir
'up
))
3012 (org-rematch-and-replace 1 (eq dir
'left
))))
3014 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3015 ;; An internal reference
3016 (if (memq dir
'(up down
))
3017 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3018 (org-rematch-and-replace 5 (eq dir
'left
))))))
3020 (defun org-rematch-and-replace (n &optional decr hline
)
3021 "Re-match the group N, and replace it with the shifted reference."
3022 (or (match-end n
) (error "Cannot shift reference in this direction"))
3023 (goto-char (match-beginning n
))
3024 (and (looking-at (regexp-quote (match-string n
)))
3025 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3028 (defun org-table-shift-refpart (ref &optional decr hline
)
3029 "Shift a reference part REF.
3030 If DECR is set, decrease the references row/column, else increase.
3031 If HLINE is set, this may be a hline reference, it certainly is not
3032 a translation reference."
3034 (let* ((sign (string-match "^[-+]" ref
)) n
)
3036 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3038 ((and hline
(string-match "^I+" ref
))
3039 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3040 (setq n
(+ n
(if decr -
1 1)))
3041 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3043 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3045 (concat sign
(make-string n ?I
)))
3047 ((string-match "^[0-9]+" ref
)
3048 (setq n
(string-to-number (concat sign ref
)))
3049 (setq n
(+ n
(if decr -
1 1)))
3051 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3052 (number-to-string (max 1 n
))))
3054 ((string-match "^[a-zA-Z]+" ref
)
3055 (org-number-to-letters
3056 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3058 (t (error "Cannot shift reference"))))))
3060 (defun org-table-fedit-toggle-coordinates ()
3061 "Toggle the display of coordinates in the referenced table."
3063 (let ((pos (marker-position org-pos
)))
3064 (with-current-buffer (marker-buffer org-pos
)
3067 (org-table-toggle-coordinate-overlays)))))
3069 (defun org-table-fedit-finish (&optional arg
)
3070 "Parse the buffer for formula definitions and install them.
3071 With prefix ARG, apply the new formulas to the table."
3073 (org-table-remove-rectangle-highlight)
3074 (if org-table-use-standard-references
3076 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3077 (setq org-table-buffer-is-an nil
)))
3078 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3079 (goto-char (point-min))
3080 (while (re-search-forward
3081 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3083 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3084 form
(match-string 3))
3085 (setq form
(org-trim form
))
3086 (when (not (equal form
""))
3087 (while (string-match "[ \t]*\n[ \t]*" form
)
3088 (setq form
(replace-match " " t t form
)))
3089 (when (assoc var eql
)
3090 (error "Double formulas for %s" var
))
3091 (push (cons var form
) eql
)))
3093 (set-window-configuration org-window-configuration
)
3094 (select-window sel-win
)
3096 (unless (org-at-table-p)
3097 (error "Lost table position - cannot install formulas"))
3098 (org-table-store-formulas eql
)
3099 (move-marker pos nil
)
3100 (kill-buffer "*Edit Formulas*")
3102 (org-table-recalculate 'all
)
3103 (message "New formulas installed - press C-u C-c C-c to apply."))))
3105 (defun org-table-fedit-abort ()
3106 "Abort editing formulas, without installing the changes."
3108 (org-table-remove-rectangle-highlight)
3109 (let ((pos org-pos
) (sel-win org-selected-window
))
3110 (set-window-configuration org-window-configuration
)
3111 (select-window sel-win
)
3113 (move-marker pos nil
)
3114 (message "Formula editing aborted without installing changes")))
3116 (defun org-table-fedit-lisp-indent ()
3117 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3119 (let ((pos (point)) beg end ind
)
3120 (beginning-of-line 1)
3122 ((looking-at "[ \t]")
3124 (call-interactively 'lisp-indent-line
))
3125 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3126 ((not (fboundp 'pp-buffer
))
3127 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3128 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3129 (goto-char (- (match-end 0) 2))
3131 (setq ind
(make-string (current-column) ?\
))
3132 (condition-case nil
(forward-sexp 1)
3134 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3137 (narrow-to-region beg end
)
3138 (if (eq last-command this-command
)
3140 (goto-char (point-min))
3141 (setq this-command nil
)
3142 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3143 (replace-match " ")))
3145 (untabify (point-min) (point-max))
3146 (goto-char (1+ (point-min)))
3147 (while (re-search-forward "^." nil t
)
3148 (beginning-of-line 1)
3150 (goto-char (point-max))
3151 (backward-delete-char 1)))
3155 (defvar org-show-positions nil
)
3157 (defun org-table-show-reference (&optional local
)
3158 "Show the location/value of the $ expression at point."
3160 (org-table-remove-rectangle-highlight)
3162 (let ((pos (if local
(point) org-pos
))
3164 (org-inhibit-highlight-removal t
)
3165 (win (selected-window))
3166 (org-show-positions nil
)
3167 var name e what match dest
)
3168 (if local
(org-table-get-specials))
3170 ((or (org-at-regexp-p org-table-range-regexp2
)
3171 (org-at-regexp-p org-table-translate-regexp
)
3172 (org-at-regexp-p org-table-range-regexp
))
3175 (org-table-convert-refs-to-rc (match-string 0))))
3177 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3178 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3180 (t (error "No reference at point")))
3181 match
(and what
(or match
(match-string 0))))
3182 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3183 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3184 'secondary-selection
))
3185 (org-add-hook 'before-change-functions
3186 'org-table-remove-rectangle-highlight
)
3187 (if (eq what
'name
) (setq var
(substring match
1)))
3188 (when (eq what
'range
)
3189 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3190 (setq match
(org-table-formula-substitute-names match
)))
3194 (re-search-backward "^\\S-" nil t
)
3195 (beginning-of-line 1)
3196 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3199 (org-table-convert-refs-to-rc (match-string 1))))
3200 (org-table-add-rectangle-overlay
3201 (match-beginning 1) (match-end 1) face2
))))
3202 (if (and (markerp pos
) (marker-buffer pos
))
3203 (if (get-buffer-window (marker-buffer pos
))
3204 (select-window (get-buffer-window (marker-buffer pos
)))
3205 (org-switch-to-buffer-other-window (get-buffer-window
3206 (marker-buffer pos
)))))
3208 (org-table-force-dataline)
3210 (setq name
(substring dest
1))
3212 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3213 (setq e
(assoc name org-table-named-field-locations
))
3214 (org-goto-line (nth 1 e
))
3215 (org-table-goto-column (nth 2 e
)))
3216 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3217 (let ((l (string-to-number (match-string 1 dest
)))
3218 (c (string-to-number (match-string 2 dest
))))
3219 (org-goto-line (aref org-table-dlines l
))
3220 (org-table-goto-column c
)))
3221 (t (org-table-goto-column (string-to-number name
))))
3222 (move-marker pos
(point))
3223 (org-table-highlight-rectangle nil nil face2
))
3225 ((equal dest match
))
3230 (org-table-get-range match nil nil
'highlight
))
3232 ((setq e
(assoc var org-table-named-field-locations
))
3233 (org-goto-line (nth 1 e
))
3234 (org-table-goto-column (nth 2 e
))
3235 (org-table-highlight-rectangle (point) (point))
3236 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3237 ((setq e
(assoc var org-table-column-names
))
3238 (org-table-goto-column (string-to-number (cdr e
)))
3239 (org-table-highlight-rectangle (point) (point))
3240 (goto-char (org-table-begin))
3241 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3244 (goto-char (match-beginning 1))
3245 (org-table-highlight-rectangle)
3246 (message "Named column (column %s)" (cdr e
)))
3247 (error "Column name not found")))
3250 (org-table-goto-column (string-to-number (substring match
1)))
3251 (org-table-highlight-rectangle (point) (point))
3252 (message "Column %s" (substring match
1)))
3253 ((setq e
(assoc var org-table-local-parameters
))
3254 (goto-char (org-table-begin))
3255 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3257 (goto-char (match-beginning 1))
3258 (org-table-highlight-rectangle)
3259 (message "Local parameter."))
3260 (error "Parameter not found")))
3263 ((not var
) (error "No reference at point"))
3264 ((setq e
(assoc var org-table-formula-constants-local
))
3265 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3267 ((setq e
(assoc var org-table-formula-constants
))
3268 (message "Constant: $%s=%s in `org-table-formula-constants'."
3270 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3271 (message "Constant: $%s=%s, from `constants.el'%s."
3272 var e
(format " (%s units)" constants-unit-system
)))
3273 (t (error "Undefined name $%s" var
)))))
3275 (when (and org-show-positions
3276 (not (memq this-command
'(org-table-fedit-scroll
3277 org-table-fedit-scroll-down
))))
3278 (push pos org-show-positions
)
3279 (push org-table-current-begin-pos org-show-positions
)
3280 (let ((min (apply 'min org-show-positions
))
3281 (max (apply 'max org-show-positions
)))
3282 (goto-char min
) (recenter 0)
3284 (or (pos-visible-in-window-p max
) (recenter -
1))))
3285 (select-window win
))))
3287 (defun org-table-force-dataline ()
3288 "Make sure the cursor is in a dataline in a table."
3289 (unless (save-excursion
3290 (beginning-of-line 1)
3291 (looking-at org-table-dataline-regexp
))
3292 (let* ((re org-table-dataline-regexp
)
3293 (p1 (save-excursion (re-search-forward re nil
'move
)))
3294 (p2 (save-excursion (re-search-backward re nil
'move
))))
3296 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3298 ((or p1 p2
) (goto-char (or p1 p2
)))
3299 (t (error "No table dataline around here"))))))
3301 (defun org-table-fedit-line-up ()
3302 "Move cursor one line up in the window showing the table."
3304 (org-table-fedit-move 'previous-line
))
3306 (defun org-table-fedit-line-down ()
3307 "Move cursor one line down in the window showing the table."
3309 (org-table-fedit-move 'next-line
))
3311 (defun org-table-fedit-move (command)
3312 "Move the cursor in the window showing the table.
3313 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3314 (let ((org-table-allow-automatic-line-recalculation nil
)
3315 (pos org-pos
) (win (selected-window)) p
)
3316 (select-window (get-buffer-window (marker-buffer org-pos
)))
3318 (call-interactively command
)
3319 (while (and (org-at-table-p)
3320 (org-at-table-hline-p))
3321 (call-interactively command
))
3322 (or (org-at-table-p) (goto-char p
))
3323 (move-marker pos
(point))
3324 (select-window win
)))
3326 (defun org-table-fedit-scroll (N)
3328 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3329 (scroll-other-window N
)))
3331 (defun org-table-fedit-scroll-down (N)
3333 (org-table-fedit-scroll (- N
)))
3335 (defvar org-table-rectangle-overlays nil
)
3337 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3338 "Add a new overlay."
3339 (let ((ov (make-overlay beg end
)))
3340 (overlay-put ov
'face
(or face
'secondary-selection
))
3341 (push ov org-table-rectangle-overlays
)))
3343 (defun org-table-highlight-rectangle (&optional beg end face
)
3344 "Highlight rectangular region in a table."
3345 (setq beg
(or beg
(point)) end
(or end
(point)))
3346 (let ((b (min beg end
))
3349 (and (boundp 'org-show-positions
)
3350 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3351 (goto-char (min beg end
))
3352 (setq l1
(org-current-line)
3353 c1
(org-table-current-column))
3354 (goto-char (max beg end
))
3355 (setq l2
(org-current-line)
3356 c2
(org-table-current-column))
3357 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3359 (beginning-of-line 1)
3360 (loop for line from l1 to l2 do
3361 (when (looking-at org-table-dataline-regexp
)
3362 (org-table-goto-column c1
)
3363 (skip-chars-backward "^|\n") (setq beg
(point))
3364 (org-table-goto-column c2
)
3365 (skip-chars-forward "^|\n") (setq end
(point))
3366 (org-table-add-rectangle-overlay beg end face
))
3367 (beginning-of-line 2))
3369 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3371 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3372 "Remove the rectangle overlays."
3373 (unless org-inhibit-highlight-removal
3374 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3375 (mapc 'delete-overlay org-table-rectangle-overlays
)
3376 (setq org-table-rectangle-overlays nil
)))
3378 (defvar org-table-coordinate-overlays nil
3379 "Collects the coordinate grid overlays, so that they can be removed.")
3380 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3382 (defun org-table-overlay-coordinates ()
3383 "Add overlays to the table at point, to show row/column coordinates."
3385 (mapc 'delete-overlay org-table-coordinate-overlays
)
3386 (setq org-table-coordinate-overlays nil
)
3388 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3389 (goto-char (org-table-begin))
3390 (while (org-at-table-p)
3391 (setq eol
(point-at-eol))
3392 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
3393 (push ov org-table-coordinate-overlays
)
3394 (setq hline
(looking-at org-table-hline-regexp
))
3395 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3396 (format "%4d" (setq id
(1+ id
)))))
3397 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3400 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3401 (setq beg
(1+ (match-beginning 0))
3403 s1
(concat "$" (int-to-string ic
))
3404 s2
(org-number-to-letters ic
)
3405 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3406 (setq ov
(make-overlay beg
(+ beg
(length str
))))
3407 (push ov org-table-coordinate-overlays
)
3408 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3409 (beginning-of-line 2)))))
3411 (defun org-table-toggle-coordinate-overlays ()
3412 "Toggle the display of Row/Column numbers in tables."
3414 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3415 (message "Row/Column number display turned %s"
3416 (if org-table-overlay-coordinates
"on" "off"))
3417 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3419 (unless org-table-overlay-coordinates
3420 (mapc 'delete-overlay org-table-coordinate-overlays
)
3421 (setq org-table-coordinate-overlays nil
)))
3423 (defun org-table-toggle-formula-debugger ()
3424 "Toggle the formula debugger in tables."
3426 (setq org-table-formula-debug
(not org-table-formula-debug
))
3427 (message "Formula debugging has been turned %s"
3428 (if org-table-formula-debug
"on" "off")))
3430 ;;; The orgtbl minor mode
3432 ;; Define a minor mode which can be used in other modes in order to
3433 ;; integrate the org-mode table editor.
3435 ;; This is really a hack, because the org-mode table editor uses several
3436 ;; keys which normally belong to the major mode, for example the TAB and
3437 ;; RET keys. Here is how it works: The minor mode defines all the keys
3438 ;; necessary to operate the table editor, but wraps the commands into a
3439 ;; function which tests if the cursor is currently inside a table. If that
3440 ;; is the case, the table editor command is executed. However, when any of
3441 ;; those keys is used outside a table, the function uses `key-binding' to
3442 ;; look up if the key has an associated command in another currently active
3443 ;; keymap (minor modes, major mode, global), and executes that command.
3444 ;; There might be problems if any of the keys used by the table editor is
3445 ;; otherwise used as a prefix key.
3447 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3448 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3449 ;; addresses this by checking explicitly for both bindings.
3451 ;; The optimized version (see variable `orgtbl-optimized') takes over
3452 ;; all keys which are bound to `self-insert-command' in the *global map*.
3453 ;; Some modes bind other commands to simple characters, for example
3454 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3455 ;; active, this binding is ignored inside tables and replaced with a
3456 ;; modified self-insert.
3459 (defvar orgtbl-mode-map
(make-keymap)
3460 "Keymap for `orgtbl-mode'.")
3463 (defun turn-on-orgtbl ()
3464 "Unconditionally turn on `orgtbl-mode'."
3467 (defvar org-old-auto-fill-inhibit-regexp nil
3468 "Local variable used by `orgtbl-mode'.")
3470 (defconst orgtbl-line-start-regexp
3471 "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\|TBLNAME\\):\\)"
3472 "Matches a line belonging to an orgtbl.")
3474 (defconst orgtbl-extra-font-lock-keywords
3475 (list (list (concat "^" orgtbl-line-start-regexp
".*")
3476 0 (quote 'org-table
) 'prepend
))
3477 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
3479 ;; Install it as a minor mode.
3480 (put 'orgtbl-mode
:included t
)
3481 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
3484 (define-minor-mode orgtbl-mode
3485 "The `org-mode' table editor as a minor mode for use in other modes."
3486 :lighter
" OrgTbl" :keymap orgtbl-mode-map
3487 (org-load-modules-maybe)
3490 ;; Exit without error, in case some hook functions calls this
3491 ;; by accident in org-mode.
3492 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
3494 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
3495 ;; Make sure we are first in minor-mode-map-alist
3496 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
3497 ;; FIXME: maybe it should use emulation-mode-map-alists?
3498 (and c
(setq minor-mode-map-alist
3499 (cons c
(delq c minor-mode-map-alist
)))))
3500 (org-set-local (quote org-table-may-need-update
) t
)
3501 (org-add-hook 'before-change-functions
'org-before-change-function
3503 (org-set-local 'org-old-auto-fill-inhibit-regexp
3504 auto-fill-inhibit-regexp
)
3505 (org-set-local 'auto-fill-inhibit-regexp
3506 (if auto-fill-inhibit-regexp
3507 (concat orgtbl-line-start-regexp
"\\|"
3508 auto-fill-inhibit-regexp
)
3509 orgtbl-line-start-regexp
))
3510 (add-to-invisibility-spec '(org-cwidth))
3511 (when (fboundp 'font-lock-add-keywords
)
3512 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
3513 (org-restart-font-lock))
3514 (easy-menu-add orgtbl-mode-menu
))
3516 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
3517 (org-table-cleanup-narrow-column-properties)
3518 (org-remove-from-invisibility-spec '(org-cwidth))
3519 (remove-hook 'before-change-functions
'org-before-change-function t
)
3520 (when (fboundp 'font-lock-remove-keywords
)
3521 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
3522 (org-restart-font-lock))
3523 (easy-menu-remove orgtbl-mode-menu
)
3524 (force-mode-line-update 'all
))))
3526 (defun org-table-cleanup-narrow-column-properties ()
3527 "Remove all properties related to narrow-column invisibility."
3529 (while (setq s
(text-property-any s
(point-max)
3530 'display org-narrow-column-arrow
))
3531 (remove-text-properties s
(1+ s
) '(display t
)))
3533 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
3534 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
3536 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
3537 (remove-text-properties s
(1+ s
) '(invisible t
)))))
3539 (defun orgtbl-make-binding (fun n
&rest keys
)
3540 "Create a function for binding in the table minor mode.
3541 FUN is the command to call inside a table. N is used to create a unique
3542 command name. KEYS are keys that should be checked in for a command
3543 to execute outside of tables."
3546 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
3548 (concat "In tables, run `" (symbol-name fun
) "'.\n"
3549 "Outside of tables, run the binding of `"
3550 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
3555 (list 'call-interactively
(list 'quote fun
))
3556 (list 'let
'(orgtbl-mode)
3557 (list 'call-interactively
3560 (list 'key-binding k
))
3562 '('orgtbl-error
))))))))
3564 (defun orgtbl-error ()
3565 "Error when there is no default binding for a table key."
3567 (error "This key has no function outside tables"))
3569 (defun orgtbl-setup ()
3570 "Setup orgtbl keymaps."
3573 '(([(meta shift left
)] org-table-delete-column
)
3574 ([(meta left
)] org-table-move-column-left
)
3575 ([(meta right
)] org-table-move-column-right
)
3576 ([(meta shift right
)] org-table-insert-column
)
3577 ([(meta shift up
)] org-table-kill-row
)
3578 ([(meta shift down
)] org-table-insert-row
)
3579 ([(meta up
)] org-table-move-row-up
)
3580 ([(meta down
)] org-table-move-row-down
)
3581 ("\C-c\C-w" org-table-cut-region
)
3582 ("\C-c\M-w" org-table-copy-region
)
3583 ("\C-c\C-y" org-table-paste-rectangle
)
3584 ("\C-c-" org-table-insert-hline
)
3585 ("\C-c}" org-table-toggle-coordinate-overlays
)
3586 ("\C-c{" org-table-toggle-formula-debugger
)
3587 ("\C-m" org-table-next-row
)
3588 ([(shift return
)] org-table-copy-down
)
3589 ("\C-c?" org-table-field-info
)
3590 ("\C-c " org-table-blank-field
)
3591 ("\C-c+" org-table-sum
)
3592 ("\C-c=" org-table-eval-formula
)
3593 ("\C-c'" org-table-edit-formulas
)
3594 ("\C-c`" org-table-edit-field
)
3595 ("\C-c*" org-table-recalculate
)
3596 ("\C-c^" org-table-sort-lines
)
3597 ("\M-a" org-table-beginning-of-field
)
3598 ("\M-e" org-table-end-of-field
)
3599 ([(control ?
#)] org-table-rotate-recalc-marks
)))
3601 (while (setq elt
(pop bindings
))
3602 (setq nfunc
(1+ nfunc
))
3603 (setq key
(org-key (car elt
))
3605 cmd
(orgtbl-make-binding fun nfunc key
))
3606 (org-defkey orgtbl-mode-map key cmd
))
3608 ;; Special treatment needed for TAB and RET
3609 (org-defkey orgtbl-mode-map
[(return)]
3610 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
3611 (org-defkey orgtbl-mode-map
"\C-m"
3612 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
3614 (org-defkey orgtbl-mode-map
[(tab)]
3615 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
3616 (org-defkey orgtbl-mode-map
"\C-i"
3617 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
3619 (org-defkey orgtbl-mode-map
[(shift tab
)]
3620 (orgtbl-make-binding 'org-table-previous-field
104
3621 [(shift tab
)] [(tab)] "\C-i"))
3624 (unless (featurep 'xemacs
)
3625 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
3626 (orgtbl-make-binding 'org-table-previous-field
107
3627 [S-iso-lefttab
] [backtab] [(shift tab)]
3630 (org-defkey orgtbl-mode-map [backtab]
3631 (orgtbl-make-binding 'org-table-previous-field
108
3632 [backtab] [S-iso-lefttab] [(shift tab)]
3635 (org-defkey orgtbl-mode-map "\M-\C-m"
3636 (orgtbl-make-binding 'org-table-wrap-region 105
3637 "\M-\C-m" [(meta return)]))
3638 (org-defkey orgtbl-mode-map [(meta return)]
3639 (orgtbl-make-binding 'org-table-wrap-region 106
3640 [(meta return)] "\M-\C-m"))
3642 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
3643 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
3645 (when orgtbl-optimized
3646 ;; If the user wants maximum table support, we need to hijack
3647 ;; some standard editing functions
3648 (org-remap orgtbl-mode-map
3649 'self-insert-command 'orgtbl-self-insert-command
3650 'delete-char 'org-delete-char
3651 'delete-backward-char 'org-delete-backward-char)
3652 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
3653 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
3655 ["Create or convert" org-table-create-or-convert-from-region
3656 :active (not (org-at-table-p)) :keys "C-c |" ]
3658 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
3659 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
3660 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
3661 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
3663 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
3664 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
3665 ["Copy Field from Above"
3666 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
3669 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
3670 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
3671 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
3672 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
3674 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
3675 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
3676 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
3677 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
3678 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
3680 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
3682 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
3683 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
3684 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
3685 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
3688 ["Insert table template" orgtbl-insert-radio-table
3689 (assq major-mode orgtbl-radio-table-templates)]
3690 ["Comment/uncomment table" orgtbl-toggle-comment t])
3692 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
3693 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
3694 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
3695 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
3696 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
3697 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
3698 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
3699 ["Sum Column/Rectangle" org-table-sum
3700 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
3701 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
3703 org-table-toggle-formula-debugger :active (org-at-table-p)
3705 :style toggle :selected org-table-formula-debug]
3706 ["Show Col/Row Numbers"
3707 org-table-toggle-coordinate-overlays :active (org-at-table-p)
3709 :style toggle :selected org-table-overlay-coordinates]
3713 (defun orgtbl-ctrl-c-ctrl-c (arg)
3714 "If the cursor is inside a table, realign the table.
3715 If it is a table to be sent away to a receiver, do it.
3716 With prefix arg, also recompute table."
3718 (let ((pos (point)) action)
3720 (beginning-of-line 1)
3721 (setq action (cond ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
3722 ((looking-at "[ \t]*|") pos)
3723 ((looking-at "[ \t]*#\\+TBLFM:") 'recalc))))
3727 (org-table-maybe-eval-formula)
3729 (call-interactively 'org-table-recalculate)
3730 (org-table-maybe-recalculate-line))
3731 (call-interactively 'org-table-align)
3732 (orgtbl-send-table 'maybe))
3733 ((eq action 'recalc)
3735 (beginning-of-line 1)
3736 (skip-chars-backward " \r\n\t")
3737 (if (org-at-table-p)
3738 (org-call-with-arg 'org-table-recalculate t))))
3739 (t (let (orgtbl-mode)
3740 (call-interactively (key-binding "\C-c\C-c")))))))
3742 (defun orgtbl-create-or-convert-from-region (arg)
3743 "Create table or convert region to table, if no conflicting binding.
3744 This installs the table binding `C-c |', but only if there is no
3745 conflicting binding to this key outside orgtbl-mode."
3747 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
3749 (call-interactively cmd)
3750 (call-interactively 'org-table-create-or-convert-from-region))))
3752 (defun orgtbl-tab (arg)
3753 "Justification and field motion for `orgtbl-mode'."
3755 (if arg (org-table-edit-field t)
3756 (org-table-justify-field-maybe)
3757 (org-table-next-field)))
3759 (defun orgtbl-ret ()
3760 "Justification and field motion for `orgtbl-mode'."
3764 (org-table-justify-field-maybe)
3765 (org-table-next-row)))
3767 (defun orgtbl-self-insert-command (N)
3768 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
3769 If the cursor is in a table looking at whitespace, the whitespace is
3770 overwritten, and the table is not marked as requiring realignment."
3772 (if (and (org-at-table-p)
3774 (and org-table-auto-blank-field
3775 (member last-command
3776 '(orgtbl-hijacker-command-100
3777 orgtbl-hijacker-command-101
3778 orgtbl-hijacker-command-102
3779 orgtbl-hijacker-command-103
3780 orgtbl-hijacker-command-104
3781 orgtbl-hijacker-command-105
3783 (org-table-blank-field))
3786 (looking-at "[^|\n]* +|"))
3787 (let (org-table-may-need-update)
3788 (goto-char (1- (match-end 0)))
3789 (delete-backward-char 1)
3790 (goto-char (match-beginning 0))
3791 (self-insert-command N))
3792 (setq org-table-may-need-update t)
3795 (cmd (or (key-binding
3796 (or (and (listp function-key-map)
3797 (setq a (assoc last-input-event function-key-map))
3799 (vector last-input-event)))
3800 'self-insert-command)))
3801 (call-interactively cmd)
3802 (if (and org-self-insert-cluster-for-undo
3803 (eq cmd 'self-insert-command))
3804 (if (not (eq last-command 'orgtbl-self-insert-command))
3805 (setq org-self-insert-command-undo-counter 1)
3806 (if (>= org-self-insert-command-undo-counter 20)
3807 (setq org-self-insert-command-undo-counter 1)
3808 (and (> org-self-insert-command-undo-counter 0)
3810 (not (cadr buffer-undo-list)) ; remove nil entry
3811 (setcdr buffer-undo-list (cddr buffer-undo-list)))
3812 (setq org-self-insert-command-undo-counter
3813 (1+ org-self-insert-command-undo-counter))))))))
3815 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
3816 "Regular expression matching exponentials as produced by calc.")
3818 (defun orgtbl-export (table target)
3820 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
3821 (lines (org-split-string table "[ \t]*\n[ \t]*"))
3822 org-table-last-alignment org-table-last-column-widths
3824 (if (not (fboundp func))
3825 (error "Cannot export orgtbl table to %s" target))
3826 (setq lines (org-table-clean-before-export lines))
3830 (if (string-match org-table-hline-regexp x)
3832 (org-split-string (org-trim x) "\\s-*|\\s-*")))
3834 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
3836 (loop for i from (1- maxcol) downto 0 do
3837 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
3838 (setq column (delq nil column))
3839 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
3840 (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))
3841 (funcall func table nil)))
3843 (defun orgtbl-gather-send-defs ()
3844 "Gather a plist of :name, :transform, :params for each destination before
3847 (goto-char (org-table-begin))
3849 (beginning-of-line 0)
3850 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
3851 (let ((name (org-no-properties (match-string 1)))
3852 (transform (intern (match-string 2)))
3853 (params (if (match-end 3)
3854 (read (concat "(" (match-string 3) ")")))))
3855 (push (list :name name :transform transform :params params)
3857 (beginning-of-line 0)))
3860 (defun orgtbl-send-replace-tbl (name txt)
3861 "Find and replace table NAME with TXT."
3863 (goto-char (point-min))
3864 (unless (re-search-forward
3865 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
3866 (error "Don't know where to insert translated table"))
3867 (goto-char (match-beginning 0))
3868 (beginning-of-line 2)
3870 (let ((beg (point)))
3871 (unless (re-search-forward
3872 (concat "END RECEIVE ORGTBL +" name) nil t)
3873 (error "Cannot find end of insertion region"))
3874 (beginning-of-line 1)
3875 (delete-region beg (point))))
3879 (defun org-table-to-lisp (&optional txt)
3880 "Convert the table at point to a Lisp structure.
3881 The structure will be a list. Each item is either the symbol `hline'
3882 for a horizontal separator line, or a list of field values as strings.
3883 The table is taken from the parameter TXT, or from the buffer at point."
3885 (unless (org-at-table-p)
3886 (error "No table at point")))
3888 (buffer-substring-no-properties (org-table-begin)
3890 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
3894 (if (string-match org-table-hline-regexp x)
3896 (org-split-string (org-trim x) "\\s-*|\\s-*")))
3899 (defun orgtbl-send-table (&optional maybe)
3900 "Send a transformed version of this table to the receiver position.
3901 With argument MAYBE, fail quietly if no transformation is defined for
3905 (unless (org-at-table-p) (error "Not at a table"))
3906 ;; when non-interactive, we assume align has just happened.
3907 (when (interactive-p) (org-table-align))
3908 (let ((dests (orgtbl-gather-send-defs))
3909 (txt (buffer-substring-no-properties (org-table-begin)
3912 (unless dests (if maybe (throw 'exit nil)
3913 (error "Don't know how to transform this table")))
3914 (dolist (dest dests)
3915 (let* ((name (plist-get dest :name))
3916 (transform (plist-get dest :transform))
3917 (params (plist-get dest :params))
3918 (skip (plist-get params :skip))
3919 (skipcols (plist-get params :skipcols))
3921 (lines (org-table-clean-before-export
3923 (org-split-string txt "[ \t]*\n[ \t]*"))))
3924 (i0 (if org-table-clean-did-remove-column 2 1))
3927 (if (string-match org-table-hline-regexp x)
3929 (org-remove-by-index
3930 (org-split-string (org-trim x) "\\s-*|\\s-*")
3933 (fun (if (= i0 2) 'cdr 'identity))
3934 (org-table-last-alignment
3935 (org-remove-by-index (funcall fun org-table-last-alignment)
3937 (org-table-last-column-widths
3938 (org-remove-by-index (funcall fun org-table-last-column-widths)
3940 (txt (if (fboundp transform)
3941 (funcall transform table params)
3942 (error "No such transformation function %s" transform))))
3943 (orgtbl-send-replace-tbl name txt))
3944 (setq ntbl (1+ ntbl)))
3945 (message "Table converted and installed at %d receiver location%s"
3946 ntbl (if (> ntbl 1) "s" "")))))
3948 (defun org-remove-by-index (list indices &optional i0)
3949 "Remove the elements in LIST with indices in INDICES.
3950 First element has index 0, or I0 if given."
3953 (if (integerp indices) (setq indices (list indices)))
3954 (setq i0 (1- (or i0 0)))
3955 (delq :rm (mapcar (lambda (x)
3957 (if (memq i0 indices) :rm x))
3960 (defun orgtbl-toggle-comment ()
3961 "Comment or uncomment the orgtbl at point."
3963 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
3964 (re2 (concat "^" orgtbl-line-start-regexp))
3965 (commented (save-excursion (beginning-of-line 1)
3966 (cond ((looking-at re1) t)
3967 ((looking-at re2) nil)
3968 (t (error "Not at an org table")))))
3969 (re (if commented re1 re2))
3972 (beginning-of-line 1)
3973 (while (looking-at re) (beginning-of-line 0))
3974 (beginning-of-line 2)
3976 (while (looking-at re) (beginning-of-line 2))
3978 (comment-region beg end (if commented '(4) nil))))
3980 (defun orgtbl-insert-radio-table ()
3981 "Insert a radio table template appropriate for this major mode."
3983 (let* ((e (assq major-mode orgtbl-radio-table-templates))
3986 (unless e (error "No radio table setup defined for %s" major-mode))
3987 (setq name (read-string "Table name: "))
3988 (while (string-match "%n" txt)
3989 (setq txt (replace-match name t t txt)))
3990 (or (bolp) (insert "\n"))
3995 ;; Dynamically bound input and output for table formatting.
3996 (defvar *orgtbl-table* nil
3997 "Carries the current table through formatting routines.")
3998 (defvar *orgtbl-rtn* nil
3999 "Formatting routines push the output lines here.")
4000 ;; Formatting parameters for the current table section.
4001 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4002 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4003 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4004 (defvar *orgtbl-fmt* nil "Format for each entry.")
4005 (defvar *orgtbl-efmt* nil "Format for numbers.")
4006 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4007 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4008 (defvar *orgtbl-lstart* nil "Text starting a row.")
4009 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4010 (defvar *orgtbl-lend* nil "Text ending a row.")
4011 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4013 (defsubst orgtbl-get-fmt (fmt i)
4014 "Retrieve the format from FMT corresponding to the Ith column."
4015 (if (and (not (functionp fmt)) (consp fmt))
4019 (defsubst orgtbl-apply-fmt (fmt &rest args)
4020 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4021 (cond ((functionp fmt) (apply fmt args))
4022 (fmt (apply 'format fmt args))
4026 (defsubst orgtbl-eval-str (str)
4027 "If STR is a function, evaluate it with no arguments."
4032 (defun orgtbl-format-line (line)
4033 "Format LINE as a table row."
4034 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4040 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4041 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4042 (orgtbl-apply-fmt efmt (match-string 1 f)
4045 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4046 *orgtbl-default-fmt*)
4049 (push (if *orgtbl-lfmt*
4050 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4051 (concat (orgtbl-eval-str *orgtbl-lstart*)
4052 (mapconcat 'identity line *orgtbl-sep*)
4053 (orgtbl-eval-str *orgtbl-lend*)))
4056 (defun orgtbl-format-section (section-stopper)
4057 "Format lines until the first occurrence of SECTION-STOPPER."
4060 (while (not (eq (car *orgtbl-table*) section-stopper))
4061 (if prevline (orgtbl-format-line prevline))
4062 (setq prevline (pop *orgtbl-table*)))
4063 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4064 (*orgtbl-lend* *orgtbl-llend*)
4065 (*orgtbl-lfmt* *orgtbl-llfmt*))
4066 (orgtbl-format-line prevline))))))
4068 (defun orgtbl-to-generic (table params)
4069 "Convert the orgtbl-mode TABLE to some other format.
4070 This generic routine can be used for many standard cases.
4071 TABLE is a list, each entry either the symbol `hline' for a horizontal
4072 separator line, or a list of fields for that line.
4073 PARAMS is a property list of parameters that can influence the conversion.
4074 For the generic converter, some parameters are obligatory: You need to
4075 specify either :lfmt, or all of (:lstart :lend :sep).
4077 Valid parameters are
4079 :splice When set to t, return only table body lines, don't wrap
4080 them into :tstart and :tend. Default is nil. When :splice
4081 is non-nil, this also means that the exporter should not look
4082 for and interpret header and footer sections.
4084 :hline String to be inserted on horizontal separation lines.
4085 May be nil to ignore hlines.
4087 :sep Separator between two fields
4088 :remove-nil-lines Do not include lines that evaluate to nil.
4091 Each in the following group may be either a string or a function
4092 of no arguments returning a string:
4093 :tstart String to start the table. Ignored when :splice is t.
4094 :tend String to end the table. Ignored when :splice is t.
4095 :lstart String to start a new table line.
4096 :llstart String to start the last table line, defaults to :lstart.
4097 :lend String to end a table line
4098 :llend String to end the last table line, defaults to :lend.
4100 Each in the following group may be a string, a function of one
4101 argument (the field or line) returning a string, or a plist
4102 mapping columns to either of the above:
4103 :lfmt Format for entire line, with enough %s to capture all fields.
4104 If this is present, :lstart, :lend, and :sep are ignored.
4105 :llfmt Format for the entire last line, defaults to :lfmt.
4106 :fmt A format to be used to wrap the field, should contain
4107 %s for the original field value. For example, to wrap
4108 everything in dollars, you could use :fmt \"$%s$\".
4109 This may also be a property list with column numbers and
4110 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4112 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4113 Same as above, specific for the header lines in the table.
4114 All lines before the first hline are treated as header.
4115 If any of these is not present, the data line value is used.
4117 This may be either a string or a function of two arguments:
4118 :efmt Use this format to print numbers with exponentials.
4119 The format should have %s twice for inserting mantissa
4120 and exponent, for example \"%s\\\\times10^{%s}\". This
4121 may also be a property list with column numbers and
4122 formats. :fmt will still be applied after :efmt.
4124 In addition to this, the parameters :skip and :skipcols are always handled
4125 directly by `orgtbl-send-table'. See manual."
4128 (let* ((splicep (plist-get params :splice))
4129 (hline (plist-get params :hline))
4130 (remove-nil-linesp (plist-get params :remove-nil-lines))
4131 (remove-newlines (plist-get params :remove-newlines))
4132 (*orgtbl-hline* hline)
4133 (*orgtbl-table* table)
4134 (*orgtbl-sep* (plist-get params :sep))
4135 (*orgtbl-efmt* (plist-get params :efmt))
4136 (*orgtbl-lstart* (plist-get params :lstart))
4137 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4138 (*orgtbl-lend* (plist-get params :lend))
4139 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4140 (*orgtbl-lfmt* (plist-get params :lfmt))
4141 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4142 (*orgtbl-fmt* (plist-get params :fmt))
4147 (when (plist-member params :tstart)
4148 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4149 (if tstart (push tstart *orgtbl-rtn*)))))
4151 ;; Do we have a heading section? If so, format it and handle the
4153 (if (and (not splicep)
4154 (or (consp (car *orgtbl-table*))
4155 (consp (nth 1 *orgtbl-table*)))
4156 (memq 'hline (cdr *orgtbl-table*)))
4158 (when (eq 'hline (car *orgtbl-table*))
4159 ;; there is a hline before the first data line
4160 (and hline (push hline *orgtbl-rtn*))
4161 (pop *orgtbl-table*))
4162 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4164 (*orgtbl-llstart* (or (plist-get params :hllstart)
4166 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4167 (*orgtbl-llend* (or (plist-get params :hllend)
4168 (plist-get params :hlend) *orgtbl-llend*))
4169 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4170 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4171 (plist-get params :hlfmt) *orgtbl-llfmt*))
4172 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4173 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4174 (orgtbl-format-section 'hline))
4175 (if hline (push hline *orgtbl-rtn*))
4176 (pop *orgtbl-table*)))
4178 ;; Now format the main section.
4179 (orgtbl-format-section nil)
4182 (when (plist-member params :tend)
4183 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4184 (if tend (push tend *orgtbl-rtn*)))))
4186 (mapconcat (if remove-newlines
4188 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4190 (nreverse (if remove-nil-linesp
4191 (remq nil *orgtbl-rtn*)
4192 *orgtbl-rtn*)) "\n")))
4194 (defun orgtbl-to-tsv (table params)
4195 "Convert the orgtbl-mode table to TAB separated material."
4196 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4197 (defun orgtbl-to-csv (table params)
4198 "Convert the orgtbl-mode table to CSV material.
4199 This does take care of the proper quoting of fields with comma or quotes."
4200 (orgtbl-to-generic table (org-combine-plists
4201 '(:sep "," :fmt org-quote-csv-field)
4204 (defun orgtbl-to-latex (table params)
4205 "Convert the orgtbl-mode TABLE to LaTeX.
4206 TABLE is a list, each entry either the symbol `hline' for a horizontal
4207 separator line, or a list of fields for that line.
4208 PARAMS is a property list of parameters that can influence the conversion.
4209 Supports all parameters from `orgtbl-to-generic'. Most important for
4212 :splice When set to t, return only table body lines, don't wrap
4213 them into a tabular environment. Default is nil.
4215 :fmt A format to be used to wrap the field, should contain %s for the
4216 original field value. For example, to wrap everything in dollars,
4217 use :fmt \"$%s$\". This may also be a property list with column
4218 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4219 The format may also be a function that formats its one argument.
4221 :efmt Format for transforming numbers with exponentials. The format
4222 should have %s twice for inserting mantissa and exponent, for
4223 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4224 This may also be a property list with column numbers and formats.
4225 The format may also be a function that formats its two arguments.
4227 :llend If you find too much space below the last line of a table,
4228 pass a value of \"\" for :llend to suppress the final \\\\.
4230 The general parameters :skip and :skipcols have already been applied when
4231 this function is called."
4232 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4233 org-table-last-alignment ""))
4236 :tstart (concat "\\begin{tabular}{" alignment "}")
4237 :tend "\\end{tabular}"
4238 :lstart "" :lend " \\\\" :sep " & "
4239 :efmt "%s\\,(%s)" :hline "\\hline")))
4240 (orgtbl-to-generic table (org-combine-plists params2 params))))
4242 (defun orgtbl-to-html (table params)
4243 "Convert the orgtbl-mode TABLE to HTML.
4244 TABLE is a list, each entry either the symbol `hline' for a horizontal
4245 separator line, or a list of fields for that line.
4246 PARAMS is a property list of parameters that can influence the conversion.
4247 Currently this function recognizes the following parameters:
4249 :splice When set to t, return only table body lines, don't wrap
4250 them into a <table> environment. Default is nil.
4252 The general parameters :skip and :skipcols have already been applied when
4253 this function is called. The function does *not* use `orgtbl-to-generic',
4254 so you cannot specify parameters for it."
4255 (let* ((splicep (plist-get params :splice))
4256 (html-table-tag org-export-html-table-tag)
4258 ;; Just call the formatter we already have
4259 ;; We need to make text lines for it, so put the fields back together.
4260 (setq html (org-format-org-table-html
4265 (concat "| " (mapconcat 'org-html-expand x " | ") " |")))
4268 (if (string-match "\n+\\'" html)
4269 (setq html (replace-match "" t t html)))
4272 (defun orgtbl-to-texinfo (table params)
4273 "Convert the orgtbl-mode TABLE to TeXInfo.
4274 TABLE is a list, each entry either the symbol `hline' for a horizontal
4275 separator line, or a list of fields for that line.
4276 PARAMS is a property list of parameters that can influence the conversion.
4277 Supports all parameters from `orgtbl-to-generic'. Most important for
4280 :splice nil/t When set to t, return only table body lines, don't wrap
4281 them into a multitable environment. Default is nil.
4283 :fmt fmt A format to be used to wrap the field, should contain
4284 %s for the original field value. For example, to wrap
4285 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4286 This may also be a property list with column numbers and
4287 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4288 Each format also may be a function that formats its one
4291 :cf \"f1 f2..\" The column fractions for the table. By default these
4292 are computed automatically from the width of the columns
4295 The general parameters :skip and :skipcols have already been applied when
4296 this function is called."
4297 (let* ((total (float (apply '+ org-table-last-column-widths)))
4298 (colfrac (or (plist-get params :cf)
4300 (lambda (x) (format "%.3f" (/ (float x) total)))
4301 org-table-last-column-widths " ")))
4304 :tstart (concat "@multitable @columnfractions " colfrac)
4305 :tend "@end multitable"
4306 :lstart "@item " :lend "" :sep " @tab "
4307 :hlstart "@headitem ")))
4308 (orgtbl-to-generic table (org-combine-plists params2 params))))
4310 (defun orgtbl-to-orgtbl (table params)
4311 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4312 Useful when slicing one table into many. The :hline, :sep,
4313 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4314 and :tend suppress strings without splicing; they can be set to
4315 provide ORGTBL directives for the generated table."
4319 :tstart nil :tend nil
4324 (params (org-combine-plists params2 params)))
4325 (orgtbl-to-generic table params)))
4327 (defun org-table-get-remote-range (name-or-id form)
4328 "Get a field value or a list of values in a range from table at ID.
4330 NAME-OR-ID may be the name of a table in the current file as set by
4331 a \"#+TBLNAME:\" directive. The first table following this line
4332 will then be used. Alternatively, it may be an ID referring to
4333 any entry, also in a different file. In this case, the first table
4334 in that entry will be referenced.
4335 FORM is a field or range descriptor like \"@2$3\" or or \"B3\" or
4336 \"@I$2..@II$2\". All the references must be absolute, not relative.
4338 The return value is either a single string for a single field, or a
4339 list of the fields in the rectangle ."
4342 org-table-column-names org-table-column-name-regexp
4343 org-table-local-parameters org-table-named-field-locations
4344 org-table-current-line-types org-table-current-begin-line
4345 org-table-current-begin-pos org-table-dlines
4346 org-table-hlines org-table-last-alignment
4347 org-table-last-column-widths org-table-last-alignment
4348 org-table-last-column-widths tbeg
4350 (setq form (org-table-convert-refs-to-rc form))
4355 (goto-char (point-min))
4356 (if (re-search-forward
4357 (concat "^[ \t]*#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4359 (setq buffer (current-buffer) loc (match-beginning 0))
4360 (setq id-loc (org-id-find name-or-id 'marker))
4361 (unless (and id-loc (markerp id-loc))
4362 (error "Can't find remote table \"%s\"" name-or-id))
4363 (setq buffer (marker-buffer id-loc)
4364 loc (marker-position id-loc))
4365 (move-marker id-loc nil)))
4366 (with-current-buffer buffer
4372 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4373 (not (match-beginning 1)))
4374 (error "Cannot find a table at NAME or ID %s" name-or-id))
4375 (setq tbeg (point-at-bol))
4376 (org-table-get-specials)
4377 (setq form (org-table-formula-substitute-names form))
4378 (if (and (string-match org-table-range-regexp form)
4379 (> (length (match-string 0 form)) 1))
4381 (org-table-get-range (match-string 0 form) tbeg 1))
4384 (provide 'org-table)
4386 ;; arch-tag: 4d21cfdd-0268-440a-84b0-09237a0fe0ef
4388 ;;; org-table.el ends here