1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;; This file contains the table editor and spreadsheed for Org-mode.
30 ;; Watch out: Here we are talking about two different kind of tables.
31 ;; Most of the code is for the tables created with the Org-mode table editor.
32 ;; Sometimes, we talk about tables created and edited with the table.el
33 ;; Emacs package. We call the former org-type tables, and the latter
34 ;; table.el-type tables.
42 (declare-function org-table-clean-before-export
"org-exp" (lines))
43 (declare-function org-format-org-table-html
"org-exp" (lines &optional splice
))
44 (defvar orgtbl-mode
) ; defined below
45 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
47 (defvar constants-unit-system
)
49 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
50 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
51 In the optimized version, the table editor takes over all simple keys that
52 normally just insert a character. In tables, the characters are inserted
53 in a way to minimize disturbing the table structure (i.e. in overwrite mode
54 for empty fields). Outside tables, the correct binding of the keys is
57 The default for this option is t if the optimized version is also used in
58 Org-mode. See the variable `org-enable-table-editor' for details. Changing
59 this variable requires a restart of Emacs to become effective."
63 (defcustom orgtbl-radio-table-templates
64 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
65 % END RECEIVE ORGTBL %n
67 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
70 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
71 @c END RECEIVE ORGTBL %n
73 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
76 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
77 <!-- END RECEIVE ORGTBL %n -->
79 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
82 "Templates for radio tables in different major modes.
83 All occurrences of %n in a template will be replaced with the name of the
84 table, obtained by prompting the user."
87 (list (symbol :tag
"Major mode")
88 (string :tag
"Format"))))
90 (defgroup org-table-settings nil
91 "Settings for tables in Org-mode."
92 :tag
"Org Table Settings"
95 (defcustom org-table-default-size
"5x2"
96 "The default size for newly created tables, Columns x Rows."
97 :group
'org-table-settings
100 (defcustom org-table-number-regexp
101 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
102 "Regular expression for recognizing numbers in table columns.
103 If a table column contains mostly numbers, it will be aligned to the
104 right. If not, it will be aligned to the left.
106 The default value of this option is a regular expression which allows
107 anything which looks remotely like a number as used in scientific
108 context. For example, all of the following will be considered a
110 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
112 Other options offered by the customize interface are more restrictive."
113 :group
'org-table-settings
115 (const :tag
"Positive Integers"
117 (const :tag
"Integers"
119 (const :tag
"Floating Point Numbers"
120 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
121 (const :tag
"Floating Point Number or Integer"
122 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
123 (const :tag
"Exponential, Floating point, Integer"
124 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
125 (const :tag
"Very General Number-Like, including hex"
126 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
127 (string :tag
"Regexp:")))
129 (defcustom org-table-number-fraction
0.5
130 "Fraction of numbers in a column required to make the column align right.
131 In a column all non-white fields are considered. If at least this
132 fraction of fields is matched by `org-table-number-fraction',
133 alignment to the right border applies."
134 :group
'org-table-settings
137 (defgroup org-table-editing nil
138 "Behavior of tables during editing in Org-mode."
139 :tag
"Org Table Editing"
142 (defcustom org-table-automatic-realign t
143 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
144 When nil, aligning is only done with \\[org-table-align], or after column
146 :group
'org-table-editing
149 (defcustom org-table-auto-blank-field t
150 "Non-nil means, automatically blank table field when starting to type into it.
151 This only happens when typing immediately after a field motion
152 command (TAB, S-TAB or RET).
153 Only relevant when `org-enable-table-editor' is equal to `optimized'."
154 :group
'org-table-editing
157 (defcustom org-table-tab-jumps-over-hlines t
158 "Non-nil means, tab in the last column of a table with jump over a hline.
159 If a horizontal separator line is following the current line,
160 `org-table-next-field' can either create a new row before that line, or jump
161 over the line. When this option is nil, a new line will be created before
163 :group
'org-table-editing
166 (defgroup org-table-calculation nil
167 "Options concerning tables in Org-mode."
168 :tag
"Org Table Calculation"
171 (defcustom org-table-use-standard-references t
172 "Should org-mode work with table refrences like B3 instead of @3$2?
175 from accept as input, do not present for editing
176 t: accept as input and present for editing"
177 :group
'org-table-calculation
179 (const :tag
"Never, don't even check user input for them" nil
)
180 (const :tag
"Always, both as user input, and when editing" t
)
181 (const :tag
"Convert user input, don't offer during editing" 'from
)))
183 (defcustom org-table-copy-increment t
184 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
185 :group
'org-table-calculation
188 (defcustom org-calc-default-modes
189 '(calc-internal-prec 12
190 calc-float-format
(float 8)
193 calc-symbolic-mode nil
194 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " HH
":" mm
))
195 calc-display-working-message t
197 "List with Calc mode settings for use in calc-eval for table formulas.
198 The list must contain alternating symbols (Calc modes variables and values).
199 Don't remove any of the default settings, just change the values. Org-mode
200 relies on the variables to be present in the list."
201 :group
'org-table-calculation
204 (defcustom org-table-formula-evaluate-inline t
205 "Non-nil means, TAB and RET evaluate a formula in current table field.
206 If the current field starts with an equal sign, it is assumed to be a formula
207 which should be evaluated as described in the manual and in the documentation
208 string of the command `org-table-eval-formula'. This feature requires the
210 When this variable is nil, formula calculation is only available through
211 the command \\[org-table-eval-formula]."
212 :group
'org-table-calculation
215 (defcustom org-table-formula-use-constants t
216 "Non-nil means, interpret constants in formulas in tables.
217 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
218 by the value given in `org-table-formula-constants', or by a value obtained
219 from the `constants.el' package."
220 :group
'org-table-calculation
223 (defcustom org-table-formula-constants nil
224 "Alist with constant names and values, for use in table formulas.
225 The car of each element is a name of a constant, without the `$' before it.
226 The cdr is the value as a string. For example, if you'd like to use the
227 speed of light in a formula, you would configure
229 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
231 and then use it in an equation like `$1*$c'.
233 Constants can also be defined on a per-file basis using a line like
235 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
236 :group
'org-table-calculation
238 (cons (string :tag
"name")
239 (string :tag
"value"))))
241 (defcustom org-table-allow-automatic-line-recalculation t
242 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
243 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
244 :group
'org-table-calculation
247 (defgroup org-table-import-export nil
248 "Options concerning table import and export in Org-mode."
249 :tag
"Org Table Import Export"
252 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
253 "Default export parameters for org-table-export. These can be
254 overridden on for a specific table by setting the TABLE_EXPORT_FORMAT
255 property. See the manual section on orgtbl radio tables for the different
256 export transformations and available parameters."
257 :group
'org-table-import-export
260 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
261 "Detects a table line marked for automatic recalculation.")
262 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
263 "Detects a table line marked for automatic recalculation.")
264 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
265 "Detects a table line marked for automatic recalculation.")
266 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
267 "Searching from within a table (any type) this finds the first line
269 (defvar org-table-last-highlighted-reference nil
)
270 (defvar org-table-formula-history nil
)
272 (defvar org-table-column-names nil
273 "Alist with column names, derived from the `!' line.")
274 (defvar org-table-column-name-regexp nil
275 "Regular expression matching the current column names.")
276 (defvar org-table-local-parameters nil
277 "Alist with parameter names, derived from the `$' line.")
278 (defvar org-table-named-field-locations nil
279 "Alist with locations of named fields.")
281 (defvar org-table-current-line-types nil
282 "Table row types, non-nil only for the duration of a comand.")
283 (defvar org-table-current-begin-line nil
284 "Table begin line, non-nil only for the duration of a comand.")
285 (defvar org-table-current-begin-pos nil
286 "Table begin position, non-nil only for the duration of a comand.")
287 (defvar org-table-dlines nil
288 "Vector of data line line numbers in the current table.")
289 (defvar org-table-hlines nil
290 "Vector of hline line numbers in the current table.")
292 (defconst org-table-range-regexp
293 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
295 "Regular expression for matching ranges in formulas.")
297 (defconst org-table-range-regexp2
299 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
301 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
302 "Match a range for reference display.")
304 (defconst org-table-translate-regexp
305 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
306 "Match a reference that needs translation, for reference display.")
308 (defun org-table-create-with-table.el
()
309 "Use the table.el package to insert a new table.
310 If there is already a table at point, convert between Org-mode tables
311 and table.el tables."
316 (if (y-or-n-p "Convert table to Org-mode table? ")
317 (org-table-convert)))
319 (if (y-or-n-p "Convert table to table.el table? ")
320 (org-table-convert)))
321 (t (call-interactively 'table-insert
))))
323 (defun org-table-create-or-convert-from-region (arg)
324 "Convert region to table, or create an empty table.
325 If there is an active region, convert it to a table, using the function
326 `org-table-convert-region'. See the documentation of that function
327 to learn how the prefix argument is interpreted to determine the field
329 If there is no such region, create an empty table with `org-table-create'."
331 (if (org-region-active-p)
332 (org-table-convert-region (region-beginning) (region-end) arg
)
333 (org-table-create arg
)))
335 (defun org-table-create (&optional size
)
336 "Query for a size and insert a table skeleton.
337 SIZE is a string Columns x Rows like for example \"3x2\"."
340 (setq size
(read-string
341 (concat "Table size Columns x Rows [e.g. "
342 org-table-default-size
"]: ")
343 "" nil org-table-default-size
)))
346 (indent (make-string (current-column) ?\
))
347 (split (org-split-string size
" *x *"))
348 (rows (string-to-number (nth 1 split
)))
349 (columns (string-to-number (car split
)))
350 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
352 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
353 (point-at-bol) (point)))
354 (beginning-of-line 1)
356 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
357 (dotimes (i rows
) (insert line
))
360 ;; Insert a hline after the first row.
367 (defun org-table-convert-region (beg0 end0
&optional separator
)
368 "Convert region to a table.
369 The region goes from BEG0 to END0, but these borders will be moved
370 slightly, to make sure a beginning of line in the first line is included.
372 SEPARATOR specifies the field separator in the lines. It can have the
375 '(4) Use the comma as a field separator
376 '(16) Use a TAB as field separator
377 integer When a number, use that many spaces as field separator
378 nil When nil, the command tries to be smart and figure out the
379 separator in the following way:
380 - when each line contains a TAB, assume TAB-separated material
381 - when each line contains a comme, assume CSV material
382 - else, assume one or more SPACE charcters as separator."
384 (let* ((beg (min beg0 end0
))
385 (end (max beg0 end0
))
388 (beginning-of-line 1)
389 (setq beg
(move-marker (make-marker) (point)))
391 (if (bolp) (backward-char 1) (end-of-line 1))
392 (setq end
(move-marker (make-marker) (point)))
393 ;; Get the right field separator
398 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
399 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
402 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
403 ((equal separator
'(16)) "^\\|\t")
404 ((integerp separator
)
405 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
))
406 (t (error "This should not happen"))))
408 (while (re-search-forward re end t
)
409 (replace-match "| " t t
))
414 (defun org-table-import (file arg
)
415 "Import FILE as a table.
416 The file is assumed to be tab-separated. Such files can be produced by most
417 spreadsheet and database applications. If no tabs (at least one per line)
418 are found, lines will be split on whitespace into fields."
420 (or (bolp) (newline))
423 (insert-file-contents file
)
424 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
427 (defvar org-table-last-alignment
)
428 (defvar org-table-last-column-widths
)
429 (defun org-table-export (&optional file format
)
430 "Export table to a file, with configurable format.
431 Such a file can be imported into a spreadsheet program like Excel.
432 FILE can be the output file name. If not given, it will be taken from
433 a TABLE_EXPORT_FILE property in the current entry or higher up in the
434 hierarchy, or the user will be prompted for a file name.
435 FORMAT can be an export format, of the same kind as it used when
436 orgtbl-mode sends a table in a different format. The default format can
437 be found in the variable `org-table-export-default-format', but the function
438 first checks if there is an export format specified in a TABLE_EXPORT_FORMAT
439 property, locally or anywhere up in the hierarchy."
441 (unless (org-at-table-p)
442 (error "No table at point"))
444 (org-table-align) ;; make sure we have everything we need
445 (let* ((beg (org-table-begin))
446 (end (org-table-end))
447 (txt (buffer-substring-no-properties beg end
))
450 (org-entry-get beg
"TABLE_EXPORT_FILE" t
)
454 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)
458 (setq file
(read-file-name "Export table to: "))
459 (unless (or (not (file-exists-p file
))
460 (y-or-n-p (format "Overwrite file %s? " file
)))
462 (if (file-directory-p file
)
463 (error "This is a directory path, not a file"))
464 (if (equal (file-truename file
)
465 (file-truename (buffer-file-name)))
466 (error "Please specify a file name that is different from current"))
468 (setq deffmt-readable org-table-export-default-format
)
469 (while (string-match "\t" deffmt-readable
)
470 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
471 (while (string-match "\n" deffmt-readable
)
472 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
473 (setq format
(org-completing-read
475 '("orgtbl-to-tsv" "orgtbl-to-csv"
476 "orgtbl-to-latex" "orgtbl-to-html"
477 "orgtbl-to-generic" "orgtbl-to-texinfo"
478 "orgtbl-to-orgtbl") nil nil
480 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
481 (let* ((transform (intern (match-string 1 format
)))
482 (params (if (match-end 2)
483 (read (concat "(" (match-string 2 format
) ")"))))
484 (skip (plist-get params
:skip
))
485 (skipcols (plist-get params
:skipcols
))
486 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
487 (lines (org-table-clean-before-export lines
))
488 (i0 (if org-table-clean-did-remove-column
2 1))
491 (if (string-match org-table-hline-regexp x
)
494 (org-split-string (org-trim x
) "\\s-*|\\s-*")
497 (fun (if (= i0
2) 'cdr
'identity
))
498 (org-table-last-alignment
499 (org-remove-by-index (funcall fun org-table-last-alignment
)
501 (org-table-last-column-widths
502 (org-remove-by-index (funcall fun org-table-last-column-widths
)
505 (unless (fboundp transform
)
506 (error "No such transformation function %s" transform
))
507 (setq txt
(funcall transform table params
))
509 (with-current-buffer (find-file-noselect file
)
510 (setq buf
(current-buffer))
516 (message "Export done."))
517 (error "TABLE_EXPORT_FORMAT invalid"))))
519 (defvar org-table-aligned-begin-marker
(make-marker)
520 "Marker at the beginning of the table last aligned.
521 Used to check if cursor still is in that table, to minimize realignment.")
522 (defvar org-table-aligned-end-marker
(make-marker)
523 "Marker at the end of the table last aligned.
524 Used to check if cursor still is in that table, to minimize realignment.")
525 (defvar org-table-last-alignment nil
526 "List of flags for flushright alignment, from the last re-alignment.
527 This is being used to correctly align a single field after TAB or RET.")
528 (defvar org-table-last-column-widths nil
529 "List of max width of fields in each column.
530 This is being used to correctly align a single field after TAB or RET.")
531 (defvar org-table-formula-debug nil
532 "Non-nil means, debug table formulas.
533 When nil, simply write \"#ERROR\" in corrupted fields.")
534 (make-variable-buffer-local 'org-table-formula-debug
)
535 (defvar org-table-overlay-coordinates nil
536 "Overlay coordinates after each align of a table.")
537 (make-variable-buffer-local 'org-table-overlay-coordinates
)
539 (defvar org-last-recalc-line nil
)
540 (defconst org-narrow-column-arrow
"=>"
541 "Used as display property in narrowed table columns.")
543 (defun org-table-align ()
544 "Align the table at point by aligning all vertical bars."
548 (beg (org-table-begin))
549 (end (org-table-end))
550 ;; Current cursor position
551 (linepos (org-current-line))
552 (colpos (org-table-current-column))
553 (winstart (window-start))
554 (winstartline (org-current-line (min winstart
(1- (point-max)))))
555 lines
(new "") lengths l typenums ty fields maxfields i
563 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
565 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
566 emptystrings links dates emph narrow fmax f1 len c e
)
568 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
569 ;; Check if we have links or dates
571 (setq links
(re-search-forward org-bracket-link-regexp end t
))
573 (setq emph
(and org-hide-emphasis-markers
574 (re-search-forward org-emph-re end t
)))
576 (setq dates
(and org-display-custom-times
577 (re-search-forward org-ts-regexp-both end t
)))
578 ;; Make sure the link properties are right
579 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
580 ;; Make sure the date properties are right
581 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
582 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
584 ;; Check if we are narrowing any columns
586 (setq narrow
(and org-format-transports-properties-p
587 (re-search-forward "<[0-9]+>" end t
)))
589 (setq lines
(org-split-string
590 (buffer-substring beg end
) "\n"))
591 ;; Store the indentation of the first line
592 (if (string-match "^ *" (car lines
))
593 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
594 ;; Mark the hlines by setting the corresponding element to nil
595 ;; At the same time, we remove trailing space.
596 (setq lines
(mapcar (lambda (l)
597 (if (string-match "^ *|-" l
)
599 (if (string-match "[ \t]+$" l
)
600 (substring l
0 (match-beginning 0))
603 ;; Get the data fields by splitting the lines.
606 (org-split-string l
" *| *"))
607 (delq nil
(copy-sequence lines
))))
608 ;; How many fields in the longest line?
610 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
612 (kill-region beg end
)
613 (org-table-create org-table-default-size
)
614 (error "Empty table - created default table")))
615 ;; A list of empty strings to fill any short rows on output
616 (setq emptystrings
(make-list maxfields
""))
617 ;; Check for special formatting.
619 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
620 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
621 ;; Check if there is an explicit width specified
623 (setq c column fmax nil
)
626 (if (and (stringp e
) (string-match "^<\\([0-9]+\\)>$" e
))
627 (setq fmax
(string-to-number (match-string 1 e
)) c nil
)))
628 ;; Find fields that are wider than fmax, and shorten them
630 (loop for xx in column do
631 (when (and (stringp xx
)
632 (> (org-string-width xx
) fmax
))
633 (org-add-props xx nil
635 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
636 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
638 (error "Cannot narrow field starting with wide link \"%s\""
639 (match-string 0 xx
)))
640 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
641 (add-text-properties (- f1
2) f1
642 (list 'display org-narrow-column-arrow
)
644 ;; Get the maximum width for each column
645 (push (apply 'max
1 (mapcar 'org-string-width column
)) lengths
)
646 ;; Get the fraction of numbers, to decide about alignment of the column
647 (setq cnt
0 frac
0.0)
648 (loop for x in column do
651 (setq frac
( / (+ (* frac cnt
)
652 (if (string-match org-table-number-regexp x
) 1 0))
653 (setq cnt
(1+ cnt
))))))
654 (push (>= frac org-table-number-fraction
) typenums
))
655 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
657 ;; Store the alignment of this table, for later editing of single fields
658 (setq org-table-last-alignment typenums
659 org-table-last-column-widths lengths
)
661 ;; With invisible characters, `format' does not get the field width right
662 ;; So we need to make these fields wide by hand.
663 (when (or links emph
)
664 (loop for i from
0 upto
(1- maxfields
) do
665 (setq len
(nth i lengths
))
666 (loop for j from
0 upto
(1- (length fields
)) do
667 (setq c
(nthcdr i
(car (nthcdr j fields
))))
668 (if (and (stringp (car c
))
669 (text-property-any 0 (length (car c
)) 'invisible
'org-link
(car c
))
670 ; (string-match org-bracket-link-regexp (car c))
671 (< (org-string-width (car c
)) len
))
672 (setcar c
(concat (car c
) (make-string (- len
(org-string-width (car c
))) ?\
)))))))
674 ;; Compute the formats needed for output of the table
675 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
676 (while (setq l
(pop lengths
))
677 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
678 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
679 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
680 (setq rfmt
(concat rfmt
"\n")
681 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
685 (if l
(apply 'format rfmt
686 (append (pop fields
) emptystrings
))
689 ;; Replace the old one
690 (delete-region beg end
)
691 (move-marker end nil
)
692 (move-marker org-table-aligned-begin-marker
(point))
694 (move-marker org-table-aligned-end-marker
(point))
695 (when (and orgtbl-mode
(not (org-mode-p)))
696 (goto-char org-table-aligned-begin-marker
)
697 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
698 ;; Try to move to the old location
699 (goto-line winstartline
)
700 (setq winstart
(point-at-bol))
702 (set-window-start (selected-window) winstart
'noforce
)
703 (org-table-goto-column colpos
)
704 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
705 (setq org-table-may-need-update nil
)
716 (defun org-table-begin (&optional table-type
)
717 "Find the beginning of the table and return its position.
718 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
720 (if (not (re-search-backward
721 (if table-type org-table-any-border-regexp
722 org-table-border-regexp
)
724 (progn (goto-char (point-min)) (point))
725 (goto-char (match-beginning 0))
726 (beginning-of-line 2)
729 (defun org-table-end (&optional table-type
)
730 "Find the end of the table and return its position.
731 With argument TABLE-TYPE, go to the end of a table.el-type table."
733 (if (not (re-search-forward
734 (if table-type org-table-any-border-regexp
735 org-table-border-regexp
)
737 (goto-char (point-max))
738 (goto-char (match-beginning 0)))
741 (defun org-table-justify-field-maybe (&optional new
)
742 "Justify the current field, text to left, number to right.
743 Optional argument NEW may specify text to replace the current field content."
745 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
746 ((org-at-table-hline-p))
748 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
750 (< (point) org-table-aligned-begin-marker
)
751 (>= (point) org-table-aligned-end-marker
)))
752 ;; This is not the same table, force a full re-align
753 (setq org-table-may-need-update t
))
754 (t ;; realign the current field, based on previous full realign
755 (let* ((pos (point)) s
756 (col (org-table-current-column))
757 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
760 (skip-chars-backward "^|\n")
761 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
763 (setq s
(match-string 1)
765 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
766 e
(not (= (match-beginning 2) (match-end 2))))
767 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
768 l
(if e
"|" (setq org-table-may-need-update t
) ""))
771 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
772 (setq n
(format f new
))
773 (setq n
(concat new
"|") org-table-may-need-update t
)))
775 (let (org-table-may-need-update)
776 (replace-match n t t
))))
777 (setq org-table-may-need-update t
))
780 (defun org-table-next-field ()
781 "Go to the next field in the current table, creating new lines as needed.
782 Before doing so, re-align the table if necessary."
784 (org-table-maybe-eval-formula)
785 (org-table-maybe-recalculate-line)
786 (if (and org-table-automatic-realign
787 org-table-may-need-update
)
789 (let ((end (org-table-end)))
790 (if (org-at-table-hline-p)
794 (re-search-forward "|" end
)
795 (if (looking-at "[ \t]*$")
796 (re-search-forward "|" end
))
797 (if (and (looking-at "-")
798 org-table-tab-jumps-over-hlines
799 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
800 (goto-char (match-beginning 1)))
803 (beginning-of-line 0)
804 (org-table-insert-row 'below
))
805 (if (looking-at " ") (forward-char 1))))
807 (org-table-insert-row 'below
)))))
809 (defun org-table-previous-field ()
810 "Go to the previous field in the table.
811 Before doing so, re-align the table if necessary."
813 (org-table-justify-field-maybe)
814 (org-table-maybe-recalculate-line)
815 (if (and org-table-automatic-realign
816 org-table-may-need-update
)
818 (if (org-at-table-hline-p)
820 (re-search-backward "|" (org-table-begin))
821 (re-search-backward "|" (org-table-begin))
822 (while (looking-at "|\\(-\\|[ \t]*$\\)")
823 (re-search-backward "|" (org-table-begin)))
824 (if (looking-at "| ?")
825 (goto-char (match-end 0))))
827 (defun org-table-next-row ()
828 "Go to the next row (same column) in the current table.
829 Before doing so, re-align the table if necessary."
831 (org-table-maybe-eval-formula)
832 (org-table-maybe-recalculate-line)
833 (if (or (looking-at "[ \t]*$")
834 (save-excursion (skip-chars-backward " \t") (bolp)))
836 (if (and org-table-automatic-realign
837 org-table-may-need-update
)
839 (let ((col (org-table-current-column)))
840 (beginning-of-line 2)
841 (if (or (not (org-at-table-p))
842 (org-at-table-hline-p))
844 (beginning-of-line 0)
845 (org-table-insert-row 'below
)))
846 (org-table-goto-column col
)
847 (skip-chars-backward "^|\n\r")
848 (if (looking-at " ") (forward-char 1)))))
850 (defun org-table-copy-down (n)
851 "Copy a field down in the current column.
852 If the field at the cursor is empty, copy into it the content of the nearest
853 non-empty field above. With argument N, use the Nth non-empty field.
854 If the current field is not empty, it is copied down to the next row, and
855 the cursor is moved with it. Therefore, repeating this command causes the
856 column to be filled row-by-row.
857 If the variable `org-table-copy-increment' is non-nil and the field is an
858 integer or a timestamp, it will be incremented while copying. In the case of
859 a timestamp, if the cursor is on the year, change the year. If it is on the
860 month or the day, change that. Point will stay on the current date field
861 in order to easily repeat the interval."
863 (let* ((colpos (org-table-current-column))
864 (col (current-column))
865 (field (org-table-get-field))
866 (non-empty (string-match "[^ \t]" field
))
867 (beg (org-table-begin))
869 (org-table-check-inside-data-field)
872 (setq txt
(org-trim field
))
874 (org-table-blank-field))
878 (while (progn (beginning-of-line 1)
879 (re-search-backward org-table-dataline-regexp
881 (org-table-goto-column colpos t
)
883 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
884 (= (setq n
(1- n
)) 0))
885 (throw 'exit
(match-string 1))))))))
888 (if (and org-table-copy-increment
889 (string-match "^[0-9]+$" txt
))
890 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
892 (org-move-to-column col
)
893 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
895 (org-table-maybe-recalculate-line))
897 (org-move-to-column col
))
898 (error "No non-empty field found"))))
900 (defun org-table-check-inside-data-field ()
901 "Is point inside a table data field?
902 I.e. not on a hline or before the first or after the last column?
903 This actually throws an error, so it aborts the current command."
904 (if (or (not (org-at-table-p))
905 (= (org-table-current-column) 0)
906 (org-at-table-hline-p)
907 (looking-at "[ \t]*$"))
908 (error "Not in table data field")))
910 (defvar org-table-clip nil
911 "Clipboard for table regions.")
913 (defun org-table-blank-field ()
914 "Blank the current table field or active region."
916 (org-table-check-inside-data-field)
917 (if (and (interactive-p) (org-region-active-p))
918 (let (org-table-clip)
919 (org-table-cut-region (region-beginning) (region-end)))
920 (skip-chars-backward "^|")
922 (if (looking-at "|[^|\n]+")
923 (let* ((pos (match-beginning 0))
924 (match (match-string 0))
925 (len (org-string-width match
)))
926 (replace-match (concat "|" (make-string (1- len
) ?\
)))
927 (goto-char (+ 2 pos
))
928 (substring match
1)))))
930 (defun org-table-get-field (&optional n replace
)
931 "Return the value of the field in column N of current row.
932 N defaults to current field.
933 If REPLACE is a string, replace field with this value. The return value
934 is always the old value."
935 (and n
(org-table-goto-column n
))
936 (skip-chars-backward "^|\n")
938 (if (looking-at "|[^|\r\n]*")
939 (let* ((pos (match-beginning 0))
940 (val (buffer-substring (1+ pos
) (match-end 0))))
942 (replace-match (concat "|" replace
) t t
))
943 (goto-char (min (point-at-eol) (+ 2 pos
)))
945 (forward-char 1) ""))
947 (defun org-table-field-info (arg)
948 "Show info about the current field, and highlight any reference at point."
950 (org-table-get-specials)
953 (col (org-table-current-column))
954 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
955 (name (car (rassoc (list (org-current-line) col
)
956 org-table-named-field-locations
)))
957 (eql (org-table-get-stored-formulas))
958 (dline (org-table-current-dline))
959 (ref (format "@%d$%d" dline col
))
960 (ref1 (org-table-convert-refs-to-an ref
))
961 (fequation (or (assoc name eql
) (assoc ref eql
)))
962 (cequation (assoc (int-to-string col
) eql
))
963 (eqn (or fequation cequation
)))
966 (org-table-show-reference 'local
)
968 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
970 (if cname
(concat " or $" cname
) "")
972 (if name
(concat " or $" name
) "")
973 ;; FIXME: formula info not correct if special table line
975 (concat ", formula: "
976 (org-table-formula-to-user
978 (if (string-match "^[$@]"(car eqn
)) "" "$")
979 (car eqn
) "=" (cdr eqn
))))
982 (defun org-table-current-column ()
983 "Find out which column we are in."
985 (let ((cnt 0) (pos (point)))
986 (beginning-of-line 1)
987 (while (search-forward "|" pos t
)
991 (defun org-table-current-dline ()
992 "Find out what table data line we are in.
993 Only datalins count for this."
995 (if (interactive-p) (org-table-check-inside-data-field))
997 (let ((cnt 0) (pos (point)))
998 (goto-char (org-table-begin))
999 (while (<= (point) pos
)
1000 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1001 (beginning-of-line 2))
1002 (if (interactive-p) (message "This is table line %d" cnt
))
1005 (defun org-table-goto-column (n &optional on-delim force
)
1006 "Move the cursor to the Nth column in the current table line.
1007 With optional argument ON-DELIM, stop with point before the left delimiter
1009 If there are less than N fields, just go to after the last delimiter.
1010 However, when FORCE is non-nil, create new columns if necessary."
1012 (let ((pos (point-at-eol)))
1013 (beginning-of-line 1)
1015 (while (and (> (setq n
(1- n
)) -
1)
1016 (or (search-forward "|" pos t
)
1018 (progn (end-of-line 1)
1019 (skip-chars-backward "^|")
1021 ; (backward-char 2) t)))))
1022 (when (and force
(not (looking-at ".*|")))
1023 (save-excursion (end-of-line 1) (insert " | ")))
1026 (if (looking-at " ") (forward-char 1))))))
1029 (defun org-table-insert-column ()
1030 "Insert a new column into the table."
1032 (if (not (org-at-table-p))
1033 (error "Not at a table"))
1034 (org-table-find-dataline)
1035 (let* ((col (max 1 (org-table-current-column)))
1036 (beg (org-table-begin))
1037 (end (org-table-end))
1038 ;; Current cursor position
1039 (linepos (org-current-line))
1042 (while (< (point) end
)
1043 (if (org-at-table-hline-p)
1045 (org-table-goto-column col t
)
1047 (beginning-of-line 2))
1048 (move-marker end nil
)
1050 (org-table-goto-column colpos
)
1052 (org-table-fix-formulas "$" nil
(1- col
) 1)))
1054 (defun org-table-find-dataline ()
1055 "Find a dataline in the current table, which is needed for column commands."
1056 (if (and (org-at-table-p)
1057 (not (org-at-table-hline-p)))
1059 (let ((col (current-column))
1060 (end (org-table-end)))
1061 (org-move-to-column col
)
1062 (while (and (< (point) end
)
1063 (or (not (= (current-column) col
))
1064 (org-at-table-hline-p)))
1065 (beginning-of-line 2)
1066 (org-move-to-column col
))
1067 (if (and (org-at-table-p)
1068 (not (org-at-table-hline-p)))
1071 "Please position cursor in a data line for column operations")))))
1073 (defun org-table-delete-column ()
1074 "Delete a column from the table."
1076 (if (not (org-at-table-p))
1077 (error "Not at a table"))
1078 (org-table-find-dataline)
1079 (org-table-check-inside-data-field)
1080 (let* ((col (org-table-current-column))
1081 (beg (org-table-begin))
1082 (end (org-table-end))
1083 ;; Current cursor position
1084 (linepos (org-current-line))
1087 (while (< (point) end
)
1088 (if (org-at-table-hline-p)
1090 (org-table-goto-column col t
)
1091 (and (looking-at "|[^|\n]+|")
1092 (replace-match "|")))
1093 (beginning-of-line 2))
1094 (move-marker end nil
)
1096 (org-table-goto-column colpos
)
1098 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1101 (defun org-table-move-column-right ()
1102 "Move column to the right."
1104 (org-table-move-column nil
))
1105 (defun org-table-move-column-left ()
1106 "Move column to the left."
1108 (org-table-move-column 'left
))
1110 (defun org-table-move-column (&optional left
)
1111 "Move the current column to the right. With arg LEFT, move to the left."
1113 (if (not (org-at-table-p))
1114 (error "Not at a table"))
1115 (org-table-find-dataline)
1116 (org-table-check-inside-data-field)
1117 (let* ((col (org-table-current-column))
1118 (col1 (if left
(1- col
) col
))
1119 (beg (org-table-begin))
1120 (end (org-table-end))
1121 ;; Current cursor position
1122 (linepos (org-current-line))
1123 (colpos (if left
(1- col
) (1+ col
))))
1124 (if (and left
(= col
1))
1125 (error "Cannot move column further left"))
1126 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1127 (error "Cannot move column further right"))
1129 (while (< (point) end
)
1130 (if (org-at-table-hline-p)
1132 (org-table-goto-column col1 t
)
1133 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1134 (replace-match "|\\2|\\1|")))
1135 (beginning-of-line 2))
1136 (move-marker end nil
)
1138 (org-table-goto-column colpos
)
1140 (org-table-fix-formulas
1141 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1142 (cons (number-to-string colpos
) (number-to-string col
))))))
1144 (defun org-table-move-row-down ()
1145 "Move table row down."
1147 (org-table-move-row nil
))
1148 (defun org-table-move-row-up ()
1149 "Move table row up."
1151 (org-table-move-row 'up
))
1153 (defun org-table-move-row (&optional up
)
1154 "Move the current table line down. With arg UP, move it up."
1156 (let* ((col (current-column))
1158 (hline1p (save-excursion (beginning-of-line 1)
1159 (looking-at org-table-hline-regexp
)))
1160 (dline1 (org-table-current-dline))
1161 (dline2 (+ dline1
(if up -
1 1)))
1164 (beginning-of-line tonew
)
1165 (unless (org-at-table-p)
1167 (error "Cannot move row further"))
1168 (setq hline2p
(looking-at org-table-hline-regexp
))
1170 (beginning-of-line 1)
1172 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1173 (delete-region (point) (1+ (point-at-eol)))
1174 (beginning-of-line tonew
)
1176 (beginning-of-line 0)
1177 (org-move-to-column col
)
1178 (unless (or hline1p hline2p
)
1179 (org-table-fix-formulas
1180 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1181 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1183 (defun org-table-insert-row (&optional arg
)
1184 "Insert a new row above the current line into the table.
1185 With prefix ARG, insert below the current line."
1187 (if (not (org-at-table-p))
1188 (error "Not at a table"))
1189 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1190 (new (org-table-clean-line line
)))
1191 ;; Fix the first field if necessary
1192 (if (string-match "^[ \t]*| *[#$] *|" line
)
1193 (setq new
(replace-match (match-string 0 line
) t t new
)))
1194 (beginning-of-line (if arg
2 1))
1195 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1196 (beginning-of-line 0)
1197 (re-search-forward "| ?" (point-at-eol) t
)
1198 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1200 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1)))
1202 (defun org-table-insert-hline (&optional above
)
1203 "Insert a horizontal-line below the current line into the table.
1204 With prefix ABOVE, insert above the current line."
1206 (if (not (org-at-table-p))
1207 (error "Not at a table"))
1208 (let ((line (org-table-clean-line
1209 (buffer-substring (point-at-bol) (point-at-eol))))
1210 (col (current-column)))
1211 (while (string-match "|\\( +\\)|" line
)
1212 (setq line
(replace-match
1213 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1214 ?-
) "|") t t line
)))
1215 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1216 (beginning-of-line (if above
1 2))
1218 (beginning-of-line (if above
1 -
1))
1219 (org-move-to-column col
)
1220 (and org-table-overlay-coordinates
(org-table-align))))
1222 (defun org-table-hline-and-move (&optional same-column
)
1223 "Insert a hline and move to the row below that line."
1225 (let ((col (org-table-current-column)))
1226 (org-table-maybe-eval-formula)
1227 (org-table-maybe-recalculate-line)
1228 (org-table-insert-hline)
1230 (if (looking-at "\n[ \t]*|-")
1231 (progn (insert "\n|") (org-table-align))
1232 (org-table-next-field))
1233 (if same-column
(org-table-goto-column col
))))
1235 (defun org-table-clean-line (s)
1236 "Convert a table line S into a string with only \"|\" and space.
1237 In particular, this does handle wide and invisible characters."
1238 (if (string-match "^[ \t]*|-" s
)
1239 ;; It's a hline, just map the characters
1240 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1241 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1242 (setq s
(replace-match
1243 (concat "|" (make-string (org-string-width (match-string 1 s
))
1248 (defun org-table-kill-row ()
1249 "Delete the current row or horizontal line from the table."
1251 (if (not (org-at-table-p))
1252 (error "Not at a table"))
1253 (let ((col (current-column))
1254 (dline (org-table-current-dline)))
1255 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1256 (if (not (org-at-table-p)) (beginning-of-line 0))
1257 (org-move-to-column col
)
1258 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1261 (defun org-table-sort-lines (with-case &optional sorting-type
)
1262 "Sort table lines according to the column at point.
1264 The position of point indicates the column to be used for
1265 sorting, and the range of lines is the range between the nearest
1266 horizontal separator lines, or the entire table of no such lines
1267 exist. If point is before the first column, you will be prompted
1268 for the sorting column. If there is an active region, the mark
1269 specifies the first line and the sorting column, while point
1270 should be in the last line to be included into the sorting.
1272 The command then prompts for the sorting type which can be
1273 alphabetically, numerically, or by time (as given in a time stamp
1274 in the field). Sorting in reverse order is also possible.
1276 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1278 If SORTING-TYPE is specified when this function is called from a Lisp
1279 program, no prompting will take place. SORTING-TYPE must be a character,
1280 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1281 should be done in reverse order."
1283 (let* ((thisline (org-current-line))
1284 (thiscol (org-table-current-column))
1285 beg end bcol ecol tend tbeg column lns pos
)
1286 (when (equal thiscol
0)
1290 (read-string "Use column N for sorting: ")))
1292 (org-table-goto-column thiscol
))
1293 (org-table-check-inside-data-field)
1294 (if (org-region-active-p)
1296 (setq beg
(region-beginning) end
(region-end))
1298 (setq column
(org-table-current-column)
1301 (setq end
(point-at-bol 2)))
1302 (setq column
(org-table-current-column)
1304 tbeg
(org-table-begin)
1305 tend
(org-table-end))
1306 (if (re-search-backward org-table-hline-regexp tbeg t
)
1307 (setq beg
(point-at-bol 2))
1309 (setq beg
(point-at-bol 1)))
1311 (if (re-search-forward org-table-hline-regexp tend t
)
1312 (setq end
(point-at-bol 1))
1314 (setq end
(point-at-bol))))
1315 (setq beg
(move-marker (make-marker) beg
)
1316 end
(move-marker (make-marker) end
))
1319 (org-table-goto-column column
)
1320 (skip-chars-backward "^|")
1321 (setq bcol
(current-column))
1322 (org-table-goto-column (1+ column
))
1323 (skip-chars-backward "^|")
1324 (setq ecol
(1- (current-column)))
1325 (org-table-goto-column column
)
1326 (setq lns
(mapcar (lambda(x) (cons
1327 (org-sort-remove-invisible
1329 (org-split-string x
"[ \t]*|[ \t]*")))
1331 (org-split-string (buffer-substring beg end
) "\n")))
1332 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1333 (delete-region beg end
)
1334 (move-marker beg nil
)
1335 (move-marker end nil
)
1336 (insert (mapconcat 'cdr lns
"\n") "\n")
1337 (goto-line thisline
)
1338 (org-table-goto-column thiscol
)
1339 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1342 (defun org-table-cut-region (beg end
)
1343 "Copy region in table to the clipboard and blank all relevant fields."
1345 (org-table-copy-region beg end
'cut
))
1347 (defun org-table-copy-region (beg end
&optional cut
)
1348 "Copy rectangular region in table to clipboard.
1349 A special clipboard is used which can only be accessed
1350 with `org-table-paste-rectangle'."
1352 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1354 (rpl (if cut
" " nil
)))
1356 (org-table-check-inside-data-field)
1357 (setq l01
(org-current-line)
1358 c01
(org-table-current-column))
1360 (org-table-check-inside-data-field)
1361 (setq l02
(org-current-line)
1362 c02
(org-table-current-column))
1363 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1364 c1
(min c01 c02
) c2
(max c01 c02
))
1368 (if (> l1 l2
) (throw 'exit t
))
1370 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1371 (setq cols nil ic1 c1 ic2 c2
)
1372 (while (< ic1
(1+ ic2
))
1373 (push (org-table-get-field ic1 rpl
) cols
)
1374 (setq ic1
(1+ ic1
)))
1375 (push (nreverse cols
) region
)
1376 (setq l1
(1+ l1
)))))
1377 (setq org-table-clip
(nreverse region
))
1378 (if cut
(org-table-align))
1381 (defun org-table-paste-rectangle ()
1382 "Paste a rectangular region into a table.
1383 The upper right corner ends up in the current field. All involved fields
1384 will be overwritten. If the rectangle does not fit into the present table,
1385 the table is enlarged as needed. The process ignores horizontal separator
1388 (unless (and org-table-clip
(listp org-table-clip
))
1389 (error "First cut/copy a region to paste!"))
1390 (org-table-check-inside-data-field)
1391 (let* ((clip org-table-clip
)
1392 (line (org-current-line))
1393 (col (org-table-current-column))
1394 (org-enable-table-editor t
)
1395 (org-table-automatic-realign nil
)
1397 (while (setq cols
(pop clip
))
1398 (while (org-at-table-hline-p) (beginning-of-line 2))
1399 (if (not (org-at-table-p))
1400 (progn (end-of-line 0) (org-table-next-field)))
1402 (while (setq field
(pop cols
))
1403 (org-table-goto-column c nil
'force
)
1404 (org-table-get-field nil field
)
1406 (beginning-of-line 2))
1408 (org-table-goto-column col
)
1411 (defun org-table-convert ()
1412 "Convert from `org-mode' table to table.el and back.
1413 Obviously, this only works within limits. When an Org-mode table is
1414 converted to table.el, all horizontal separator lines get lost, because
1415 table.el uses these as cell boundaries and has no notion of horizontal lines.
1416 A table.el table can be converted to an Org-mode table only if it does not
1417 do row or column spanning. Multiline cells will become multiple cells.
1418 Beware, Org-mode does not test if the table can be successfully converted - it
1419 blindly applies a recipe that works for simple tables."
1422 (if (org-at-table.el-p
)
1423 ;; convert to Org-mode table
1424 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1425 (end (move-marker (make-marker) (org-table-end t
))))
1426 (table-unrecognize-region beg end
)
1428 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1431 (if (org-at-table-p)
1432 ;; convert to table.el table
1433 (let ((beg (move-marker (make-marker) (org-table-begin)))
1434 (end (move-marker (make-marker) (org-table-end))))
1435 ;; first, get rid of all horizontal lines
1437 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1439 ;; insert a hline before first
1441 (org-table-insert-hline 'above
)
1442 (beginning-of-line -
1)
1443 ;; insert a hline after each line
1444 (while (progn (beginning-of-line 3) (< (point) end
))
1445 (org-table-insert-hline))
1447 (setq end
(move-marker end
(org-table-end)))
1448 ;; replace "+" at beginning and ending of hlines
1449 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1450 (replace-match "\\1+-"))
1452 (while (re-search-forward "-|[ \t]*$" end t
)
1453 (replace-match "-+"))
1456 (defun org-table-wrap-region (arg)
1457 "Wrap several fields in a column like a paragraph.
1458 This is useful if you'd like to spread the contents of a field over several
1459 lines, in order to keep the table compact.
1461 If there is an active region, and both point and mark are in the same column,
1462 the text in the column is wrapped to minimum width for the given number of
1463 lines. Generally, this makes the table more compact. A prefix ARG may be
1464 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1465 formats the selected text to two lines. If the region was longer than two
1466 lines, the remaining lines remain empty. A negative prefix argument reduces
1467 the current number of lines by that amount. The wrapped text is pasted back
1468 into the table. If you formatted it to more lines than it was before, fields
1469 further down in the table get overwritten - so you might need to make space in
1472 If there is no region, the current field is split at the cursor position and
1473 the text fragment to the right of the cursor is prepended to the field one
1476 If there is no region, but you specify a prefix ARG, the current field gets
1477 blank, and the content is appended to the field above."
1479 (org-table-check-inside-data-field)
1480 (if (org-region-active-p)
1481 ;; There is a region: fill as a paragraph
1482 (let* ((beg (region-beginning))
1483 (cline (save-excursion (goto-char beg
) (org-current-line)))
1484 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1486 (org-table-cut-region (region-beginning) (region-end))
1487 (if (> (length (car org-table-clip
)) 1)
1488 (error "Region must be limited to single column"))
1489 (setq nlines
(if arg
1491 (+ (length org-table-clip
) arg
)
1493 (length org-table-clip
)))
1494 (setq org-table-clip
1495 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1498 (org-table-goto-column ccol
)
1499 (org-table-paste-rectangle))
1500 ;; No region, split the current field at point
1501 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1502 (skip-chars-forward "^\r\n|"))
1504 ;; combine with field above
1505 (let ((s (org-table-blank-field))
1506 (col (org-table-current-column)))
1507 (beginning-of-line 0)
1508 (while (org-at-table-hline-p) (beginning-of-line 0))
1509 (org-table-goto-column col
)
1510 (skip-chars-forward "^|")
1511 (skip-chars-backward " ")
1512 (insert " " (org-trim s
))
1515 (if (looking-at "\\([^|]+\\)+|")
1516 (let ((s (match-string 1)))
1517 (replace-match " |")
1518 (goto-char (match-beginning 0))
1519 (org-table-next-row)
1520 (insert (org-trim s
) " ")
1522 (org-table-next-row)))))
1524 (defvar org-field-marker nil
)
1526 (defun org-table-edit-field (arg)
1527 "Edit table field in a different window.
1528 This is mainly useful for fields that contain hidden parts.
1529 When called with a \\[universal-argument] prefix, just make the full field visible so that
1530 it can be edited in place."
1533 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1534 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1535 (remove-text-properties b e
'(org-cwidth t invisible t
1536 display t intangible t
))
1537 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1538 (font-lock-fontify-block)))
1539 (let ((pos (move-marker (make-marker) (point)))
1540 (field (org-table-get-field))
1541 (cw (current-window-configuration))
1543 (org-switch-to-buffer-other-window "*Org tmp*")
1545 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
1546 (let ((org-inhibit-startup t
)) (org-mode))
1547 (goto-char (setq p
(point-max)))
1548 (insert (org-trim field
))
1549 (remove-text-properties p
(point-max)
1550 '(invisible t org-cwidth t display t
1553 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1554 (org-set-local 'org-window-configuration cw
)
1555 (org-set-local 'org-field-marker pos
)
1556 (message "Edit and finish with C-c C-c"))))
1558 (defun org-table-finish-edit-field ()
1559 "Finish editing a table data field.
1560 Remove all newline characters, insert the result into the table, realign
1561 the table and kill the editing buffer."
1562 (let ((pos org-field-marker
)
1563 (cw org-window-configuration
)
1564 (cb (current-buffer))
1566 (goto-char (point-min))
1567 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1568 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1569 (replace-match " "))
1570 (setq text
(org-trim (buffer-string)))
1571 (set-window-configuration cw
)
1573 (select-window (get-buffer-window (marker-buffer pos
)))
1575 (move-marker pos nil
)
1576 (org-table-check-inside-data-field)
1577 (org-table-get-field nil text
)
1579 (message "New field value inserted")))
1598 (defvar org-timecnt
) ; dynamically scoped parameter
1600 (defun org-table-sum (&optional beg end nlast
)
1601 "Sum numbers in region of current table column.
1602 The result will be displayed in the echo area, and will be available
1603 as kill to be inserted with \\[yank].
1605 If there is an active region, it is interpreted as a rectangle and all
1606 numbers in that rectangle will be summed. If there is no active
1607 region and point is located in a table column, sum all numbers in that
1610 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1611 numbers are assumed to be times as well (in decimal hours) and the
1612 numbers are added as such.
1614 If NLAST is a number, only the NLAST fields will actually be summed."
1617 (let (col (org-timecnt 0) diff h m s org-table-clip
)
1619 ((and beg end
)) ; beg and end given explicitly
1620 ((org-region-active-p)
1621 (setq beg
(region-beginning) end
(region-end)))
1623 (setq col
(org-table-current-column))
1624 (goto-char (org-table-begin))
1625 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
1626 (error "No table data"))
1627 (org-table-goto-column col
)
1629 (goto-char (org-table-end))
1630 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
1631 (error "No table data"))
1632 (org-table-goto-column col
)
1633 (setq end
(point))))
1634 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
1635 (items1 (cond ((not nlast
) items
)
1636 ((>= nlast
(length items
)) items
)
1637 (t (setq items
(reverse items
))
1638 (setcdr (nthcdr (1- nlast
) items
) nil
)
1640 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
1642 (res (apply '+ numbers
))
1643 (sres (if (= org-timecnt
0)
1645 (setq diff
(* 3600 res
)
1646 h
(floor (/ diff
3600)) diff
(mod diff
3600)
1647 m
(floor (/ diff
60)) diff
(mod diff
60)
1649 (format "%d:%02d:%02d" h m s
))))
1653 (substitute-command-keys
1654 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
1655 (length numbers
) sres
))))
1658 (defun org-table-get-number-for-summing (s)
1660 (if (string-match "^ *|? *" s
)
1661 (setq s
(replace-match "" nil nil s
)))
1662 (if (string-match " *|? *$" s
)
1663 (setq s
(replace-match "" nil nil s
)))
1664 (setq n
(string-to-number s
))
1666 ((and (string-match "0" s
)
1667 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
1668 ((string-match "\\`[ \t]+\\'" s
) nil
)
1669 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
1670 (let ((h (string-to-number (or (match-string 1 s
) "0")))
1671 (m (string-to-number (or (match-string 2 s
) "0")))
1672 (s (string-to-number (or (match-string 4 s
) "0"))))
1673 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
1674 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
1678 (defun org-table-current-field-formula (&optional key noerror
)
1679 "Return the formula active for the current field.
1680 Assumes that specials are in place.
1681 If KEY is given, return the key to this formula.
1682 Otherwise return the formula preceeded with \"=\" or \":=\"."
1683 (let* ((name (car (rassoc (list (org-current-line)
1684 (org-table-current-column))
1685 org-table-named-field-locations
)))
1686 (col (org-table-current-column))
1687 (scol (int-to-string col
))
1688 (ref (format "@%d$%d" (org-table-current-dline) col
))
1689 (stored-list (org-table-get-stored-formulas noerror
))
1690 (ass (or (assoc name stored-list
)
1691 (assoc ref stored-list
)
1692 (assoc scol stored-list
))))
1695 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
1698 (defun org-table-get-formula (&optional equation named
)
1699 "Read a formula from the minibuffer, offer stored formula as default.
1700 When NAMED is non-nil, look for a named equation."
1701 (let* ((stored-list (org-table-get-stored-formulas))
1702 (name (car (rassoc (list (org-current-line)
1703 (org-table-current-column))
1704 org-table-named-field-locations
)))
1705 (ref (format "@%d$%d" (org-table-current-dline)
1706 (org-table-current-column)))
1707 (refass (assoc ref stored-list
))
1710 (int-to-string (org-table-current-column))))
1711 (dummy (and (or name refass
) (not named
)
1712 (not (y-or-n-p "Replace field formula with column formula? " ))
1714 (name (or name ref
))
1715 (org-table-may-need-update nil
)
1716 (stored (cdr (assoc scol stored-list
)))
1718 ((and stored equation
(string-match "^ *=? *$" equation
))
1722 (t (org-table-formula-from-user
1724 (org-table-formula-to-user
1725 (format "%s formula %s%s="
1726 (if named
"Field" "Column")
1727 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
1729 (if stored
(org-table-formula-to-user stored
) "")
1730 'org-table-formula-history
1733 (when (not (string-match "\\S-" eq
))
1735 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
1736 (org-table-store-formulas stored-list
)
1737 (error "Formula removed"))
1738 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
1739 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
1740 (if (and name
(not named
))
1741 ;; We set the column equation, delete the named one.
1742 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
1745 (setcdr (assoc scol stored-list
) eq
)
1746 (setq stored-list
(cons (cons scol eq
) stored-list
)))
1747 (if (or mustsave
(not (equal stored eq
)))
1748 (org-table-store-formulas stored-list
))
1751 (defun org-table-store-formulas (alist)
1752 "Store the list of formulas below the current table."
1753 (setq alist
(sort alist
'org-table-formula-less-p
))
1755 (goto-char (org-table-end))
1756 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
1758 ;; don't overwrite TBLFM, we might use text properties to store stuff
1759 (goto-char (match-beginning 2))
1760 (delete-region (match-beginning 2) (match-end 0)))
1761 (insert "#+TBLFM:"))
1763 (mapconcat (lambda (x)
1765 (if (equal (string-to-char (car x
)) ?
@) "" "$")
1766 (car x
) "=" (cdr x
)))
1770 (defsubst org-table-formula-make-cmp-string
(a)
1771 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a
)
1773 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a
))) "")
1774 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a
))) "")
1775 (if (match-end 5) (concat "@@" (match-string 5 a
))))))
1777 (defun org-table-formula-less-p (a b
)
1778 "Compare two formulas for sorting."
1779 (let ((as (org-table-formula-make-cmp-string (car a
)))
1780 (bs (org-table-formula-make-cmp-string (car b
))))
1781 (and as bs
(string< as bs
))))
1783 (defun org-table-get-stored-formulas (&optional noerror
)
1784 "Return an alist with the stored formulas directly after current table."
1786 (let (scol eq eq-alist strings string seen
)
1788 (goto-char (org-table-end))
1789 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
1790 (setq strings
(org-split-string (match-string 2) " *:: *"))
1791 (while (setq string
(pop strings
))
1792 (when (string-match "\\`\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
1793 (setq scol
(if (match-end 2)
1794 (match-string 2 string
)
1795 (match-string 1 string
))
1796 eq
(match-string 3 string
)
1797 eq-alist
(cons (cons scol eq
) eq-alist
))
1798 (if (member scol seen
)
1801 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
1804 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
1805 (push scol seen
))))))
1806 (nreverse eq-alist
)))
1808 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
1809 "Modify the equations after the table structure has been edited.
1810 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
1811 For all numbers larger than LIMIT, shift them by DELTA."
1813 (goto-char (org-table-end))
1814 (when (looking-at "#\\+TBLFM:")
1815 (let ((re (concat key
"\\([0-9]+\\)"))
1819 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove
)
1820 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
1823 (while (re-search-forward re2
(point-at-eol) t
)
1824 (replace-match "")))
1825 (while (re-search-forward re
(point-at-eol) t
)
1826 (setq s
(match-string 1) n
(string-to-number s
))
1828 ((setq a
(assoc s replace
))
1829 (replace-match (concat key
(cdr a
)) t t
))
1830 ((and limit
(> n limit
))
1831 (replace-match (concat key
(int-to-string (+ n delta
))) t t
))))))))
1833 (defun org-table-get-specials ()
1834 "Get the column names and local parameters for this table."
1836 (let ((beg (org-table-begin)) (end (org-table-end))
1837 names name fields fields1 field cnt
1838 c v l line col types dlines hlines
)
1839 (setq org-table-column-names nil
1840 org-table-local-parameters nil
1841 org-table-named-field-locations nil
1842 org-table-current-begin-line nil
1843 org-table-current-begin-pos nil
1844 org-table-current-line-types nil
)
1846 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
1847 (setq names
(org-split-string (match-string 1) " *| *")
1849 (while (setq name
(pop names
))
1851 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name
)
1852 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
1853 (setq org-table-column-names
(nreverse org-table-column-names
))
1854 (setq org-table-column-name-regexp
1855 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
1857 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
1858 (setq fields
(org-split-string (match-string 1) " *| *"))
1859 (while (setq field
(pop fields
))
1860 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
1861 (push (cons (match-string 1 field
) (match-string 2 field
))
1862 org-table-local-parameters
))))
1864 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
1865 (setq c
(match-string 1)
1866 fields
(org-split-string (match-string 2) " *| *"))
1868 (beginning-of-line (if (equal c
"_") 2 0))
1869 (setq line
(org-current-line) col
1)
1870 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
1871 (setq fields1
(org-split-string (match-string 1) " *| *"))))
1872 (while (and fields1
(setq field
(pop fields
)))
1873 (setq v
(pop fields1
) col
(1+ col
))
1874 (when (and (stringp field
) (stringp v
)
1875 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field
))
1876 (push (cons field v
) org-table-local-parameters
)
1877 (push (list field line col
) org-table-named-field-locations
))))
1878 ;; Analyse the line types
1880 (setq org-table-current-begin-line
(org-current-line)
1881 org-table-current-begin-pos
(point)
1882 l org-table-current-begin-line
)
1883 (while (looking-at "[ \t]*|\\(-\\)?")
1884 (push (if (match-end 1) 'hline
'dline
) types
)
1885 (if (match-end 1) (push l hlines
) (push l dlines
))
1886 (beginning-of-line 2)
1888 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
1889 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
1890 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
)))))))
1892 (defun org-table-maybe-eval-formula ()
1893 "Check if the current field starts with \"=\" or \":=\".
1894 If yes, store the formula and apply it."
1895 ;; We already know we are in a table. Get field will only return a formula
1896 ;; when appropriate. It might return a separator line, but no problem.
1897 (when org-table-formula-evaluate-inline
1898 (let* ((field (org-trim (or (org-table-get-field) "")))
1900 (when (string-match "^:?=\\(.*\\)" field
)
1901 (setq named
(equal (string-to-char field
) ?
:)
1902 eq
(match-string 1 field
))
1903 (if (or (fboundp 'calc-eval
)
1904 (equal (substring eq
0 (min 2 (length eq
))) "'("))
1905 (org-table-eval-formula (if named
'(4) nil
)
1906 (org-table-formula-from-user eq
))
1907 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
1909 (defvar org-recalc-commands nil
1910 "List of commands triggering the recalculation of a line.
1911 Will be filled automatically during use.")
1913 (defvar org-recalc-marks
1914 '((" " .
"Unmarked: no special line, no automatic recalculation")
1915 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
1916 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
1917 ("!" .
"Column name definition line. Reference in formula as $name.")
1918 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
1919 ("_" .
"Names for values in row below this one.")
1920 ("^" .
"Names for values in row above this one.")))
1922 (defun org-table-rotate-recalc-marks (&optional newchar
)
1923 "Rotate the recalculation mark in the first column.
1924 If in any row, the first field is not consistent with a mark,
1925 insert a new column for the markers.
1926 When there is an active region, change all the lines in the region,
1927 after prompting for the marking character.
1928 After each change, a message will be displayed indicating the meaning
1931 (unless (org-at-table-p) (error "Not at a table"))
1932 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
1933 (beg (org-table-begin))
1934 (end (org-table-end))
1935 (l (org-current-line))
1936 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
1937 (l2 (if (org-region-active-p) (org-current-line (region-end))))
1941 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
1942 (col (org-table-current-column))
1943 (forcenew (car (assoc newchar org-recalc-marks
)))
1946 (message "Change region to what mark? Type # * ! $ or SPC: ")
1947 (setq newchar
(char-to-string (read-char-exclusive))
1948 forcenew
(car (assoc newchar org-recalc-marks
))))
1949 (if (and newchar
(not forcenew
))
1950 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
1952 (if l1
(goto-line l1
))
1954 (beginning-of-line 1)
1955 (unless (looking-at org-table-dataline-regexp
)
1956 (error "Not at a table data line")))
1958 (org-table-goto-column 1)
1959 (org-table-insert-column)
1960 (org-table-goto-column (1+ col
)))
1961 (setq epos
(point-at-eol))
1963 (beginning-of-line 1)
1964 (org-table-get-field
1965 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
1967 (setq new
(or forcenew
1968 (cadr (member (match-string 1) marks
))))
1974 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
1975 (and (looking-at org-table-dataline-regexp
)
1976 (org-table-get-field 1 (concat " " new
" "))))
1978 (if (not (= epos
(point-at-eol))) (org-table-align))
1980 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks
))))))
1982 (defun org-table-maybe-recalculate-line ()
1983 "Recompute the current line if marked for it, and if we haven't just done it."
1985 (and org-table-allow-automatic-line-recalculation
1986 (not (and (memq last-command org-recalc-commands
)
1987 (equal org-last-recalc-line
(org-current-line))))
1988 (save-excursion (beginning-of-line 1)
1989 (looking-at org-table-auto-recalculate-regexp
))
1990 (org-table-recalculate) t
))
1993 (defsubst org-set-calc-mode
(var &optional value
)
1995 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
1996 ("R" calc-angle-mode rad
)
1997 ("F" calc-prefer-frac t
)
1998 ("S" calc-symbolic-mode t
)))
1999 value
(nth 2 var
) var
(nth 1 var
)))
2000 (if (memq var modes
)
2001 (setcar (cdr (memq var modes
)) value
)
2002 (cons var
(cons value modes
)))
2005 (defun org-table-eval-formula (&optional arg equation
2006 suppress-align suppress-const
2007 suppress-store suppress-analysis
)
2008 "Replace the table field value at the cursor by the result of a calculation.
2010 This function makes use of Dave Gillespie's Calc package, in my view the
2011 most exciting program ever written for GNU Emacs. So you need to have Calc
2012 installed in order to use this function.
2014 In a table, this command replaces the value in the current field with the
2015 result of a formula. It also installs the formula as the \"current\" column
2016 formula, by storing it in a special line below the table. When called
2017 with a `C-u' prefix, the current field must ba a named field, and the
2018 formula is installed as valid in only this specific field.
2020 When called with two `C-u' prefixes, insert the active equation
2021 for the field back into the current field, so that it can be
2022 edited there. This is useful in order to use \\[org-table-show-reference]
2023 to check the referenced fields.
2025 When called, the command first prompts for a formula, which is read in
2026 the minibuffer. Previously entered formulas are available through the
2027 history list, and the last used formula is offered as a default.
2028 These stored formulas are adapted correctly when moving, inserting, or
2029 deleting columns with the corresponding commands.
2031 The formula can be any algebraic expression understood by the Calc package.
2032 For details, see the Org-mode manual.
2034 This function can also be called from Lisp programs and offers
2035 additional arguments: EQUATION can be the formula to apply. If this
2036 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2037 used to speed-up recursive calls by by-passing unnecessary aligns.
2038 SUPPRESS-CONST suppresses the interpretation of constants in the
2039 formula, assuming that this has been done already outside the function.
2040 SUPPRESS-STORE means the formula should not be stored, either because
2041 it is already stored, or because it is a modified equation that should
2042 not overwrite the stored one."
2044 (org-table-check-inside-data-field)
2045 (or suppress-analysis
(org-table-get-specials))
2046 (if (equal arg
'(16))
2047 (let ((eq (org-table-current-field-formula)))
2048 (or eq
(error "No equation active for current field"))
2049 (org-table-get-field nil eq
)
2051 (setq org-table-may-need-update t
))
2053 (ndown (if (integerp arg
) arg
1))
2054 (org-table-automatic-realign nil
)
2055 (case-fold-search nil
)
2057 (formula (if (and equation suppress-store
)
2059 (org-table-get-formula equation
(equal arg
'(4)))))
2060 (n0 (org-table-current-column))
2061 (modes (copy-sequence org-calc-default-modes
))
2062 (numbers nil
) ; was a variable, now fixed default
2064 n form form0 bw fmt x ev orig c lispp literal
)
2065 ;; Parse the format string. Since we have a lot of modes, this is
2066 ;; a lot of work. However, I think calc still uses most of the time.
2067 (if (string-match ";" formula
)
2068 (let ((tmp (org-split-string formula
";")))
2069 (setq formula
(car tmp
)
2070 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2072 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2073 (setq c
(string-to-char (match-string 1 fmt
))
2074 n
(string-to-number (match-string 2 fmt
)))
2076 (setq modes
(org-set-calc-mode 'calc-internal-prec n
))
2077 (setq modes
(org-set-calc-mode
2079 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2080 (?s . sci
) (?e . eng
))))
2082 (setq fmt
(replace-match "" t t fmt
)))
2083 (if (string-match "[NT]" fmt
)
2084 (setq numbers
(equal (match-string 0 fmt
) "N")
2085 fmt
(replace-match "" t t fmt
)))
2086 (if (string-match "L" fmt
)
2088 fmt
(replace-match "" t t fmt
)))
2089 (if (string-match "E" fmt
)
2091 fmt
(replace-match "" t t fmt
)))
2092 (while (string-match "[DRFS]" fmt
)
2093 (setq modes
(org-set-calc-mode (match-string 0 fmt
)))
2094 (setq fmt
(replace-match "" t t fmt
)))
2095 (unless (string-match "\\S-" fmt
)
2097 (if (and (not suppress-const
) org-table-formula-use-constants
)
2098 (setq formula
(org-table-formula-substitute-names formula
)))
2099 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2101 (setq fields
(org-split-string
2103 (buffer-substring (point-at-bol) (point-at-eol)))
2106 (setq fields
(mapcar
2107 (lambda (x) (number-to-string (string-to-number x
)))
2109 (setq ndown
(1- ndown
))
2110 (setq form
(copy-sequence formula
)
2111 lispp
(and (> (length form
) 2)(equal (substring form
0 2) "'(")))
2112 (if (and lispp literal
) (setq lispp
'literal
))
2113 ;; Check for old vertical references
2114 (setq form
(org-rewrite-old-row-references form
))
2115 ;; Insert complex ranges
2116 (while (string-match org-table-range-regexp form
)
2120 (org-table-make-reference
2121 (org-table-get-range (match-string 0 form
) nil n0
)
2122 keep-empty numbers lispp
))
2124 ;; Insert simple ranges
2125 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2129 (org-table-make-reference
2131 fields
(string-to-number (match-string 1 form
))
2132 (string-to-number (match-string 2 form
)))
2133 keep-empty numbers lispp
))
2136 ;; Insert the references to fields in same row
2137 (while (string-match "\\$\\([0-9]+\\)" form
)
2138 (setq n
(string-to-number (match-string 1 form
))
2139 x
(nth (1- (if (= n
0) n0 n
)) fields
))
2140 (unless x
(error "Invalid field specifier \"%s\""
2141 (match-string 0 form
)))
2142 (setq form
(replace-match
2144 (org-table-make-reference x nil numbers lispp
))
2148 (setq ev
(condition-case nil
2149 (eval (eval (read form
)))
2151 ev
(if (numberp ev
) (number-to-string ev
) ev
))
2152 (or (fboundp 'calc-eval
)
2153 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2154 (setq ev
(calc-eval (cons form modes
)
2155 (if numbers
'num
))))
2157 (when org-table-formula-debug
2158 (with-output-to-temp-buffer "*Substitution History*"
2159 (princ (format "Substitution history of formula
2163 $1-> %s\n" orig formula form0 form
))
2165 (princ (format " %s^\nError: %s"
2166 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2167 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2169 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2170 (setq bw
(get-buffer-window "*Substitution History*"))
2171 (shrink-window-if-larger-than-buffer bw
)
2172 (unless (and (interactive-p) (not ndown
))
2173 (unless (let (inhibit-redisplay)
2174 (y-or-n-p "Debugging Formula. Continue to next? "))
2179 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2180 (org-table-justify-field-maybe
2181 (if fmt
(format fmt
(string-to-number ev
)) ev
))
2182 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2183 (call-interactively 'org-return
)
2185 (and down
(org-table-maybe-recalculate-line))
2186 (or suppress-align
(and org-table-may-need-update
2187 (org-table-align))))))
2189 (defun org-table-put-field-property (prop value
)
2191 (put-text-property (progn (skip-chars-backward "^|") (point))
2192 (progn (skip-chars-forward "^|") (point))
2195 (defun org-table-get-range (desc &optional tbeg col highlight
)
2196 "Get a calc vector from a column, accorting to descriptor DESC.
2197 Optional arguments TBEG and COL can give the beginning of the table and
2198 the current column, to avoid unnecessary parsing.
2199 HIGHLIGHT means, just highlight the range."
2200 (if (not (equal (string-to-char desc
) ?
@))
2201 (setq desc
(concat "@" desc
)))
2203 (or tbeg
(setq tbeg
(org-table-begin)))
2204 (or col
(setq col
(org-table-current-column)))
2205 (let ((thisline (org-current-line))
2206 beg end c1 c2 r1 r2 rangep tmp
)
2207 (unless (string-match org-table-range-regexp desc
)
2208 (error "Invalid table range specifier `%s'" desc
))
2209 (setq rangep
(match-end 3)
2210 r1
(and (match-end 1) (match-string 1 desc
))
2211 r2
(and (match-end 4) (match-string 4 desc
))
2212 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2213 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2215 (and c1
(setq c1
(+ (string-to-number c1
)
2216 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2217 (and c2
(setq c2
(+ (string-to-number c2
)
2218 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2219 (if (equal r1
"") (setq r1 nil
))
2220 (if (equal r2
"") (setq r2 nil
))
2221 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2222 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2223 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2224 (if (not r1
) (setq r1 thisline
))
2225 (if (not r2
) (setq r2 thisline
))
2226 (if (not c1
) (setq c1 col
))
2227 (if (not c2
) (setq c2 col
))
2228 (if (or (not rangep
) (and (= r1 r2
) (= c1 c2
)))
2232 (while (not (looking-at org-table-dataline-regexp
))
2233 (beginning-of-line 2))
2234 (prog1 (org-trim (org-table-get-field c1
))
2235 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2236 ;; A range, return a vector
2237 ;; First sort the numbers to get a regular ractangle
2238 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2239 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2241 (while (not (looking-at org-table-dataline-regexp
))
2242 (beginning-of-line 2))
2243 (org-table-goto-column c1
)
2246 (while (not (looking-at org-table-dataline-regexp
))
2247 (beginning-of-line 0))
2248 (org-table-goto-column c2
)
2251 (org-table-highlight-rectangle
2252 beg
(progn (skip-chars-forward "^|\n") (point))))
2253 ;; return string representation of calc vector
2255 (apply 'append
(org-table-copy-region beg end
)))))))
2257 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2258 "Analyze descriptor DESC and retrieve the corresponding line number.
2259 The cursor is currently in line CLINE, the table begins in line BLINE,
2260 and TABLE is a vector with line types."
2261 (if (string-match "^[0-9]+$" desc
)
2262 (aref org-table-dlines
(string-to-number desc
))
2263 (setq cline
(or cline
(org-current-line))
2264 bline
(or bline org-table-current-begin-line
)
2265 table
(or table org-table-current-line-types
))
2267 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2269 (and (not (match-end 3)) (not (match-end 6)))
2270 (and (match-end 3) (match-end 6) (not (match-end 5))))
2271 (error "invalid row descriptor `%s'" desc
))
2272 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2273 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2274 (odir (and (match-end 5) (match-string 5 desc
)))
2275 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2277 (rel (and (match-end 6)
2278 (or (and (match-end 1) (not (match-end 3)))
2280 (if (and hn
(not hdir
))
2283 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2284 (if (and (not hn
) on
(not odir
))
2285 (error "should never happen");;(aref org-table-dlines on)
2286 (if (and hn
(> hn
0))
2287 (setq i
(org-find-row-type table i
'hline
(equal hdir
"-") nil hn
)))
2289 (setq i
(org-find-row-type table i
'dline
(equal odir
"-") rel on
)))
2292 (defun org-find-row-type (table i type backwards relative n
)
2293 (let ((l (length table
)))
2295 (while (and (setq i
(+ i
(if backwards -
1 1)))
2297 (not (eq (aref table i
) type
))
2298 (if (and relative
(eq (aref table i
) 'hline
))
2299 (progn (setq i
(- i
(if backwards -
1 1)) n
1) nil
)
2302 (if (or (< i
0) (>= i l
))
2303 (error "Row descriptor leads outside table")
2306 (defun org-rewrite-old-row-references (s)
2307 (if (string-match "&[-+0-9I]" s
)
2308 (error "Formula contains old &row reference, please rewrite using @-syntax")
2311 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2312 "Convert list ELEMENTS to something appropriate to insert into formula.
2313 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2314 NUMBERS indicates that everything should be converted to numbers.
2315 LISPP means to return something appropriate for a Lisp list."
2316 (if (stringp elements
) ; just a single val
2318 (if (eq lispp
'literal
)
2320 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2321 (if (equal elements
"") (setq elements
"0"))
2322 (if numbers
(setq elements
(number-to-string (string-to-number elements
))))
2323 (concat "(" elements
")"))
2327 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2329 (setq elements
(or elements
'("0")))
2333 (if (eq lispp
'literal
)
2335 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2337 (concat "[" (mapconcat
2339 (if numbers
(number-to-string (string-to-number x
)) x
))
2343 (defun org-table-recalculate (&optional all noalign
)
2344 "Recalculate the current table line by applying all stored formulas.
2345 With prefix arg ALL, do this for all lines in the table."
2347 (or (memq this-command org-recalc-commands
)
2348 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2349 (unless (org-at-table-p) (error "Not at a table"))
2350 (if (equal all
'(16))
2352 (org-table-get-specials)
2353 (let* ((eqlist (sort (org-table-get-stored-formulas)
2354 (lambda (a b
) (string< (car a
) (car b
)))))
2355 (inhibit-redisplay (not debug-on-error
))
2356 (line-re org-table-dataline-regexp
)
2357 (thisline (org-current-line))
2358 (thiscol (org-table-current-column))
2359 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name
)
2360 ;; Insert constants in all formulas
2363 (setcdr x
(org-table-formula-substitute-names (cdr x
)))
2366 ;; Split the equation list
2367 (while (setq eq
(pop eqlist
))
2368 (if (<= (string-to-char (car eq
)) ?
9)
2371 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
2374 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
2375 (goto-char (setq beg
(org-table-begin)))
2376 (if (re-search-forward org-table-calculate-mark-regexp end t
)
2377 ;; This is a table with marked lines, compute selected lines
2378 (setq line-re org-table-recalculate-regexp
)
2379 ;; Move forward to the first non-header line
2380 (if (and (re-search-forward org-table-dataline-regexp end t
)
2381 (re-search-forward org-table-hline-regexp end t
)
2382 (re-search-forward org-table-dataline-regexp end t
))
2383 (setq beg
(match-beginning 0))
2384 nil
))) ;; just leave beg where it is
2385 (setq beg
(point-at-bol)
2386 end
(move-marker (make-marker) (1+ (point-at-eol)))))
2388 (and all
(message "Re-applying formulas to full table..."))
2390 ;; First find the named fields, and mark them untouchable
2391 (remove-text-properties beg end
'(org-untouchable t
))
2392 (while (setq eq
(pop eqlname
))
2394 a
(assoc name org-table-named-field-locations
))
2396 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
2399 (aref org-table-dlines
2400 (string-to-number (match-string 1 name
)))
2401 (error (error "Invalid row number in %s"
2403 (string-to-number (match-string 2 name
)))))
2404 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
2405 (message "Re-applying formula to field: %s" name
)
2406 (goto-line (nth 1 a
))
2407 (org-table-goto-column (nth 2 a
))
2408 (push (append a
(list (cdr eq
))) eqlname1
)
2409 (org-table-put-field-property :org-untouchable t
)))
2411 ;; Now evauluate the column formulas, but skip fields covered by
2414 (while (re-search-forward line-re end t
)
2415 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2416 ;; Unprotected line, recalculate
2417 (and all
(message "Re-applying formulas to full table...(line %d)"
2418 (setq cnt
(1+ cnt
))))
2419 (setq org-last-recalc-line
(org-current-line))
2421 (while (setq entry
(pop eql
))
2422 (goto-line org-last-recalc-line
)
2423 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
2424 (unless (get-text-property (point) :org-untouchable
)
2425 (org-table-eval-formula nil
(cdr entry
)
2426 'noalign
'nocst
'nostore
'noanalysis
)))))
2428 ;; Now evaluate the field formulas
2429 (while (setq eq
(pop eqlname1
))
2430 (message "Re-applying formula to field: %s" (car eq
))
2431 (goto-line (nth 1 eq
))
2432 (org-table-goto-column (nth 2 eq
))
2433 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
2434 'nostore
'noanalysis
))
2436 (goto-line thisline
)
2437 (org-table-goto-column thiscol
)
2438 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
2439 (or noalign
(and org-table-may-need-update
(org-table-align))
2440 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
2442 ;; back to initial position
2443 (message "Re-applying formulas...done")
2444 (goto-line thisline
)
2445 (org-table-goto-column thiscol
)
2446 (or noalign
(and org-table-may-need-update
(org-table-align))
2447 (and all
(message "Re-applying formulas...done"))))))
2449 (defun org-table-iterate (&optional arg
)
2450 "Recalculate the table until it does not change anymore."
2452 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
2454 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2459 (org-table-recalculate 'all
)
2460 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
2461 (if (not (string= lasttbl thistbl
))
2462 (setq lasttbl thistbl
)
2464 (message "Convergence after %d iterations" i
)
2465 (message "Table was already stable"))
2467 (error "No convergence after %d iterations" i
))))
2469 (defun org-table-formula-substitute-names (f)
2470 "Replace $const with values in string F."
2471 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
2472 ;; First, check for column names
2473 (while (setq start
(string-match org-table-column-name-regexp f start
))
2474 (setq start
(1+ start
))
2475 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
2476 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
2477 ;; Parameters and constants
2479 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start
))
2480 (setq start
(1+ start
))
2481 (if (setq a
(save-match-data
2482 (org-table-get-constant (match-string 1 f
))))
2483 (setq f
(replace-match
2484 (concat (if pp
"(") a
(if pp
")")) t t f
))))
2485 (if org-table-formula-debug
2486 (put-text-property 0 (length f
) :orig-formula f1 f
))
2489 (defun org-table-get-constant (const)
2490 "Find the value for a parameter or constant in a formula.
2491 Parameters get priority."
2492 (or (cdr (assoc const org-table-local-parameters
))
2493 (cdr (assoc const org-table-formula-constants-local
))
2494 (cdr (assoc const org-table-formula-constants
))
2495 (and (fboundp 'constants-get
) (constants-get const
))
2496 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
2497 (org-entry-get nil
(substring const
5) 'inherit
))
2500 (defvar org-table-fedit-map
2501 (let ((map (make-sparse-keymap)))
2502 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
2503 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
2504 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
2505 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
2506 (org-defkey map
"\C-c?" 'org-table-show-reference
)
2507 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
2508 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
2509 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
2510 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
2511 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
2512 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
2513 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
2514 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
2515 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
2516 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
2517 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
2518 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
2519 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
2520 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
2523 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
2525 ["Finish and Install" org-table-fedit-finish t
]
2526 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
2527 ["Abort" org-table-fedit-abort t
]
2529 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
2530 ["Complete Lisp Symbol" lisp-complete-symbol t
]
2532 "Shift Reference at Point"
2533 ["Up" org-table-fedit-ref-up t
]
2534 ["Down" org-table-fedit-ref-down t
]
2535 ["Left" org-table-fedit-ref-left t
]
2536 ["Right" org-table-fedit-ref-right t
]
2538 "Change Test Row for Column Formulas"
2539 ["Up" org-table-fedit-line-up t
]
2540 ["Down" org-table-fedit-line-down t
]
2542 ["Scroll Table Window" org-table-fedit-scroll t
]
2543 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
2544 ["Show Table Grid" org-table-fedit-toggle-coordinates
2545 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
2546 org-table-overlay-coordinates
)]
2548 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
2549 :style toggle
:selected org-table-buffer-is-an
]))
2553 (defun org-table-edit-formulas ()
2554 "Edit the formulas of the current table in a separate buffer."
2556 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
2557 (beginning-of-line 0))
2558 (unless (org-at-table-p) (error "Not at a table"))
2559 (org-table-get-specials)
2560 (let ((key (org-table-current-field-formula 'key
'noerror
))
2561 (eql (sort (org-table-get-stored-formulas 'noerror
)
2562 'org-table-formula-less-p
))
2563 (pos (move-marker (make-marker) (point)))
2565 (wc (current-window-configuration))
2566 (titles '((column .
"# Column Formulas\n")
2567 (field .
"# Field Formulas\n")
2568 (named .
"# Named Field Formulas\n")))
2570 (org-switch-to-buffer-other-window "*Edit Formulas*")
2572 ;; Keep global-font-lock-mode from turning on font-lock-mode
2573 (let ((font-lock-global-modes '(not fundamental-mode
)))
2575 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
2576 (org-set-local 'org-pos pos
)
2577 (org-set-local 'org-window-configuration wc
)
2578 (use-local-map org-table-fedit-map
)
2579 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
2580 (easy-menu-add org-table-fedit-menu
)
2581 (setq startline
(org-current-line))
2582 (while (setq entry
(pop eql
))
2584 ((equal (string-to-char (car entry
)) ?
@) 'field
)
2585 ((string-match "^[0-9]" (car entry
)) 'column
)
2587 (when (setq title
(assq type titles
))
2588 (or (bobp) (insert "\n"))
2589 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
2590 (setq titles
(delq title titles
)))
2591 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
2592 (setq s
(concat (if (equal (string-to-char (car entry
)) ?
@) "" "$")
2593 (car entry
) " = " (cdr entry
) "\n"))
2594 (remove-text-properties 0 (length s
) '(face nil
) s
)
2596 (if (eq org-table-use-standard-references t
)
2597 (org-table-fedit-toggle-ref-type))
2598 (goto-line startline
)
2599 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
2601 (defun org-table-fedit-post-command ()
2602 (when (not (memq this-command
'(lisp-complete-symbol)))
2603 (let ((win (selected-window)))
2606 (org-table-show-reference)
2608 (select-window win
)))))
2610 (defun org-table-formula-to-user (s)
2611 "Convert a formula from internal to user representation."
2612 (if (eq org-table-use-standard-references t
)
2613 (org-table-convert-refs-to-an s
)
2616 (defun org-table-formula-from-user (s)
2617 "Convert a formula from user to internal representation."
2618 (if org-table-use-standard-references
2619 (org-table-convert-refs-to-rc s
)
2622 (defun org-table-convert-refs-to-rc (s)
2623 "Convert spreadsheet references from AB7 to @7$28.
2624 Works for single references, but also for entire formulas and even the
2627 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start
)
2630 ;; format match, just advance
2631 (setq start
(match-end 0)))
2632 ((and (> (match-beginning 0) 0)
2633 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
2634 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
2635 ;; 3.e5 or something like this.
2636 (setq start
(match-end 0)))
2638 (setq start
(match-beginning 0)
2640 (if (equal (match-string 2 s
) "&")
2641 (format "$%d" (org-letters-to-number (match-string 1 s
)))
2643 (string-to-number (match-string 2 s
))
2644 (org-letters-to-number (match-string 1 s
))))
2648 (defun org-table-convert-refs-to-an (s)
2649 "Convert spreadsheet references from to @7$28 to AB7.
2650 Works for single references, but also for entire formulas and even the
2652 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
2653 (setq s
(replace-match
2655 (org-number-to-letters
2656 (string-to-number (match-string 2 s
)))
2657 (string-to-number (match-string 1 s
)))
2659 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
2660 (setq s
(replace-match (concat "\\1"
2661 (org-number-to-letters
2662 (string-to-number (match-string 2 s
))) "&")
2666 (defun org-letters-to-number (s)
2667 "Convert a base 26 number represented by letters into an integer.
2668 For example: AB -> 28."
2671 (while (> (length s
) 0)
2672 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
2676 (defun org-number-to-letters (n)
2677 "Convert an integer into a base 26 number represented by letters.
2678 For example: 28 -> AB."
2681 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
2685 (defun org-table-fedit-convert-buffer (function)
2686 "Convert all references in this buffer, using FUNTION."
2687 (let ((line (org-current-line)))
2688 (goto-char (point-min))
2690 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
2691 (delete-region (point) (point-at-eol))
2692 (or (eobp) (forward-char 1)))
2695 (defun org-table-fedit-toggle-ref-type ()
2696 "Convert all references in the buffer from B3 to @3$2 and back."
2698 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
2699 (org-table-fedit-convert-buffer
2700 (if org-table-buffer-is-an
2701 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
2702 (message "Reference type switched to %s"
2703 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
2705 (defun org-table-fedit-ref-up ()
2706 "Shift the reference at point one row/hline up."
2708 (org-table-fedit-shift-reference 'up
))
2709 (defun org-table-fedit-ref-down ()
2710 "Shift the reference at point one row/hline down."
2712 (org-table-fedit-shift-reference 'down
))
2713 (defun org-table-fedit-ref-left ()
2714 "Shift the reference at point one field to the left."
2716 (org-table-fedit-shift-reference 'left
))
2717 (defun org-table-fedit-ref-right ()
2718 "Shift the reference at point one field to the right."
2720 (org-table-fedit-shift-reference 'right
))
2722 (defun org-table-fedit-shift-reference (dir)
2724 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
2725 (if (memq dir
'(left right
))
2726 (org-rematch-and-replace 1 (eq dir
'left
))
2727 (error "Cannot shift reference in this direction")))
2728 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
2729 ;; A B3-like reference
2730 (if (memq dir
'(up down
))
2731 (org-rematch-and-replace 2 (eq dir
'up
))
2732 (org-rematch-and-replace 1 (eq dir
'left
))))
2734 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
2735 ;; An internal reference
2736 (if (memq dir
'(up down
))
2737 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
2738 (org-rematch-and-replace 5 (eq dir
'left
))))))
2740 (defun org-rematch-and-replace (n &optional decr hline
)
2741 "Re-match the group N, and replace it with the shifted refrence."
2742 (or (match-end n
) (error "Cannot shift reference in this direction"))
2743 (goto-char (match-beginning n
))
2744 (and (looking-at (regexp-quote (match-string n
)))
2745 (replace-match (org-shift-refpart (match-string 0) decr hline
)
2748 (defun org-shift-refpart (ref &optional decr hline
)
2749 "Shift a refrence part REF.
2750 If DECR is set, decrease the references row/column, else increase.
2751 If HLINE is set, this may be a hline reference, it certainly is not
2752 a translation reference."
2754 (let* ((sign (string-match "^[-+]" ref
)) n
)
2756 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
2758 ((and hline
(string-match "^I+" ref
))
2759 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
2760 (setq n
(+ n
(if decr -
1 1)))
2761 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
2763 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
2765 (concat sign
(make-string n ?I
)))
2767 ((string-match "^[0-9]+" ref
)
2768 (setq n
(string-to-number (concat sign ref
)))
2769 (setq n
(+ n
(if decr -
1 1)))
2771 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
2772 (number-to-string (max 1 n
))))
2774 ((string-match "^[a-zA-Z]+" ref
)
2775 (org-number-to-letters
2776 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
2778 (t (error "Cannot shift reference"))))))
2780 (defun org-table-fedit-toggle-coordinates ()
2781 "Toggle the display of coordinates in the refrenced table."
2783 (let ((pos (marker-position org-pos
)))
2784 (with-current-buffer (marker-buffer org-pos
)
2787 (org-table-toggle-coordinate-overlays)))))
2789 (defun org-table-fedit-finish (&optional arg
)
2790 "Parse the buffer for formula definitions and install them.
2791 With prefix ARG, apply the new formulas to the table."
2793 (org-table-remove-rectangle-highlight)
2794 (if org-table-use-standard-references
2796 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
2797 (setq org-table-buffer-is-an nil
)))
2798 (let ((pos org-pos
) eql var form
)
2799 (goto-char (point-min))
2800 (while (re-search-forward
2801 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
2803 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
2804 form
(match-string 3))
2805 (setq form
(org-trim form
))
2806 (when (not (equal form
""))
2807 (while (string-match "[ \t]*\n[ \t]*" form
)
2808 (setq form
(replace-match " " t t form
)))
2809 (when (assoc var eql
)
2810 (error "Double formulas for %s" var
))
2811 (push (cons var form
) eql
)))
2813 (set-window-configuration org-window-configuration
)
2814 (select-window (get-buffer-window (marker-buffer pos
)))
2816 (unless (org-at-table-p)
2817 (error "Lost table position - cannot install formulae"))
2818 (org-table-store-formulas eql
)
2819 (move-marker pos nil
)
2820 (kill-buffer "*Edit Formulas*")
2822 (org-table-recalculate 'all
)
2823 (message "New formulas installed - press C-u C-c C-c to apply."))))
2825 (defun org-table-fedit-abort ()
2826 "Abort editing formulas, without installing the changes."
2828 (org-table-remove-rectangle-highlight)
2829 (let ((pos org-pos
))
2830 (set-window-configuration org-window-configuration
)
2831 (select-window (get-buffer-window (marker-buffer pos
)))
2833 (move-marker pos nil
)
2834 (message "Formula editing aborted without installing changes")))
2836 (defun org-table-fedit-lisp-indent ()
2837 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
2839 (let ((pos (point)) beg end ind
)
2840 (beginning-of-line 1)
2842 ((looking-at "[ \t]")
2844 (call-interactively 'lisp-indent-line
))
2845 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
2846 ((not (fboundp 'pp-buffer
))
2847 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
2848 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
2849 (goto-char (- (match-end 0) 2))
2851 (setq ind
(make-string (current-column) ?\
))
2852 (condition-case nil
(forward-sexp 1)
2854 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
2857 (narrow-to-region beg end
)
2858 (if (eq last-command this-command
)
2860 (goto-char (point-min))
2861 (setq this-command nil
)
2862 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
2863 (replace-match " ")))
2865 (untabify (point-min) (point-max))
2866 (goto-char (1+ (point-min)))
2867 (while (re-search-forward "^." nil t
)
2868 (beginning-of-line 1)
2870 (goto-char (point-max))
2871 (backward-delete-char 1)))
2875 (defvar org-show-positions nil
)
2877 (defun org-table-show-reference (&optional local
)
2878 "Show the location/value of the $ expression at point."
2880 (org-table-remove-rectangle-highlight)
2882 (let ((pos (if local
(point) org-pos
))
2884 (org-inhibit-highlight-removal t
)
2885 (win (selected-window))
2886 (org-show-positions nil
)
2887 var name e what match dest
)
2888 (if local
(org-table-get-specials))
2890 ((or (org-at-regexp-p org-table-range-regexp2
)
2891 (org-at-regexp-p org-table-translate-regexp
)
2892 (org-at-regexp-p org-table-range-regexp
))
2895 (org-table-convert-refs-to-rc (match-string 0))))
2897 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
2898 ((org-at-regexp-p "\\$[0-9]+") 'column
)
2900 (t (error "No reference at point")))
2901 match
(and what
(or match
(match-string 0))))
2902 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
2903 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
2904 'secondary-selection
))
2905 (org-add-hook 'before-change-functions
2906 'org-table-remove-rectangle-highlight
)
2907 (if (eq what
'name
) (setq var
(substring match
1)))
2908 (when (eq what
'range
)
2909 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
2910 (setq match
(org-table-formula-substitute-names match
)))
2914 (re-search-backward "^\\S-" nil t
)
2915 (beginning-of-line 1)
2916 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
2919 (org-table-convert-refs-to-rc (match-string 1))))
2920 (org-table-add-rectangle-overlay
2921 (match-beginning 1) (match-end 1) face2
))))
2922 (if (and (markerp pos
) (marker-buffer pos
))
2923 (if (get-buffer-window (marker-buffer pos
))
2924 (select-window (get-buffer-window (marker-buffer pos
)))
2925 (org-switch-to-buffer-other-window (get-buffer-window
2926 (marker-buffer pos
)))))
2928 (org-table-force-dataline)
2930 (setq name
(substring dest
1))
2932 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
2933 (setq e
(assoc name org-table-named-field-locations
))
2934 (goto-line (nth 1 e
))
2935 (org-table-goto-column (nth 2 e
)))
2936 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
2937 (let ((l (string-to-number (match-string 1 dest
)))
2938 (c (string-to-number (match-string 2 dest
))))
2939 (goto-line (aref org-table-dlines l
))
2940 (org-table-goto-column c
)))
2941 (t (org-table-goto-column (string-to-number name
))))
2942 (move-marker pos
(point))
2943 (org-table-highlight-rectangle nil nil face2
))
2945 ((equal dest match
))
2950 (org-table-get-range match nil nil
'highlight
))
2952 ((setq e
(assoc var org-table-named-field-locations
))
2953 (goto-line (nth 1 e
))
2954 (org-table-goto-column (nth 2 e
))
2955 (org-table-highlight-rectangle (point) (point))
2956 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
2957 ((setq e
(assoc var org-table-column-names
))
2958 (org-table-goto-column (string-to-number (cdr e
)))
2959 (org-table-highlight-rectangle (point) (point))
2960 (goto-char (org-table-begin))
2961 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
2964 (goto-char (match-beginning 1))
2965 (org-table-highlight-rectangle)
2966 (message "Named column (column %s)" (cdr e
)))
2967 (error "Column name not found")))
2970 (org-table-goto-column (string-to-number (substring match
1)))
2971 (org-table-highlight-rectangle (point) (point))
2972 (message "Column %s" (substring match
1)))
2973 ((setq e
(assoc var org-table-local-parameters
))
2974 (goto-char (org-table-begin))
2975 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
2977 (goto-char (match-beginning 1))
2978 (org-table-highlight-rectangle)
2979 (message "Local parameter."))
2980 (error "Parameter not found")))
2983 ((not var
) (error "No reference at point"))
2984 ((setq e
(assoc var org-table-formula-constants-local
))
2985 (message "Local Constant: $%s=%s in #+CONSTANTS line."
2987 ((setq e
(assoc var org-table-formula-constants
))
2988 (message "Constant: $%s=%s in `org-table-formula-constants'."
2990 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
2991 (message "Constant: $%s=%s, from `constants.el'%s."
2992 var e
(format " (%s units)" constants-unit-system
)))
2993 (t (error "Undefined name $%s" var
)))))
2995 (when (and org-show-positions
2996 (not (memq this-command
'(org-table-fedit-scroll
2997 org-table-fedit-scroll-down
))))
2998 (push pos org-show-positions
)
2999 (push org-table-current-begin-pos org-show-positions
)
3000 (let ((min (apply 'min org-show-positions
))
3001 (max (apply 'max org-show-positions
)))
3002 (goto-char min
) (recenter 0)
3004 (or (pos-visible-in-window-p max
) (recenter -
1))))
3005 (select-window win
))))
3007 (defun org-table-force-dataline ()
3008 "Make sure the cursor is in a dataline in a table."
3009 (unless (save-excursion
3010 (beginning-of-line 1)
3011 (looking-at org-table-dataline-regexp
))
3012 (let* ((re org-table-dataline-regexp
)
3013 (p1 (save-excursion (re-search-forward re nil
'move
)))
3014 (p2 (save-excursion (re-search-backward re nil
'move
))))
3016 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3018 ((or p1 p2
) (goto-char (or p1 p2
)))
3019 (t (error "No table dataline around here"))))))
3021 (defun org-table-fedit-line-up ()
3022 "Move cursor one line up in the window showing the table."
3024 (org-table-fedit-move 'previous-line
))
3026 (defun org-table-fedit-line-down ()
3027 "Move cursor one line down in the window showing the table."
3029 (org-table-fedit-move 'next-line
))
3031 (defun org-table-fedit-move (command)
3032 "Move the cursor in the window shoinw the table.
3033 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3034 (let ((org-table-allow-automatic-line-recalculation nil
)
3035 (pos org-pos
) (win (selected-window)) p
)
3036 (select-window (get-buffer-window (marker-buffer org-pos
)))
3038 (call-interactively command
)
3039 (while (and (org-at-table-p)
3040 (org-at-table-hline-p))
3041 (call-interactively command
))
3042 (or (org-at-table-p) (goto-char p
))
3043 (move-marker pos
(point))
3044 (select-window win
)))
3046 (defun org-table-fedit-scroll (N)
3048 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3049 (scroll-other-window N
)))
3051 (defun org-table-fedit-scroll-down (N)
3053 (org-table-fedit-scroll (- N
)))
3055 (defvar org-table-rectangle-overlays nil
)
3057 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3058 "Add a new overlay."
3059 (let ((ov (org-make-overlay beg end
)))
3060 (org-overlay-put ov
'face
(or face
'secondary-selection
))
3061 (push ov org-table-rectangle-overlays
)))
3063 (defun org-table-highlight-rectangle (&optional beg end face
)
3064 "Highlight rectangular region in a table."
3065 (setq beg
(or beg
(point)) end
(or end
(point)))
3066 (let ((b (min beg end
))
3069 (and (boundp 'org-show-positions
)
3070 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3071 (goto-char (min beg end
))
3072 (setq l1
(org-current-line)
3073 c1
(org-table-current-column))
3074 (goto-char (max beg end
))
3075 (setq l2
(org-current-line)
3076 c2
(org-table-current-column))
3077 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3079 (beginning-of-line 1)
3080 (loop for line from l1 to l2 do
3081 (when (looking-at org-table-dataline-regexp
)
3082 (org-table-goto-column c1
)
3083 (skip-chars-backward "^|\n") (setq beg
(point))
3084 (org-table-goto-column c2
)
3085 (skip-chars-forward "^|\n") (setq end
(point))
3086 (org-table-add-rectangle-overlay beg end face
))
3087 (beginning-of-line 2))
3089 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3091 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3092 "Remove the rectangle overlays."
3093 (unless org-inhibit-highlight-removal
3094 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3095 (mapc 'org-delete-overlay org-table-rectangle-overlays
)
3096 (setq org-table-rectangle-overlays nil
)))
3098 (defvar org-table-coordinate-overlays nil
3099 "Collects the cooordinate grid overlays, so that they can be removed.")
3100 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3102 (defun org-table-overlay-coordinates ()
3103 "Add overlays to the table at point, to show row/column coordinates."
3105 (mapc 'org-delete-overlay org-table-coordinate-overlays
)
3106 (setq org-table-coordinate-overlays nil
)
3108 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3109 (goto-char (org-table-begin))
3110 (while (org-at-table-p)
3111 (setq eol
(point-at-eol))
3112 (setq ov
(org-make-overlay (point-at-bol) (1+ (point-at-bol))))
3113 (push ov org-table-coordinate-overlays
)
3114 (setq hline
(looking-at org-table-hline-regexp
))
3115 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3116 (format "%4d" (setq id
(1+ id
)))))
3117 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3120 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3121 (setq beg
(1+ (match-beginning 0))
3123 s1
(concat "$" (int-to-string ic
))
3124 s2
(org-number-to-letters ic
)
3125 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3126 (setq ov
(org-make-overlay beg
(+ beg
(length str
))))
3127 (push ov org-table-coordinate-overlays
)
3128 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3129 (beginning-of-line 2)))))
3131 (defun org-table-toggle-coordinate-overlays ()
3132 "Toggle the display of Row/Column numbers in tables."
3134 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3135 (message "Row/Column number display turned %s"
3136 (if org-table-overlay-coordinates
"on" "off"))
3137 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3139 (unless org-table-overlay-coordinates
3140 (mapc 'org-delete-overlay org-table-coordinate-overlays
)
3141 (setq org-table-coordinate-overlays nil
)))
3143 (defun org-table-toggle-formula-debugger ()
3144 "Toggle the formula debugger in tables."
3146 (setq org-table-formula-debug
(not org-table-formula-debug
))
3147 (message "Formula debugging has been turned %s"
3148 (if org-table-formula-debug
"on" "off")))
3150 ;;; The orgtbl minor mode
3152 ;; Define a minor mode which can be used in other modes in order to
3153 ;; integrate the org-mode table editor.
3155 ;; This is really a hack, because the org-mode table editor uses several
3156 ;; keys which normally belong to the major mode, for example the TAB and
3157 ;; RET keys. Here is how it works: The minor mode defines all the keys
3158 ;; necessary to operate the table editor, but wraps the commands into a
3159 ;; function which tests if the cursor is currently inside a table. If that
3160 ;; is the case, the table editor command is executed. However, when any of
3161 ;; those keys is used outside a table, the function uses `key-binding' to
3162 ;; look up if the key has an associated command in another currently active
3163 ;; keymap (minor modes, major mode, global), and executes that command.
3164 ;; There might be problems if any of the keys used by the table editor is
3165 ;; otherwise used as a prefix key.
3167 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3168 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3169 ;; addresses this by checking explicitly for both bindings.
3171 ;; The optimized version (see variable `orgtbl-optimized') takes over
3172 ;; all keys which are bound to `self-insert-command' in the *global map*.
3173 ;; Some modes bind other commands to simple characters, for example
3174 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3175 ;; active, this binding is ignored inside tables and replaced with a
3176 ;; modified self-insert.
3178 (defvar orgtbl-mode nil
3179 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
3180 table editor in arbitrary modes.")
3181 (make-variable-buffer-local 'orgtbl-mode
)
3183 (defvar orgtbl-mode-map
(make-keymap)
3184 "Keymap for `orgtbl-mode'.")
3187 (defun turn-on-orgtbl ()
3188 "Unconditionally turn on `orgtbl-mode'."
3191 (defvar org-old-auto-fill-inhibit-regexp nil
3192 "Local variable used by `orgtbl-mode'")
3194 (defconst orgtbl-line-start-regexp
"[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
3195 "Matches a line belonging to an orgtbl.")
3197 (defconst orgtbl-extra-font-lock-keywords
3198 (list (list (concat "^" orgtbl-line-start-regexp
".*")
3199 0 (quote 'org-table
) 'prepend
))
3200 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
3203 (defun orgtbl-mode (&optional arg
)
3204 "The `org-mode' table editor as a minor mode for use in other modes."
3206 (org-load-modules-maybe)
3208 ;; Exit without error, in case some hook functions calls this
3209 ;; by accident in org-mode.
3210 (message "Orgtbl-mode is not useful in org-mode, command ignored")
3212 (if arg
(> (prefix-numeric-value arg
) 0) (not orgtbl-mode
)))
3215 (and (orgtbl-setup) (defun orgtbl-setup () nil
))
3216 ;; Make sure we are first in minor-mode-map-alist
3217 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
3218 (and c
(setq minor-mode-map-alist
3219 (cons c
(delq c minor-mode-map-alist
)))))
3220 (org-set-local (quote org-table-may-need-update
) t
)
3221 (org-add-hook 'before-change-functions
'org-before-change-function
3223 (org-set-local 'org-old-auto-fill-inhibit-regexp
3224 auto-fill-inhibit-regexp
)
3225 (org-set-local 'auto-fill-inhibit-regexp
3226 (if auto-fill-inhibit-regexp
3227 (concat orgtbl-line-start-regexp
"\\|"
3228 auto-fill-inhibit-regexp
)
3229 orgtbl-line-start-regexp
))
3230 (org-add-to-invisibility-spec '(org-cwidth))
3231 (when (fboundp 'font-lock-add-keywords
)
3232 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
3233 (org-restart-font-lock))
3234 (easy-menu-add orgtbl-mode-menu
)
3235 (run-hooks 'orgtbl-mode-hook
))
3236 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
3237 (org-cleanup-narrow-column-properties)
3238 (org-remove-from-invisibility-spec '(org-cwidth))
3239 (remove-hook 'before-change-functions
'org-before-change-function t
)
3240 (when (fboundp 'font-lock-remove-keywords
)
3241 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
3242 (org-restart-font-lock))
3243 (easy-menu-remove orgtbl-mode-menu
)
3244 (force-mode-line-update 'all
))))
3246 (defun org-cleanup-narrow-column-properties ()
3247 "Remove all properties related to narrow-column invisibility."
3249 (while (setq s
(text-property-any s
(point-max)
3250 'display org-narrow-column-arrow
))
3251 (remove-text-properties s
(1+ s
) '(display t
)))
3253 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
3254 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
3256 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
3257 (remove-text-properties s
(1+ s
) '(invisible t
)))))
3259 ;; Install it as a minor mode.
3260 (put 'orgtbl-mode
:included t
)
3261 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
3262 (add-minor-mode 'orgtbl-mode
" OrgTbl" orgtbl-mode-map
)
3264 (defun orgtbl-make-binding (fun n
&rest keys
)
3265 "Create a function for binding in the table minor mode.
3266 FUN is the command to call inside a table. N is used to create a unique
3267 command name. KEYS are keys that should be checked in for a command
3268 to execute outside of tables."
3271 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
3273 (concat "In tables, run `" (symbol-name fun
) "'.\n"
3274 "Outside of tables, run the binding of `"
3275 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
3280 (list 'call-interactively
(list 'quote fun
))
3281 (list 'let
'(orgtbl-mode)
3282 (list 'call-interactively
3285 (list 'key-binding k
))
3287 '('orgtbl-error
))))))))
3289 (defun orgtbl-error ()
3290 "Error when there is no default binding for a table key."
3292 (error "This key has no function outside tables"))
3294 (defun orgtbl-setup ()
3295 "Setup orgtbl keymaps."
3299 '([(meta shift left
)] org-table-delete-column
)
3300 '([(meta left
)] org-table-move-column-left
)
3301 '([(meta right
)] org-table-move-column-right
)
3302 '([(meta shift right
)] org-table-insert-column
)
3303 '([(meta shift up
)] org-table-kill-row
)
3304 '([(meta shift down
)] org-table-insert-row
)
3305 '([(meta up
)] org-table-move-row-up
)
3306 '([(meta down
)] org-table-move-row-down
)
3307 '("\C-c\C-w" org-table-cut-region
)
3308 '("\C-c\M-w" org-table-copy-region
)
3309 '("\C-c\C-y" org-table-paste-rectangle
)
3310 '("\C-c-" org-table-insert-hline
)
3311 '("\C-c}" org-table-toggle-coordinate-overlays
)
3312 '("\C-c{" org-table-toggle-formula-debugger
)
3313 '("\C-m" org-table-next-row
)
3314 '([(shift return
)] org-table-copy-down
)
3315 '("\C-c\C-q" org-table-wrap-region
)
3316 '("\C-c?" org-table-field-info
)
3317 '("\C-c " org-table-blank-field
)
3318 '("\C-c+" org-table-sum
)
3319 '("\C-c=" org-table-eval-formula
)
3320 '("\C-c'" org-table-edit-formulas
)
3321 '("\C-c`" org-table-edit-field
)
3322 '("\C-c*" org-table-recalculate
)
3323 '("\C-c|" org-table-create-or-convert-from-region
)
3324 '("\C-c^" org-table-sort-lines
)
3325 '([(control ?
#)] org-table-rotate-recalc-marks
)))
3327 (while (setq elt
(pop bindings
))
3328 (setq nfunc
(1+ nfunc
))
3329 (setq key
(org-key (car elt
))
3331 cmd
(orgtbl-make-binding fun nfunc key
))
3332 (org-defkey orgtbl-mode-map key cmd
))
3334 ;; Special treatment needed for TAB and RET
3335 (org-defkey orgtbl-mode-map
[(return)]
3336 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
3337 (org-defkey orgtbl-mode-map
"\C-m"
3338 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
3340 (org-defkey orgtbl-mode-map
[(tab)]
3341 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
3342 (org-defkey orgtbl-mode-map
"\C-i"
3343 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
3345 (org-defkey orgtbl-mode-map
[(shift tab
)]
3346 (orgtbl-make-binding 'org-table-previous-field
104
3347 [(shift tab
)] [(tab)] "\C-i"))
3349 (org-defkey orgtbl-mode-map
"\M-\C-m"
3350 (orgtbl-make-binding 'org-table-wrap-region
105
3351 "\M-\C-m" [(meta return
)]))
3352 (org-defkey orgtbl-mode-map
[(meta return
)]
3353 (orgtbl-make-binding 'org-table-wrap-region
106
3354 [(meta return
)] "\M-\C-m"))
3356 (org-defkey orgtbl-mode-map
"\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c
)
3357 (when orgtbl-optimized
3358 ;; If the user wants maximum table support, we need to hijack
3359 ;; some standard editing functions
3360 (org-remap orgtbl-mode-map
3361 'self-insert-command
'orgtbl-self-insert-command
3362 'delete-char
'org-delete-char
3363 'delete-backward-char
'org-delete-backward-char
)
3364 (org-defkey orgtbl-mode-map
"|" 'org-force-self-insert
))
3365 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map
"OrgTbl menu"
3367 ["Align" org-ctrl-c-ctrl-c
:active
(org-at-table-p) :keys
"C-c C-c"]
3368 ["Next Field" org-cycle
:active
(org-at-table-p) :keys
"TAB"]
3369 ["Previous Field" org-shifttab
:active
(org-at-table-p) :keys
"S-TAB"]
3370 ["Next Row" org-return
:active
(org-at-table-p) :keys
"RET"]
3372 ["Blank Field" org-table-blank-field
:active
(org-at-table-p) :keys
"C-c SPC"]
3373 ["Edit Field" org-table-edit-field
:active
(org-at-table-p) :keys
"C-c ` "]
3374 ["Copy Field from Above"
3375 org-table-copy-down
:active
(org-at-table-p) :keys
"S-RET"]
3378 ["Move Column Left" org-metaleft
:active
(org-at-table-p) :keys
"M-<left>"]
3379 ["Move Column Right" org-metaright
:active
(org-at-table-p) :keys
"M-<right>"]
3380 ["Delete Column" org-shiftmetaleft
:active
(org-at-table-p) :keys
"M-S-<left>"]
3381 ["Insert Column" org-shiftmetaright
:active
(org-at-table-p) :keys
"M-S-<right>"])
3383 ["Move Row Up" org-metaup
:active
(org-at-table-p) :keys
"M-<up>"]
3384 ["Move Row Down" org-metadown
:active
(org-at-table-p) :keys
"M-<down>"]
3385 ["Delete Row" org-shiftmetaup
:active
(org-at-table-p) :keys
"M-S-<up>"]
3386 ["Insert Row" org-shiftmetadown
:active
(org-at-table-p) :keys
"M-S-<down>"]
3387 ["Sort lines in region" org-table-sort-lines
:active
(org-at-table-p) :keys
"C-c ^"]
3389 ["Insert Hline" org-table-insert-hline
:active
(org-at-table-p) :keys
"C-c -"])
3391 ["Copy Rectangle" org-copy-special
:active
(org-at-table-p)]
3392 ["Cut Rectangle" org-cut-special
:active
(org-at-table-p)]
3393 ["Paste Rectangle" org-paste-special
:active
(org-at-table-p)]
3394 ["Fill Rectangle" org-table-wrap-region
:active
(org-at-table-p)])
3397 ["Insert table template" orgtbl-insert-radio-table
3398 (assq major-mode orgtbl-radio-table-templates
)]
3399 ["Comment/uncomment table" orgtbl-toggle-comment t
])
3401 ["Set Column Formula" org-table-eval-formula
:active
(org-at-table-p) :keys
"C-c ="]
3402 ["Set Field Formula" (org-table-eval-formula '(4)) :active
(org-at-table-p) :keys
"C-u C-c ="]
3403 ["Edit Formulas" org-table-edit-formulas
:active
(org-at-table-p) :keys
"C-c '"]
3404 ["Recalculate line" org-table-recalculate
:active
(org-at-table-p) :keys
"C-c *"]
3405 ["Recalculate all" (org-table-recalculate '(4)) :active
(org-at-table-p) :keys
"C-u C-c *"]
3406 ["Iterate all" (org-table-recalculate '(16)) :active
(org-at-table-p) :keys
"C-u C-u C-c *"]
3407 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks
:active
(org-at-table-p) :keys
"C-c #"]
3408 ["Sum Column/Rectangle" org-table-sum
3409 :active
(or (org-at-table-p) (org-region-active-p)) :keys
"C-c +"]
3410 ["Which Column?" org-table-current-column
:active
(org-at-table-p) :keys
"C-c ?"]
3412 org-table-toggle-formula-debugger
:active
(org-at-table-p)
3414 :style toggle
:selected org-table-formula-debug
]
3415 ["Show Col/Row Numbers"
3416 org-table-toggle-coordinate-overlays
:active
(org-at-table-p)
3418 :style toggle
:selected org-table-overlay-coordinates
]
3422 (defun orgtbl-ctrl-c-ctrl-c (arg)
3423 "If the cursor is inside a table, realign the table.
3424 It it is a table to be sent away to a receiver, do it.
3425 With prefix arg, also recompute table."
3427 (let ((pos (point)) action
)
3429 (beginning-of-line 1)
3430 (setq action
(cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
3431 ((looking-at "[ \t]*|") pos
)
3432 ((looking-at "#\\+TBLFM:") 'recalc
))))
3436 (org-table-maybe-eval-formula)
3438 (call-interactively 'org-table-recalculate
)
3439 (org-table-maybe-recalculate-line))
3440 (call-interactively 'org-table-align
)
3441 (orgtbl-send-table 'maybe
))
3442 ((eq action
'recalc
)
3444 (beginning-of-line 1)
3445 (skip-chars-backward " \r\n\t")
3446 (if (org-at-table-p)
3447 (org-call-with-arg 'org-table-recalculate t
))))
3448 (t (let (orgtbl-mode)
3449 (call-interactively (key-binding "\C-c\C-c")))))))
3451 (defun orgtbl-tab (arg)
3452 "Justification and field motion for `orgtbl-mode'."
3454 (if arg
(org-table-edit-field t
)
3455 (org-table-justify-field-maybe)
3456 (org-table-next-field)))
3458 (defun orgtbl-ret ()
3459 "Justification and field motion for `orgtbl-mode'."
3461 (org-table-justify-field-maybe)
3462 (org-table-next-row))
3464 (defun orgtbl-self-insert-command (N)
3465 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
3466 If the cursor is in a table looking at whitespace, the whitespace is
3467 overwritten, and the table is not marked as requiring realignment."
3469 (if (and (org-at-table-p)
3471 (and org-table-auto-blank-field
3472 (member last-command
3473 '(orgtbl-hijacker-command-100
3474 orgtbl-hijacker-command-101
3475 orgtbl-hijacker-command-102
3476 orgtbl-hijacker-command-103
3477 orgtbl-hijacker-command-104
3478 orgtbl-hijacker-command-105
))
3479 (org-table-blank-field))
3482 (looking-at "[^|\n]* +|"))
3483 (let (org-table-may-need-update)
3484 (goto-char (1- (match-end 0)))
3485 (delete-backward-char 1)
3486 (goto-char (match-beginning 0))
3487 (self-insert-command N
))
3488 (setq org-table-may-need-update t
)
3490 (call-interactively (key-binding (vector last-input-event
))))))
3492 (defvar orgtbl-exp-regexp
"^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
3493 "Regular expression matching exponentials as produced by calc.")
3495 (defun orgtbl-export (table target
)
3497 (let ((func (intern (concat "orgtbl-to-" (symbol-name target
))))
3498 (lines (org-split-string table
"[ \t]*\n[ \t]*"))
3499 org-table-last-alignment org-table-last-column-widths
3501 (if (not (fboundp func
))
3502 (error "Cannot export orgtbl table to %s" target
))
3503 (setq lines
(org-table-clean-before-export lines
))
3507 (if (string-match org-table-hline-regexp x
)
3509 (org-split-string (org-trim x
) "\\s-*|\\s-*")))
3511 (setq maxcol
(apply 'max
(mapcar (lambda (x) (if (listp x
) (length x
) 0))
3513 (loop for i from
(1- maxcol
) downto
0 do
3514 (setq column
(mapcar (lambda (x) (if (listp x
) (nth i x
) nil
)) table
))
3515 (setq column
(delq nil column
))
3516 (push (apply 'max
(mapcar 'string-width column
)) org-table-last-column-widths
)
3517 (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
))
3518 (funcall func table nil
)))
3520 (defun orgtbl-gather-send-defs ()
3521 "Gathers a plist of :name, :transform, :params for each destination before
3524 (goto-char (org-table-begin))
3526 (beginning-of-line 0)
3527 (while (looking-at "#\\+ORGTBL[: \t][ \t]*SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
3528 (let ((name (org-no-properties (match-string 1)))
3529 (transform (intern (match-string 2)))
3530 (params (if (match-end 3)
3531 (read (concat "(" (match-string 3) ")")))))
3532 (push (list :name name
:transform transform
:params params
)
3534 (beginning-of-line 0)))
3537 (defun orgtbl-send-replace-tbl (name txt
)
3538 "Find and replace table NAME with TXT."
3540 (goto-char (point-min))
3541 (unless (re-search-forward
3542 (concat "BEGIN RECEIVE ORGTBL +" name
"\\([ \t]\\|$\\)") nil t
)
3543 (error "Don't know where to insert translated table"))
3544 (goto-char (match-beginning 0))
3545 (beginning-of-line 2)
3547 (let ((beg (point)))
3548 (unless (re-search-forward
3549 (concat "END RECEIVE ORGTBL +" name
) nil t
)
3550 (error "Cannot find end of insertion region"))
3551 (beginning-of-line 1)
3552 (delete-region beg
(point))))
3555 (defun org-table-to-lisp (&optional txt
)
3556 "Convert the table at point to a Lisp structure.
3557 The structure will be a list. Each item is either the symbol `hline'
3558 for a horizontal separator line, or a list of field values as strings.
3559 The table is taken from the parameter TXT, or from the buffer at point."
3561 (unless (org-at-table-p)
3562 (error "No table at point")))
3564 (buffer-substring-no-properties (org-table-begin)
3566 (lines (org-split-string txt
"[ \t]*\n[ \t]*")))
3570 (if (string-match org-table-hline-regexp x
)
3572 (org-split-string (org-trim x
) "\\s-*|\\s-*")))
3575 (defun orgtbl-send-table (&optional maybe
)
3576 "Send a tranformed version of this table to the receiver position.
3577 With argument MAYBE, fail quietly if no transformation is defined for
3581 (unless (org-at-table-p) (error "Not at a table"))
3582 ;; when non-interactive, we assume align has just happened.
3583 (when (interactive-p) (org-table-align))
3584 (let ((dests (orgtbl-gather-send-defs))
3585 (txt (buffer-substring-no-properties (org-table-begin)
3588 (unless dests
(if maybe
(throw 'exit nil
)
3589 (error "Don't know how to transform this table.")))
3590 (dolist (dest dests
)
3591 (let* ((name (plist-get dest
:name
))
3592 (transform (plist-get dest
:transform
))
3593 (params (plist-get dest
:params
))
3594 (skip (plist-get params
:skip
))
3595 (skipcols (plist-get params
:skipcols
))
3597 (lines (org-table-clean-before-export
3599 (org-split-string txt
"[ \t]*\n[ \t]*"))))
3600 (i0 (if org-table-clean-did-remove-column
2 1))
3603 (if (string-match org-table-hline-regexp x
)
3605 (org-remove-by-index
3606 (org-split-string (org-trim x
) "\\s-*|\\s-*")
3609 (fun (if (= i0
2) 'cdr
'identity
))
3610 (org-table-last-alignment
3611 (org-remove-by-index (funcall fun org-table-last-alignment
)
3613 (org-table-last-column-widths
3614 (org-remove-by-index (funcall fun org-table-last-column-widths
)
3616 (txt (if (fboundp transform
)
3617 (funcall transform table params
)
3618 (error "No such transformation function %s" transform
))))
3619 (orgtbl-send-replace-tbl name txt
))
3620 (setq ntbl
(1+ ntbl
)))
3621 (message "Table converted and installed at %d receiver location%s"
3622 ntbl
(if (> ntbl
1) "s" "")))))
3624 (defun org-remove-by-index (list indices
&optional i0
)
3625 "Remove the elements in LIST with indices in INDICES.
3626 First element has index 0, or I0 if given."
3629 (if (integerp indices
) (setq indices
(list indices
)))
3630 (setq i0
(1- (or i0
0)))
3631 (delq :rm
(mapcar (lambda (x)
3633 (if (memq i0 indices
) :rm x
))
3636 (defun orgtbl-toggle-comment ()
3637 "Comment or uncomment the orgtbl at point."
3639 (let* ((re1 (concat "^" (regexp-quote comment-start
) orgtbl-line-start-regexp
))
3640 (re2 (concat "^" orgtbl-line-start-regexp
))
3641 (commented (save-excursion (beginning-of-line 1)
3642 (cond ((looking-at re1
) t
)
3643 ((looking-at re2
) nil
)
3644 (t (error "Not at an org table")))))
3645 (re (if commented re1 re2
))
3648 (beginning-of-line 1)
3649 (while (looking-at re
) (beginning-of-line 0))
3650 (beginning-of-line 2)
3652 (while (looking-at re
) (beginning-of-line 2))
3654 (comment-region beg end
(if commented
'(4) nil
))))
3656 (defun orgtbl-insert-radio-table ()
3657 "Insert a radio table template appropriate for this major mode."
3659 (let* ((e (assq major-mode orgtbl-radio-table-templates
))
3662 (unless e
(error "No radio table setup defined for %s" major-mode
))
3663 (setq name
(read-string "Table name: "))
3664 (while (string-match "%n" txt
)
3665 (setq txt
(replace-match name t t txt
)))
3666 (or (bolp) (insert "\n"))
3671 ;; Dynamically bound input and output for table formatting.
3672 (defvar *orgtbl-table
* nil
3673 "Carries the current table through formatting routines.")
3674 (defvar *orgtbl-rtn
* nil
3675 "Formatting routines push the output lines here.")
3676 ;; Formatting parameters for the current table section.
3677 (defvar *orgtbl-hline
* nil
"Text used for horizontal lines")
3678 (defvar *orgtbl-sep
* nil
"Text used as a column separator")
3679 (defvar *orgtbl-default-fmt
* nil
"Default format for each entry")
3680 (defvar *orgtbl-fmt
* nil
"Format for each entry")
3681 (defvar *orgtbl-efmt
* nil
"Format for numbers")
3682 (defvar *orgtbl-lfmt
* nil
"Format for an entire line, overrides fmt")
3683 (defvar *orgtbl-llfmt
* nil
"Specializes lfmt for the last row")
3684 (defvar *orgtbl-lstart
* nil
"Text starting a row")
3685 (defvar *orgtbl-llstart
* nil
"Specializes lstart for the last row")
3686 (defvar *orgtbl-lend
* nil
"Text ending a row")
3687 (defvar *orgtbl-llend
* nil
"Specializes lend for the last row")
3689 (defsubst orgtbl-get-fmt
(fmt i
)
3690 "Retrieve the format from FMT corresponding to the Ith column."
3691 (if (and (not (functionp fmt
)) (consp fmt
))
3695 (defsubst orgtbl-apply-fmt
(fmt &rest args
)
3696 "Apply format FMT to the arguments. NIL FMTs return the first argument."
3697 (cond ((functionp fmt
) (apply fmt args
))
3698 (fmt (apply 'format fmt args
))
3702 (defsubst orgtbl-eval-str
(str)
3703 "If STR is a function, evaluate it with no arguments."
3708 (defun orgtbl-format-line (line)
3709 "Format LINE as a table row."
3710 (if (eq line
'hline
) (if *orgtbl-hline
* (push *orgtbl-hline
* *orgtbl-rtn
*))
3716 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt
* i
))
3717 (f (if (and efmt
(string-match orgtbl-exp-regexp f
))
3718 (orgtbl-apply-fmt efmt
(match-string 1 f
)
3721 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt
* i
)
3722 *orgtbl-default-fmt
*)
3725 (push (if *orgtbl-lfmt
*
3726 (orgtbl-apply-fmt *orgtbl-lfmt
* line
)
3727 (concat (orgtbl-eval-str *orgtbl-lstart
*)
3728 (mapconcat 'identity line
*orgtbl-sep
*)
3729 (orgtbl-eval-str *orgtbl-lend
*)))
3732 (defun orgtbl-format-section (section-stopper)
3733 "Format lines until the first occurrence of SECTION-STOPPER."
3736 (while (not (eq (car *orgtbl-table
*) section-stopper
))
3737 (if prevline
(orgtbl-format-line prevline
))
3738 (setq prevline
(pop *orgtbl-table
*)))
3739 (if prevline
(let ((*orgtbl-lstart
* *orgtbl-llstart
*)
3740 (*orgtbl-lend
* *orgtbl-llend
*)
3741 (*orgtbl-lfmt
* *orgtbl-llfmt
*))
3742 (orgtbl-format-line prevline
))))))
3744 (defun orgtbl-to-generic (table params
)
3745 "Convert the orgtbl-mode TABLE to some other format.
3746 This generic routine can be used for many standard cases.
3747 TABLE is a list, each entry either the symbol `hline' for a horizontal
3748 separator line, or a list of fields for that line.
3749 PARAMS is a property list of parameters that can influence the conversion.
3750 For the generic converter, some parameters are obligatory: You need to
3751 specify either :lfmt, or all of (:lstart :lend :sep).
3753 Valid parameters are
3755 :splice When set to t, return only table body lines, don't wrap
3756 them into :tstart and :tend. Default is nil. When :splice
3757 is non-nil, this also means that the exporter should not look
3758 for and interpret header and footer sections.
3760 :hline String to be inserted on horizontal separation lines.
3761 May be nil to ignore hlines.
3763 :sep Separator between two fields
3764 :remove-nil-lines Do not include lines that evaluate to nil.
3767 Each in the following group may be either a string or a function
3768 of no arguments returning a string:
3769 :tstart String to start the table. Ignored when :splice is t.
3770 :tend String to end the table. Ignored when :splice is t.
3771 :lstart String to start a new table line.
3772 :llstart String to start the last table line, defaults to :lstart.
3773 :lend String to end a table line
3774 :llend String to end the last table line, defaults to :lend.
3776 Each in the following group may be a string, a function of one
3777 argument (the field or line) returning a string, or a plist
3778 mapping columns to either of the above:
3779 :lfmt Format for entire line, with enough %s to capture all fields.
3780 If this is present, :lstart, :lend, and :sep are ignored.
3781 :llfmt Format for the entire last line, defaults to :lfmt.
3782 :fmt A format to be used to wrap the field, should contain
3783 %s for the original field value. For example, to wrap
3784 everything in dollars, you could use :fmt \"$%s$\".
3785 This may also be a property list with column numbers and
3786 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
3788 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
3789 Same as above, specific for the header lines in the table.
3790 All lines before the first hline are treated as header.
3791 If any of these is not present, the data line value is used.
3793 This may be either a string or a function of two arguments:
3794 :efmt Use this format to print numbers with exponentials.
3795 The format should have %s twice for inserting mantissa
3796 and exponent, for example \"%s\\\\times10^{%s}\". This
3797 may also be a property list with column numbers and
3798 formats. :fmt will still be applied after :efmt.
3800 In addition to this, the parameters :skip and :skipcols are always handled
3801 directly by `orgtbl-send-table'. See manual."
3804 (let* ((splicep (plist-get params
:splice
))
3805 (hline (plist-get params
:hline
))
3806 (remove-nil-linesp (plist-get params
:remove-nil-lines
))
3807 (*orgtbl-hline
* hline
)
3808 (*orgtbl-table
* table
)
3809 (*orgtbl-sep
* (plist-get params
:sep
))
3810 (*orgtbl-efmt
* (plist-get params
:efmt
))
3811 (*orgtbl-lstart
* (plist-get params
:lstart
))
3812 (*orgtbl-llstart
* (or (plist-get params
:llstart
) *orgtbl-lstart
*))
3813 (*orgtbl-lend
* (plist-get params
:lend
))
3814 (*orgtbl-llend
* (or (plist-get params
:llend
) *orgtbl-lend
*))
3815 (*orgtbl-lfmt
* (plist-get params
:lfmt
))
3816 (*orgtbl-llfmt
* (or (plist-get params
:llfmt
) *orgtbl-lfmt
*))
3817 (*orgtbl-fmt
* (plist-get params
:fmt
))
3822 (when (plist-member params
:tstart
)
3823 (let ((tstart (orgtbl-eval-str (plist-get params
:tstart
))))
3824 (if tstart
(push tstart
*orgtbl-rtn
*)))))
3826 ;; Do we have a heading section? If so, format it and handle the
3828 (if (and (not splicep
) (listp (car *orgtbl-table
*))
3829 (memq 'hline
*orgtbl-table
*))
3831 (let* ((*orgtbl-lstart
* (or (plist-get params
:hlstart
)
3833 (*orgtbl-llstart
* (or (plist-get params
:hllstart
)
3835 (*orgtbl-lend
* (or (plist-get params
:hlend
) *orgtbl-lend
*))
3836 (*orgtbl-llend
* (or (plist-get params
:hllend
)
3837 (plist-get params
:hlend
) *orgtbl-llend
*))
3838 (*orgtbl-lfmt
* (or (plist-get params
:hlfmt
) *orgtbl-lfmt
*))
3839 (*orgtbl-llfmt
* (or (plist-get params
:hllfmt
)
3840 (plist-get params
:hlfmt
) *orgtbl-llfmt
*))
3841 (*orgtbl-sep
* (or (plist-get params
:hlsep
) *orgtbl-sep
*))
3842 (*orgtbl-fmt
* (or (plist-get params
:hfmt
) *orgtbl-fmt
*)))
3843 (orgtbl-format-section 'hline
))
3844 (if hline
(push hline
*orgtbl-rtn
*))
3845 (pop *orgtbl-table
*)))
3847 ;; Now format the main section.
3848 (orgtbl-format-section nil
)
3851 (when (plist-member params
:tend
)
3852 (let ((tend (orgtbl-eval-str (plist-get params
:tend
))))
3853 (if tend
(push tend
*orgtbl-rtn
*)))))
3855 (mapconcat 'identity
(nreverse (if remove-nil-linesp
3856 (remq nil
*orgtbl-rtn
*)
3857 *orgtbl-rtn
*)) "\n")))
3859 (defun orgtbl-to-tsv (table params
)
3860 "Convert the orgtbl-mode table to TAB separated material."
3861 (orgtbl-to-generic table
(org-combine-plists '(:sep
"\t") params
)))
3862 (defun orgtbl-to-csv (table params
)
3863 "Convert the orgtbl-mode table to CSV material.
3864 This does take care of the proper quoting of fields with comma or quotes."
3865 (orgtbl-to-generic table
(org-combine-plists
3866 '(:sep
"," :fmt org-quote-csv-field
)
3869 (defun orgtbl-to-latex (table params
)
3870 "Convert the orgtbl-mode TABLE to LaTeX.
3871 TABLE is a list, each entry either the symbol `hline' for a horizontal
3872 separator line, or a list of fields for that line.
3873 PARAMS is a property list of parameters that can influence the conversion.
3874 Supports all parameters from `orgtbl-to-generic'. Most important for
3877 :splice When set to t, return only table body lines, don't wrap
3878 them into a tabular environment. Default is nil.
3880 :fmt A format to be used to wrap the field, should contain %s for the
3881 original field value. For example, to wrap everything in dollars,
3882 use :fmt \"$%s$\". This may also be a property list with column
3883 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
3884 The format may also be a function that formats its one argument.
3886 :efmt Format for transforming numbers with exponentials. The format
3887 should have %s twice for inserting mantissa and exponent, for
3888 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
3889 This may also be a property list with column numbers and formats.
3890 The format may also be a function that formats its two arguments.
3892 :llend If you find too much space below the last line of a table,
3893 pass a value of \"\" for :llend to suppress the final \\\\.
3895 The general parameters :skip and :skipcols have already been applied when
3896 this function is called."
3897 (let* ((alignment (mapconcat (lambda (x) (if x
"r" "l"))
3898 org-table-last-alignment
""))
3901 :tstart
(concat "\\begin{tabular}{" alignment
"}")
3902 :tend
"\\end{tabular}"
3903 :lstart
"" :lend
" \\\\" :sep
" & "
3904 :efmt
"%s\\,(%s)" :hline
"\\hline")))
3905 (orgtbl-to-generic table
(org-combine-plists params2 params
))))
3907 (defun orgtbl-to-html (table params
)
3908 "Convert the orgtbl-mode TABLE to LaTeX.
3909 TABLE is a list, each entry either the symbol `hline' for a horizontal
3910 separator line, or a list of fields for that line.
3911 PARAMS is a property list of parameters that can influence the conversion.
3912 Currently this function recognizes the following parameters:
3914 :splice When set to t, return only table body lines, don't wrap
3915 them into a <table> environment. Default is nil.
3917 The general parameters :skip and :skipcols have already been applied when
3918 this function is called. The function does *not* use `orgtbl-to-generic',
3919 so you cannot specify parameters for it."
3920 (let* ((splicep (plist-get params
:splice
))
3922 ;; Just call the formatter we already have
3923 ;; We need to make text lines for it, so put the fields back together.
3924 (setq html
(org-format-org-table-html
3929 (concat "| " (mapconcat 'identity x
" | ") " |")))
3932 (if (string-match "\n+\\'" html
)
3933 (setq html
(replace-match "" t t html
)))
3936 (defun orgtbl-to-texinfo (table params
)
3937 "Convert the orgtbl-mode TABLE to TeXInfo.
3938 TABLE is a list, each entry either the symbol `hline' for a horizontal
3939 separator line, or a list of fields for that line.
3940 PARAMS is a property list of parameters that can influence the conversion.
3941 Supports all parameters from `orgtbl-to-generic'. Most important for
3944 :splice nil/t When set to t, return only table body lines, don't wrap
3945 them into a multitable environment. Default is nil.
3947 :fmt fmt A format to be used to wrap the field, should contain
3948 %s for the original field value. For example, to wrap
3949 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
3950 This may also be a property list with column numbers and
3951 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
3952 Each format also may be a function that formats its one
3955 :cf \"f1 f2..\" The column fractions for the table. By default these
3956 are computed automatically from the width of the columns
3959 The general parameters :skip and :skipcols have already been applied when
3960 this function is called."
3961 (let* ((total (float (apply '+ org-table-last-column-widths
)))
3962 (colfrac (or (plist-get params
:cf
)
3964 (lambda (x) (format "%.3f" (/ (float x
) total
)))
3965 org-table-last-column-widths
" ")))
3968 :tstart
(concat "@multitable @columnfractions " colfrac
)
3969 :tend
"@end multitable"
3970 :lstart
"@item " :lend
"" :sep
" @tab "
3971 :hlstart
"@headitem ")))
3972 (orgtbl-to-generic table
(org-combine-plists params2 params
))))
3974 (defun orgtbl-to-orgtbl (table params
)
3975 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
3976 Useful when slicing one table into many. The :hline, :sep,
3977 :lstart, and :lend provide orgtbl framing. The default nil :tstart
3978 and :tend suppress strings without splicing; they can be set to
3979 provide ORGTBL directives for the generated table."
3982 :tstart nil
:tend nil
3987 (params (org-combine-plists params2 params
)))
3988 (orgtbl-to-generic table params
)))
3990 (provide 'org-table
)
3992 ;; arch-tag: 4d21cfdd-0268-440a-84b0-09237a0fe0ef
3994 ;;; org-table.el ends here