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 spreadsheet 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
46 (defvar org-export-html-table-tag
) ; defined in org-exp.el
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 references 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 (defcustom org-table-error-on-row-ref-crossing-hline t
248 "Non-nil means, a relative row reference that tries to cross a hline errors.
249 When nil, the reference will silently be to the field just next to the hline.
250 Coming from below, it will be the field below the hline, coming from
251 above, it will be the field above the hline."
255 (defgroup org-table-import-export nil
256 "Options concerning table import and export in Org-mode."
257 :tag
"Org Table Import Export"
260 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
261 "Default export parameters for org-table-export. These can be
262 overridden on for a specific table by setting the TABLE_EXPORT_FORMAT
263 property. See the manual section on orgtbl radio tables for the different
264 export transformations and available parameters."
265 :group
'org-table-import-export
268 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
269 "Detects a table line marked for automatic recalculation.")
270 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
271 "Detects a table line marked for automatic recalculation.")
272 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
273 "Detects a table line marked for automatic recalculation.")
274 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
275 "Searching from within a table (any type) this finds the first line
277 (defvar org-table-last-highlighted-reference nil
)
278 (defvar org-table-formula-history nil
)
280 (defvar org-table-column-names nil
281 "Alist with column names, derived from the `!' line.")
282 (defvar org-table-column-name-regexp nil
283 "Regular expression matching the current column names.")
284 (defvar org-table-local-parameters nil
285 "Alist with parameter names, derived from the `$' line.")
286 (defvar org-table-named-field-locations nil
287 "Alist with locations of named fields.")
289 (defvar org-table-current-line-types nil
290 "Table row types, non-nil only for the duration of a comand.")
291 (defvar org-table-current-begin-line nil
292 "Table begin line, non-nil only for the duration of a comand.")
293 (defvar org-table-current-begin-pos nil
294 "Table begin position, non-nil only for the duration of a comand.")
295 (defvar org-table-dlines nil
296 "Vector of data line line numbers in the current table.")
297 (defvar org-table-hlines nil
298 "Vector of hline line numbers in the current table.")
300 (defconst org-table-range-regexp
301 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
303 "Regular expression for matching ranges in formulas.")
305 (defconst org-table-range-regexp2
307 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
309 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
310 "Match a range for reference display.")
312 (defconst org-table-translate-regexp
313 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
314 "Match a reference that needs translation, for reference display.")
316 (defun org-table-create-with-table.el
()
317 "Use the table.el package to insert a new table.
318 If there is already a table at point, convert between Org-mode tables
319 and table.el tables."
324 (if (y-or-n-p "Convert table to Org-mode table? ")
325 (org-table-convert)))
327 (if (y-or-n-p "Convert table to table.el table? ")
328 (org-table-convert)))
329 (t (call-interactively 'table-insert
))))
331 (defun org-table-create-or-convert-from-region (arg)
332 "Convert region to table, or create an empty table.
333 If there is an active region, convert it to a table, using the function
334 `org-table-convert-region'. See the documentation of that function
335 to learn how the prefix argument is interpreted to determine the field
337 If there is no such region, create an empty table with `org-table-create'."
339 (if (org-region-active-p)
340 (org-table-convert-region (region-beginning) (region-end) arg
)
341 (org-table-create arg
)))
343 (defun org-table-create (&optional size
)
344 "Query for a size and insert a table skeleton.
345 SIZE is a string Columns x Rows like for example \"3x2\"."
348 (setq size
(read-string
349 (concat "Table size Columns x Rows [e.g. "
350 org-table-default-size
"]: ")
351 "" nil org-table-default-size
)))
354 (indent (make-string (current-column) ?\
))
355 (split (org-split-string size
" *x *"))
356 (rows (string-to-number (nth 1 split
)))
357 (columns (string-to-number (car split
)))
358 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
360 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
361 (point-at-bol) (point)))
362 (beginning-of-line 1)
364 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
365 (dotimes (i rows
) (insert line
))
368 ;; Insert a hline after the first row.
375 (defun org-table-convert-region (beg0 end0
&optional separator
)
376 "Convert region to a table.
377 The region goes from BEG0 to END0, but these borders will be moved
378 slightly, to make sure a beginning of line in the first line is included.
380 SEPARATOR specifies the field separator in the lines. It can have the
383 '(4) Use the comma as a field separator
384 '(16) Use a TAB as field separator
385 integer When a number, use that many spaces as field separator
386 nil When nil, the command tries to be smart and figure out the
387 separator in the following way:
388 - when each line contains a TAB, assume TAB-separated material
389 - when each line contains a comma, assume CSV material
390 - else, assume one or more SPACE characters as separator."
392 (let* ((beg (min beg0 end0
))
393 (end (max beg0 end0
))
396 (beginning-of-line 1)
397 (setq beg
(move-marker (make-marker) (point)))
399 (if (bolp) (backward-char 1) (end-of-line 1))
400 (setq end
(move-marker (make-marker) (point)))
401 ;; Get the right field separator
406 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
407 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
410 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
411 ((equal separator
'(16)) "^\\|\t")
412 ((integerp separator
)
413 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
))
414 (t (error "This should not happen"))))
416 (while (re-search-forward re end t
)
417 (replace-match "| " t t
))
422 (defun org-table-import (file arg
)
423 "Import FILE as a table.
424 The file is assumed to be tab-separated. Such files can be produced by most
425 spreadsheet and database applications. If no tabs (at least one per line)
426 are found, lines will be split on whitespace into fields."
428 (or (bolp) (newline))
431 (insert-file-contents file
)
432 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
435 (defvar org-table-last-alignment
)
436 (defvar org-table-last-column-widths
)
437 (defun org-table-export (&optional file format
)
438 "Export table to a file, with configurable format.
439 Such a file can be imported into a spreadsheet program like Excel.
440 FILE can be the output file name. If not given, it will be taken from
441 a TABLE_EXPORT_FILE property in the current entry or higher up in the
442 hierarchy, or the user will be prompted for a file name.
443 FORMAT can be an export format, of the same kind as it used when
444 orgtbl-mode sends a table in a different format. The default format can
445 be found in the variable `org-table-export-default-format', but the function
446 first checks if there is an export format specified in a TABLE_EXPORT_FORMAT
447 property, locally or anywhere up in the hierarchy."
449 (unless (org-at-table-p)
450 (error "No table at point"))
452 (org-table-align) ;; make sure we have everything we need
453 (let* ((beg (org-table-begin))
454 (end (org-table-end))
455 (txt (buffer-substring-no-properties beg end
))
458 (org-entry-get beg
"TABLE_EXPORT_FILE" t
)
462 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)
466 (setq file
(read-file-name "Export table to: "))
467 (unless (or (not (file-exists-p file
))
468 (y-or-n-p (format "Overwrite file %s? " file
)))
470 (if (file-directory-p file
)
471 (error "This is a directory path, not a file"))
472 (if (equal (file-truename file
)
473 (file-truename (buffer-file-name)))
474 (error "Please specify a file name that is different from current"))
476 (setq deffmt-readable org-table-export-default-format
)
477 (while (string-match "\t" deffmt-readable
)
478 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
479 (while (string-match "\n" deffmt-readable
)
480 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
481 (setq format
(org-completing-read
483 '("orgtbl-to-tsv" "orgtbl-to-csv"
484 "orgtbl-to-latex" "orgtbl-to-html"
485 "orgtbl-to-generic" "orgtbl-to-texinfo"
486 "orgtbl-to-orgtbl") nil nil
488 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
489 (let* ((transform (intern (match-string 1 format
)))
490 (params (if (match-end 2)
491 (read (concat "(" (match-string 2 format
) ")"))))
492 (skip (plist-get params
:skip
))
493 (skipcols (plist-get params
:skipcols
))
494 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
495 (lines (org-table-clean-before-export lines
))
496 (i0 (if org-table-clean-did-remove-column
2 1))
499 (if (string-match org-table-hline-regexp x
)
502 (org-split-string (org-trim x
) "\\s-*|\\s-*")
505 (fun (if (= i0
2) 'cdr
'identity
))
506 (org-table-last-alignment
507 (org-remove-by-index (funcall fun org-table-last-alignment
)
509 (org-table-last-column-widths
510 (org-remove-by-index (funcall fun org-table-last-column-widths
)
513 (unless (fboundp transform
)
514 (error "No such transformation function %s" transform
))
515 (setq txt
(funcall transform table params
))
517 (with-current-buffer (find-file-noselect file
)
518 (setq buf
(current-buffer))
524 (message "Export done."))
525 (error "TABLE_EXPORT_FORMAT invalid"))))
527 (defvar org-table-aligned-begin-marker
(make-marker)
528 "Marker at the beginning of the table last aligned.
529 Used to check if cursor still is in that table, to minimize realignment.")
530 (defvar org-table-aligned-end-marker
(make-marker)
531 "Marker at the end of the table last aligned.
532 Used to check if cursor still is in that table, to minimize realignment.")
533 (defvar org-table-last-alignment nil
534 "List of flags for flushright alignment, from the last re-alignment.
535 This is being used to correctly align a single field after TAB or RET.")
536 (defvar org-table-last-column-widths nil
537 "List of max width of fields in each column.
538 This is being used to correctly align a single field after TAB or RET.")
539 (defvar org-table-formula-debug nil
540 "Non-nil means, debug table formulas.
541 When nil, simply write \"#ERROR\" in corrupted fields.")
542 (make-variable-buffer-local 'org-table-formula-debug
)
543 (defvar org-table-overlay-coordinates nil
544 "Overlay coordinates after each align of a table.")
545 (make-variable-buffer-local 'org-table-overlay-coordinates
)
547 (defvar org-last-recalc-line nil
)
548 (defconst org-narrow-column-arrow
"=>"
549 "Used as display property in narrowed table columns.")
551 (defun org-table-align ()
552 "Align the table at point by aligning all vertical bars."
556 (beg (org-table-begin))
557 (end (org-table-end))
558 ;; Current cursor position
559 (linepos (org-current-line))
560 (colpos (org-table-current-column))
561 (winstart (window-start))
562 (winstartline (org-current-line (min winstart
(1- (point-max)))))
563 lines
(new "") lengths l typenums ty fields maxfields i
571 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
573 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
574 emptystrings links dates emph narrow fmax f1 len c e
)
576 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
577 ;; Check if we have links or dates
579 (setq links
(re-search-forward org-bracket-link-regexp end t
))
581 (setq emph
(and org-hide-emphasis-markers
582 (re-search-forward org-emph-re end t
)))
584 (setq dates
(and org-display-custom-times
585 (re-search-forward org-ts-regexp-both end t
)))
586 ;; Make sure the link properties are right
587 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
588 ;; Make sure the date properties are right
589 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
590 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
592 ;; Check if we are narrowing any columns
594 (setq narrow
(and org-format-transports-properties-p
595 (re-search-forward "<[0-9]+>" end t
)))
597 (setq lines
(org-split-string
598 (buffer-substring beg end
) "\n"))
599 ;; Store the indentation of the first line
600 (if (string-match "^ *" (car lines
))
601 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
602 ;; Mark the hlines by setting the corresponding element to nil
603 ;; At the same time, we remove trailing space.
604 (setq lines
(mapcar (lambda (l)
605 (if (string-match "^ *|-" l
)
607 (if (string-match "[ \t]+$" l
)
608 (substring l
0 (match-beginning 0))
611 ;; Get the data fields by splitting the lines.
614 (org-split-string l
" *| *"))
615 (delq nil
(copy-sequence lines
))))
616 ;; How many fields in the longest line?
618 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
620 (kill-region beg end
)
621 (org-table-create org-table-default-size
)
622 (error "Empty table - created default table")))
623 ;; A list of empty strings to fill any short rows on output
624 (setq emptystrings
(make-list maxfields
""))
625 ;; Check for special formatting.
627 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
628 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
629 ;; Check if there is an explicit width specified
631 (setq c column fmax nil
)
634 (if (and (stringp e
) (string-match "^<\\([0-9]+\\)>$" e
))
635 (setq fmax
(string-to-number (match-string 1 e
)) c nil
)))
636 ;; Find fields that are wider than fmax, and shorten them
638 (loop for xx in column do
639 (when (and (stringp xx
)
640 (> (org-string-width xx
) fmax
))
641 (org-add-props xx nil
643 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
644 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
646 (error "Cannot narrow field starting with wide link \"%s\""
647 (match-string 0 xx
)))
648 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
649 (add-text-properties (- f1
2) f1
650 (list 'display org-narrow-column-arrow
)
652 ;; Get the maximum width for each column
653 (push (apply 'max
1 (mapcar 'org-string-width column
)) lengths
)
654 ;; Get the fraction of numbers, to decide about alignment of the column
655 (setq cnt
0 frac
0.0)
656 (loop for x in column do
659 (setq frac
( / (+ (* frac cnt
)
660 (if (string-match org-table-number-regexp x
) 1 0))
661 (setq cnt
(1+ cnt
))))))
662 (push (>= frac org-table-number-fraction
) typenums
))
663 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
665 ;; Store the alignment of this table, for later editing of single fields
666 (setq org-table-last-alignment typenums
667 org-table-last-column-widths lengths
)
669 ;; With invisible characters, `format' does not get the field width right
670 ;; So we need to make these fields wide by hand.
671 (when (or links emph
)
672 (loop for i from
0 upto
(1- maxfields
) do
673 (setq len
(nth i lengths
))
674 (loop for j from
0 upto
(1- (length fields
)) do
675 (setq c
(nthcdr i
(car (nthcdr j fields
))))
676 (if (and (stringp (car c
))
677 (text-property-any 0 (length (car c
)) 'invisible
'org-link
(car c
))
678 ; (string-match org-bracket-link-regexp (car c))
679 (< (org-string-width (car c
)) len
))
680 (setcar c
(concat (car c
) (make-string (- len
(org-string-width (car c
))) ?\
)))))))
682 ;; Compute the formats needed for output of the table
683 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
684 (while (setq l
(pop lengths
))
685 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
686 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
687 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
688 (setq rfmt
(concat rfmt
"\n")
689 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
693 (if l
(apply 'format rfmt
694 (append (pop fields
) emptystrings
))
697 ;; Replace the old one
698 (delete-region beg end
)
699 (move-marker end nil
)
700 (move-marker org-table-aligned-begin-marker
(point))
702 (move-marker org-table-aligned-end-marker
(point))
703 (when (and orgtbl-mode
(not (org-mode-p)))
704 (goto-char org-table-aligned-begin-marker
)
705 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
706 ;; Try to move to the old location
707 (goto-line winstartline
)
708 (setq winstart
(point-at-bol))
710 (set-window-start (selected-window) winstart
'noforce
)
711 (org-table-goto-column colpos
)
712 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
713 (setq org-table-may-need-update nil
)
724 (defun org-table-begin (&optional table-type
)
725 "Find the beginning of the table and return its position.
726 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
728 (if (not (re-search-backward
729 (if table-type org-table-any-border-regexp
730 org-table-border-regexp
)
732 (progn (goto-char (point-min)) (point))
733 (goto-char (match-beginning 0))
734 (beginning-of-line 2)
737 (defun org-table-end (&optional table-type
)
738 "Find the end of the table and return its position.
739 With argument TABLE-TYPE, go to the end of a table.el-type table."
741 (if (not (re-search-forward
742 (if table-type org-table-any-border-regexp
743 org-table-border-regexp
)
745 (goto-char (point-max))
746 (goto-char (match-beginning 0)))
749 (defun org-table-justify-field-maybe (&optional new
)
750 "Justify the current field, text to left, number to right.
751 Optional argument NEW may specify text to replace the current field content."
753 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
754 ((org-at-table-hline-p))
756 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
758 (< (point) org-table-aligned-begin-marker
)
759 (>= (point) org-table-aligned-end-marker
)))
760 ;; This is not the same table, force a full re-align
761 (setq org-table-may-need-update t
))
762 (t ;; realign the current field, based on previous full realign
763 (let* ((pos (point)) s
764 (col (org-table-current-column))
765 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
768 (skip-chars-backward "^|\n")
769 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
771 (setq s
(match-string 1)
773 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
774 e
(not (= (match-beginning 2) (match-end 2))))
775 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
776 l
(if e
"|" (setq org-table-may-need-update t
) ""))
779 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
780 (setq n
(format f new
))
781 (setq n
(concat new
"|") org-table-may-need-update t
)))
783 (let (org-table-may-need-update)
784 (replace-match n t t
))))
785 (setq org-table-may-need-update t
))
788 (defun org-table-next-field ()
789 "Go to the next field in the current table, creating new lines as needed.
790 Before doing so, re-align the table if necessary."
792 (org-table-maybe-eval-formula)
793 (org-table-maybe-recalculate-line)
794 (if (and org-table-automatic-realign
795 org-table-may-need-update
)
797 (let ((end (org-table-end)))
798 (if (org-at-table-hline-p)
802 (re-search-forward "|" end
)
803 (if (looking-at "[ \t]*$")
804 (re-search-forward "|" end
))
805 (if (and (looking-at "-")
806 org-table-tab-jumps-over-hlines
807 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
808 (goto-char (match-beginning 1)))
811 (beginning-of-line 0)
812 (org-table-insert-row 'below
))
813 (if (looking-at " ") (forward-char 1))))
815 (org-table-insert-row 'below
)))))
817 (defun org-table-previous-field ()
818 "Go to the previous field in the table.
819 Before doing so, re-align the table if necessary."
821 (org-table-justify-field-maybe)
822 (org-table-maybe-recalculate-line)
823 (if (and org-table-automatic-realign
824 org-table-may-need-update
)
826 (if (org-at-table-hline-p)
828 (re-search-backward "|" (org-table-begin))
829 (re-search-backward "|" (org-table-begin))
830 (while (looking-at "|\\(-\\|[ \t]*$\\)")
831 (re-search-backward "|" (org-table-begin)))
832 (if (looking-at "| ?")
833 (goto-char (match-end 0))))
835 (defun org-table-next-row ()
836 "Go to the next row (same column) in the current table.
837 Before doing so, re-align the table if necessary."
839 (org-table-maybe-eval-formula)
840 (org-table-maybe-recalculate-line)
841 (if (or (looking-at "[ \t]*$")
842 (save-excursion (skip-chars-backward " \t") (bolp)))
844 (if (and org-table-automatic-realign
845 org-table-may-need-update
)
847 (let ((col (org-table-current-column)))
848 (beginning-of-line 2)
849 (if (or (not (org-at-table-p))
850 (org-at-table-hline-p))
852 (beginning-of-line 0)
853 (org-table-insert-row 'below
)))
854 (org-table-goto-column col
)
855 (skip-chars-backward "^|\n\r")
856 (if (looking-at " ") (forward-char 1)))))
858 (defun org-table-copy-down (n)
859 "Copy a field down in the current column.
860 If the field at the cursor is empty, copy into it the content of the nearest
861 non-empty field above. With argument N, use the Nth non-empty field.
862 If the current field is not empty, it is copied down to the next row, and
863 the cursor is moved with it. Therefore, repeating this command causes the
864 column to be filled row-by-row.
865 If the variable `org-table-copy-increment' is non-nil and the field is an
866 integer or a timestamp, it will be incremented while copying. In the case of
867 a timestamp, if the cursor is on the year, change the year. If it is on the
868 month or the day, change that. Point will stay on the current date field
869 in order to easily repeat the interval."
871 (let* ((colpos (org-table-current-column))
872 (col (current-column))
873 (field (org-table-get-field))
874 (non-empty (string-match "[^ \t]" field
))
875 (beg (org-table-begin))
878 (org-table-check-inside-data-field)
881 (setq txt
(org-trim field
))
883 (org-table-blank-field))
887 (while (progn (beginning-of-line 1)
888 (re-search-backward org-table-dataline-regexp
890 (org-table-goto-column colpos t
)
892 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
893 (<= (setq n
(1- n
)) 0))
894 (throw 'exit
(match-string 1))))))))
897 (if (and org-table-copy-increment
898 (not (equal orig-n
0))
899 (string-match "^[0-9]+$" txt
)
900 (< (string-to-number txt
) 100000000))
901 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
903 (org-move-to-column col
)
904 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
905 (org-timestamp-up-day)
906 (org-table-maybe-recalculate-line))
908 (org-move-to-column col
))
909 (error "No non-empty field found"))))
911 (defun org-table-check-inside-data-field ()
912 "Is point inside a table data field?
913 I.e. not on a hline or before the first or after the last column?
914 This actually throws an error, so it aborts the current command."
915 (if (or (not (org-at-table-p))
916 (= (org-table-current-column) 0)
917 (org-at-table-hline-p)
918 (looking-at "[ \t]*$"))
919 (error "Not in table data field")))
921 (defvar org-table-clip nil
922 "Clipboard for table regions.")
924 (defun org-table-blank-field ()
925 "Blank the current table field or active region."
927 (org-table-check-inside-data-field)
928 (if (and (interactive-p) (org-region-active-p))
929 (let (org-table-clip)
930 (org-table-cut-region (region-beginning) (region-end)))
931 (skip-chars-backward "^|")
933 (if (looking-at "|[^|\n]+")
934 (let* ((pos (match-beginning 0))
935 (match (match-string 0))
936 (len (org-string-width match
)))
937 (replace-match (concat "|" (make-string (1- len
) ?\
)))
938 (goto-char (+ 2 pos
))
939 (substring match
1)))))
941 (defun org-table-get-field (&optional n replace
)
942 "Return the value of the field in column N of current row.
943 N defaults to current field.
944 If REPLACE is a string, replace field with this value. The return value
945 is always the old value."
946 (and n
(org-table-goto-column n
))
947 (skip-chars-backward "^|\n")
949 (if (looking-at "|[^|\r\n]*")
950 (let* ((pos (match-beginning 0))
951 (val (buffer-substring (1+ pos
) (match-end 0))))
953 (replace-match (concat "|" replace
) t t
))
954 (goto-char (min (point-at-eol) (+ 2 pos
)))
956 (forward-char 1) ""))
958 (defun org-table-field-info (arg)
959 "Show info about the current field, and highlight any reference at point."
961 (org-table-get-specials)
964 (col (org-table-current-column))
965 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
966 (name (car (rassoc (list (org-current-line) col
)
967 org-table-named-field-locations
)))
968 (eql (org-table-get-stored-formulas))
969 (dline (org-table-current-dline))
970 (ref (format "@%d$%d" dline col
))
971 (ref1 (org-table-convert-refs-to-an ref
))
972 (fequation (or (assoc name eql
) (assoc ref eql
)))
973 (cequation (assoc (int-to-string col
) eql
))
974 (eqn (or fequation cequation
)))
977 (org-table-show-reference 'local
)
979 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
981 (if cname
(concat " or $" cname
) "")
983 (if name
(concat " or $" name
) "")
984 ;; FIXME: formula info not correct if special table line
986 (concat ", formula: "
987 (org-table-formula-to-user
989 (if (string-match "^[$@]"(car eqn
)) "" "$")
990 (car eqn
) "=" (cdr eqn
))))
993 (defun org-table-current-column ()
994 "Find out which column we are in."
996 (let ((cnt 0) (pos (point)))
997 (beginning-of-line 1)
998 (while (search-forward "|" pos t
)
1002 (defun org-table-current-dline ()
1003 "Find out what table data line we are in.
1004 Only datalines count for this."
1006 (if (interactive-p) (org-table-check-inside-data-field))
1008 (let ((cnt 0) (pos (point)))
1009 (goto-char (org-table-begin))
1010 (while (<= (point) pos
)
1011 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1012 (beginning-of-line 2))
1013 (if (interactive-p) (message "This is table line %d" cnt
))
1016 (defun org-table-goto-column (n &optional on-delim force
)
1017 "Move the cursor to the Nth column in the current table line.
1018 With optional argument ON-DELIM, stop with point before the left delimiter
1020 If there are less than N fields, just go to after the last delimiter.
1021 However, when FORCE is non-nil, create new columns if necessary."
1023 (let ((pos (point-at-eol)))
1024 (beginning-of-line 1)
1026 (while (and (> (setq n
(1- n
)) -
1)
1027 (or (search-forward "|" pos t
)
1029 (progn (end-of-line 1)
1030 (skip-chars-backward "^|")
1032 ; (backward-char 2) t)))))
1033 (when (and force
(not (looking-at ".*|")))
1034 (save-excursion (end-of-line 1) (insert " | ")))
1037 (if (looking-at " ") (forward-char 1))))))
1040 (defun org-table-insert-column ()
1041 "Insert a new column into the table."
1043 (if (not (org-at-table-p))
1044 (error "Not at a table"))
1045 (org-table-find-dataline)
1046 (let* ((col (max 1 (org-table-current-column)))
1047 (beg (org-table-begin))
1048 (end (org-table-end))
1049 ;; Current cursor position
1050 (linepos (org-current-line))
1053 (while (< (point) end
)
1054 (if (org-at-table-hline-p)
1056 (org-table-goto-column col t
)
1058 (beginning-of-line 2))
1059 (move-marker end nil
)
1061 (org-table-goto-column colpos
)
1063 (org-table-fix-formulas "$" nil
(1- col
) 1)))
1065 (defun org-table-find-dataline ()
1066 "Find a dataline in the current table, which is needed for column commands."
1067 (if (and (org-at-table-p)
1068 (not (org-at-table-hline-p)))
1070 (let ((col (current-column))
1071 (end (org-table-end)))
1072 (org-move-to-column col
)
1073 (while (and (< (point) end
)
1074 (or (not (= (current-column) col
))
1075 (org-at-table-hline-p)))
1076 (beginning-of-line 2)
1077 (org-move-to-column col
))
1078 (if (and (org-at-table-p)
1079 (not (org-at-table-hline-p)))
1082 "Please position cursor in a data line for column operations")))))
1084 (defun org-table-delete-column ()
1085 "Delete a column from the table."
1087 (if (not (org-at-table-p))
1088 (error "Not at a table"))
1089 (org-table-find-dataline)
1090 (org-table-check-inside-data-field)
1091 (let* ((col (org-table-current-column))
1092 (beg (org-table-begin))
1093 (end (org-table-end))
1094 ;; Current cursor position
1095 (linepos (org-current-line))
1098 (while (< (point) end
)
1099 (if (org-at-table-hline-p)
1101 (org-table-goto-column col t
)
1102 (and (looking-at "|[^|\n]+|")
1103 (replace-match "|")))
1104 (beginning-of-line 2))
1105 (move-marker end nil
)
1107 (org-table-goto-column colpos
)
1109 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1112 (defun org-table-move-column-right ()
1113 "Move column to the right."
1115 (org-table-move-column nil
))
1116 (defun org-table-move-column-left ()
1117 "Move column to the left."
1119 (org-table-move-column 'left
))
1121 (defun org-table-move-column (&optional left
)
1122 "Move the current column to the right. With arg LEFT, move to the left."
1124 (if (not (org-at-table-p))
1125 (error "Not at a table"))
1126 (org-table-find-dataline)
1127 (org-table-check-inside-data-field)
1128 (let* ((col (org-table-current-column))
1129 (col1 (if left
(1- col
) col
))
1130 (beg (org-table-begin))
1131 (end (org-table-end))
1132 ;; Current cursor position
1133 (linepos (org-current-line))
1134 (colpos (if left
(1- col
) (1+ col
))))
1135 (if (and left
(= col
1))
1136 (error "Cannot move column further left"))
1137 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1138 (error "Cannot move column further right"))
1140 (while (< (point) end
)
1141 (if (org-at-table-hline-p)
1143 (org-table-goto-column col1 t
)
1144 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1145 (replace-match "|\\2|\\1|")))
1146 (beginning-of-line 2))
1147 (move-marker end nil
)
1149 (org-table-goto-column colpos
)
1151 (org-table-fix-formulas
1152 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1153 (cons (number-to-string colpos
) (number-to-string col
))))))
1155 (defun org-table-move-row-down ()
1156 "Move table row down."
1158 (org-table-move-row nil
))
1159 (defun org-table-move-row-up ()
1160 "Move table row up."
1162 (org-table-move-row 'up
))
1164 (defun org-table-move-row (&optional up
)
1165 "Move the current table line down. With arg UP, move it up."
1167 (let* ((col (current-column))
1169 (hline1p (save-excursion (beginning-of-line 1)
1170 (looking-at org-table-hline-regexp
)))
1171 (dline1 (org-table-current-dline))
1172 (dline2 (+ dline1
(if up -
1 1)))
1175 (beginning-of-line tonew
)
1176 (unless (org-at-table-p)
1178 (error "Cannot move row further"))
1179 (setq hline2p
(looking-at org-table-hline-regexp
))
1181 (beginning-of-line 1)
1183 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1184 (delete-region (point) (1+ (point-at-eol)))
1185 (beginning-of-line tonew
)
1187 (beginning-of-line 0)
1188 (org-move-to-column col
)
1189 (unless (or hline1p hline2p
)
1190 (org-table-fix-formulas
1191 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1192 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1194 (defun org-table-insert-row (&optional arg
)
1195 "Insert a new row above the current line into the table.
1196 With prefix ARG, insert below the current line."
1198 (if (not (org-at-table-p))
1199 (error "Not at a table"))
1200 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1201 (new (org-table-clean-line line
)))
1202 ;; Fix the first field if necessary
1203 (if (string-match "^[ \t]*| *[#$] *|" line
)
1204 (setq new
(replace-match (match-string 0 line
) t t new
)))
1205 (beginning-of-line (if arg
2 1))
1206 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1207 (beginning-of-line 0)
1208 (re-search-forward "| ?" (point-at-eol) t
)
1209 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1211 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1)))
1213 (defun org-table-insert-hline (&optional above
)
1214 "Insert a horizontal-line below the current line into the table.
1215 With prefix ABOVE, insert above the current line."
1217 (if (not (org-at-table-p))
1218 (error "Not at a table"))
1219 (let ((line (org-table-clean-line
1220 (buffer-substring (point-at-bol) (point-at-eol))))
1221 (col (current-column)))
1222 (while (string-match "|\\( +\\)|" line
)
1223 (setq line
(replace-match
1224 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1225 ?-
) "|") t t line
)))
1226 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1227 (beginning-of-line (if above
1 2))
1229 (beginning-of-line (if above
1 -
1))
1230 (org-move-to-column col
)
1231 (and org-table-overlay-coordinates
(org-table-align))))
1233 (defun org-table-hline-and-move (&optional same-column
)
1234 "Insert a hline and move to the row below that line."
1236 (let ((col (org-table-current-column)))
1237 (org-table-maybe-eval-formula)
1238 (org-table-maybe-recalculate-line)
1239 (org-table-insert-hline)
1241 (if (looking-at "\n[ \t]*|-")
1242 (progn (insert "\n|") (org-table-align))
1243 (org-table-next-field))
1244 (if same-column
(org-table-goto-column col
))))
1246 (defun org-table-clean-line (s)
1247 "Convert a table line S into a string with only \"|\" and space.
1248 In particular, this does handle wide and invisible characters."
1249 (if (string-match "^[ \t]*|-" s
)
1250 ;; It's a hline, just map the characters
1251 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1252 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1253 (setq s
(replace-match
1254 (concat "|" (make-string (org-string-width (match-string 1 s
))
1259 (defun org-table-kill-row ()
1260 "Delete the current row or horizontal line from the table."
1262 (if (not (org-at-table-p))
1263 (error "Not at a table"))
1264 (let ((col (current-column))
1265 (dline (org-table-current-dline)))
1266 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1267 (if (not (org-at-table-p)) (beginning-of-line 0))
1268 (org-move-to-column col
)
1269 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1272 (defun org-table-sort-lines (with-case &optional sorting-type
)
1273 "Sort table lines according to the column at point.
1275 The position of point indicates the column to be used for
1276 sorting, and the range of lines is the range between the nearest
1277 horizontal separator lines, or the entire table of no such lines
1278 exist. If point is before the first column, you will be prompted
1279 for the sorting column. If there is an active region, the mark
1280 specifies the first line and the sorting column, while point
1281 should be in the last line to be included into the sorting.
1283 The command then prompts for the sorting type which can be
1284 alphabetically, numerically, or by time (as given in a time stamp
1285 in the field). Sorting in reverse order is also possible.
1287 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1289 If SORTING-TYPE is specified when this function is called from a Lisp
1290 program, no prompting will take place. SORTING-TYPE must be a character,
1291 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1292 should be done in reverse order."
1294 (let* ((thisline (org-current-line))
1295 (thiscol (org-table-current-column))
1296 beg end bcol ecol tend tbeg column lns pos
)
1297 (when (equal thiscol
0)
1301 (read-string "Use column N for sorting: ")))
1303 (org-table-goto-column thiscol
))
1304 (org-table-check-inside-data-field)
1305 (if (org-region-active-p)
1307 (setq beg
(region-beginning) end
(region-end))
1309 (setq column
(org-table-current-column)
1312 (setq end
(point-at-bol 2)))
1313 (setq column
(org-table-current-column)
1315 tbeg
(org-table-begin)
1316 tend
(org-table-end))
1317 (if (re-search-backward org-table-hline-regexp tbeg t
)
1318 (setq beg
(point-at-bol 2))
1320 (setq beg
(point-at-bol 1)))
1322 (if (re-search-forward org-table-hline-regexp tend t
)
1323 (setq end
(point-at-bol 1))
1325 (setq end
(point-at-bol))))
1326 (setq beg
(move-marker (make-marker) beg
)
1327 end
(move-marker (make-marker) end
))
1330 (org-table-goto-column column
)
1331 (skip-chars-backward "^|")
1332 (setq bcol
(current-column))
1333 (org-table-goto-column (1+ column
))
1334 (skip-chars-backward "^|")
1335 (setq ecol
(1- (current-column)))
1336 (org-table-goto-column column
)
1337 (setq lns
(mapcar (lambda(x) (cons
1338 (org-sort-remove-invisible
1340 (org-split-string x
"[ \t]*|[ \t]*")))
1342 (org-split-string (buffer-substring beg end
) "\n")))
1343 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1344 (delete-region beg end
)
1345 (move-marker beg nil
)
1346 (move-marker end nil
)
1347 (insert (mapconcat 'cdr lns
"\n") "\n")
1348 (goto-line thisline
)
1349 (org-table-goto-column thiscol
)
1350 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1353 (defun org-table-cut-region (beg end
)
1354 "Copy region in table to the clipboard and blank all relevant fields."
1356 (org-table-copy-region beg end
'cut
))
1358 (defun org-table-copy-region (beg end
&optional cut
)
1359 "Copy rectangular region in table to clipboard.
1360 A special clipboard is used which can only be accessed
1361 with `org-table-paste-rectangle'."
1363 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1365 (rpl (if cut
" " nil
)))
1367 (org-table-check-inside-data-field)
1368 (setq l01
(org-current-line)
1369 c01
(org-table-current-column))
1371 (org-table-check-inside-data-field)
1372 (setq l02
(org-current-line)
1373 c02
(org-table-current-column))
1374 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1375 c1
(min c01 c02
) c2
(max c01 c02
))
1379 (if (> l1 l2
) (throw 'exit t
))
1381 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1382 (setq cols nil ic1 c1 ic2 c2
)
1383 (while (< ic1
(1+ ic2
))
1384 (push (org-table-get-field ic1 rpl
) cols
)
1385 (setq ic1
(1+ ic1
)))
1386 (push (nreverse cols
) region
)
1387 (setq l1
(1+ l1
)))))
1388 (setq org-table-clip
(nreverse region
))
1389 (if cut
(org-table-align))
1392 (defun org-table-paste-rectangle ()
1393 "Paste a rectangular region into a table.
1394 The upper right corner ends up in the current field. All involved fields
1395 will be overwritten. If the rectangle does not fit into the present table,
1396 the table is enlarged as needed. The process ignores horizontal separator
1399 (unless (and org-table-clip
(listp org-table-clip
))
1400 (error "First cut/copy a region to paste!"))
1401 (org-table-check-inside-data-field)
1402 (let* ((clip org-table-clip
)
1403 (line (org-current-line))
1404 (col (org-table-current-column))
1405 (org-enable-table-editor t
)
1406 (org-table-automatic-realign nil
)
1408 (while (setq cols
(pop clip
))
1409 (while (org-at-table-hline-p) (beginning-of-line 2))
1410 (if (not (org-at-table-p))
1411 (progn (end-of-line 0) (org-table-next-field)))
1413 (while (setq field
(pop cols
))
1414 (org-table-goto-column c nil
'force
)
1415 (org-table-get-field nil field
)
1417 (beginning-of-line 2))
1419 (org-table-goto-column col
)
1422 (defun org-table-convert ()
1423 "Convert from `org-mode' table to table.el and back.
1424 Obviously, this only works within limits. When an Org-mode table is
1425 converted to table.el, all horizontal separator lines get lost, because
1426 table.el uses these as cell boundaries and has no notion of horizontal lines.
1427 A table.el table can be converted to an Org-mode table only if it does not
1428 do row or column spanning. Multiline cells will become multiple cells.
1429 Beware, Org-mode does not test if the table can be successfully converted - it
1430 blindly applies a recipe that works for simple tables."
1433 (if (org-at-table.el-p
)
1434 ;; convert to Org-mode table
1435 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1436 (end (move-marker (make-marker) (org-table-end t
))))
1437 (table-unrecognize-region beg end
)
1439 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1442 (if (org-at-table-p)
1443 ;; convert to table.el table
1444 (let ((beg (move-marker (make-marker) (org-table-begin)))
1445 (end (move-marker (make-marker) (org-table-end))))
1446 ;; first, get rid of all horizontal lines
1448 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1450 ;; insert a hline before first
1452 (org-table-insert-hline 'above
)
1453 (beginning-of-line -
1)
1454 ;; insert a hline after each line
1455 (while (progn (beginning-of-line 3) (< (point) end
))
1456 (org-table-insert-hline))
1458 (setq end
(move-marker end
(org-table-end)))
1459 ;; replace "+" at beginning and ending of hlines
1460 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1461 (replace-match "\\1+-"))
1463 (while (re-search-forward "-|[ \t]*$" end t
)
1464 (replace-match "-+"))
1467 (defun org-table-wrap-region (arg)
1468 "Wrap several fields in a column like a paragraph.
1469 This is useful if you'd like to spread the contents of a field over several
1470 lines, in order to keep the table compact.
1472 If there is an active region, and both point and mark are in the same column,
1473 the text in the column is wrapped to minimum width for the given number of
1474 lines. Generally, this makes the table more compact. A prefix ARG may be
1475 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1476 formats the selected text to two lines. If the region was longer than two
1477 lines, the remaining lines remain empty. A negative prefix argument reduces
1478 the current number of lines by that amount. The wrapped text is pasted back
1479 into the table. If you formatted it to more lines than it was before, fields
1480 further down in the table get overwritten - so you might need to make space in
1483 If there is no region, the current field is split at the cursor position and
1484 the text fragment to the right of the cursor is prepended to the field one
1487 If there is no region, but you specify a prefix ARG, the current field gets
1488 blank, and the content is appended to the field above."
1490 (org-table-check-inside-data-field)
1491 (if (org-region-active-p)
1492 ;; There is a region: fill as a paragraph
1493 (let* ((beg (region-beginning))
1494 (cline (save-excursion (goto-char beg
) (org-current-line)))
1495 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1497 (org-table-cut-region (region-beginning) (region-end))
1498 (if (> (length (car org-table-clip
)) 1)
1499 (error "Region must be limited to single column"))
1500 (setq nlines
(if arg
1502 (+ (length org-table-clip
) arg
)
1504 (length org-table-clip
)))
1505 (setq org-table-clip
1506 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1509 (org-table-goto-column ccol
)
1510 (org-table-paste-rectangle))
1511 ;; No region, split the current field at point
1512 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1513 (skip-chars-forward "^\r\n|"))
1515 ;; combine with field above
1516 (let ((s (org-table-blank-field))
1517 (col (org-table-current-column)))
1518 (beginning-of-line 0)
1519 (while (org-at-table-hline-p) (beginning-of-line 0))
1520 (org-table-goto-column col
)
1521 (skip-chars-forward "^|")
1522 (skip-chars-backward " ")
1523 (insert " " (org-trim s
))
1526 (if (looking-at "\\([^|]+\\)+|")
1527 (let ((s (match-string 1)))
1528 (replace-match " |")
1529 (goto-char (match-beginning 0))
1530 (org-table-next-row)
1531 (insert (org-trim s
) " ")
1533 (org-table-next-row)))))
1535 (defvar org-field-marker nil
)
1537 (defun org-table-edit-field (arg)
1538 "Edit table field in a different window.
1539 This is mainly useful for fields that contain hidden parts.
1540 When called with a \\[universal-argument] prefix, just make the full field visible so that
1541 it can be edited in place."
1544 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1545 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1546 (remove-text-properties b e
'(org-cwidth t invisible t
1547 display t intangible t
))
1548 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1549 (font-lock-fontify-block)))
1550 (let ((pos (move-marker (make-marker) (point)))
1551 (field (org-table-get-field))
1552 (cw (current-window-configuration))
1554 (org-switch-to-buffer-other-window "*Org tmp*")
1556 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
1557 (let ((org-inhibit-startup t
)) (org-mode))
1558 (goto-char (setq p
(point-max)))
1559 (insert (org-trim field
))
1560 (remove-text-properties p
(point-max)
1561 '(invisible t org-cwidth t display t
1564 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1565 (org-set-local 'org-window-configuration cw
)
1566 (org-set-local 'org-field-marker pos
)
1567 (message "Edit and finish with C-c C-c"))))
1569 (defun org-table-finish-edit-field ()
1570 "Finish editing a table data field.
1571 Remove all newline characters, insert the result into the table, realign
1572 the table and kill the editing buffer."
1573 (let ((pos org-field-marker
)
1574 (cw org-window-configuration
)
1575 (cb (current-buffer))
1577 (goto-char (point-min))
1578 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1579 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1580 (replace-match " "))
1581 (setq text
(org-trim (buffer-string)))
1582 (set-window-configuration cw
)
1584 (select-window (get-buffer-window (marker-buffer pos
)))
1586 (move-marker pos nil
)
1587 (org-table-check-inside-data-field)
1588 (org-table-get-field nil text
)
1590 (message "New field value inserted")))
1609 (defvar org-timecnt
) ; dynamically scoped parameter
1611 (defun org-table-sum (&optional beg end nlast
)
1612 "Sum numbers in region of current table column.
1613 The result will be displayed in the echo area, and will be available
1614 as kill to be inserted with \\[yank].
1616 If there is an active region, it is interpreted as a rectangle and all
1617 numbers in that rectangle will be summed. If there is no active
1618 region and point is located in a table column, sum all numbers in that
1621 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1622 numbers are assumed to be times as well (in decimal hours) and the
1623 numbers are added as such.
1625 If NLAST is a number, only the NLAST fields will actually be summed."
1628 (let (col (org-timecnt 0) diff h m s org-table-clip
)
1630 ((and beg end
)) ; beg and end given explicitly
1631 ((org-region-active-p)
1632 (setq beg
(region-beginning) end
(region-end)))
1634 (setq col
(org-table-current-column))
1635 (goto-char (org-table-begin))
1636 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
1637 (error "No table data"))
1638 (org-table-goto-column col
)
1640 (goto-char (org-table-end))
1641 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
1642 (error "No table data"))
1643 (org-table-goto-column col
)
1644 (setq end
(point))))
1645 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
1646 (items1 (cond ((not nlast
) items
)
1647 ((>= nlast
(length items
)) items
)
1648 (t (setq items
(reverse items
))
1649 (setcdr (nthcdr (1- nlast
) items
) nil
)
1651 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
1653 (res (apply '+ numbers
))
1654 (sres (if (= org-timecnt
0)
1655 (number-to-string res
)
1656 (setq diff
(* 3600 res
)
1657 h
(floor (/ diff
3600)) diff
(mod diff
3600)
1658 m
(floor (/ diff
60)) diff
(mod diff
60)
1660 (format "%d:%02d:%02d" h m s
))))
1664 (substitute-command-keys
1665 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
1666 (length numbers
) sres
))))
1669 (defun org-table-get-number-for-summing (s)
1671 (if (string-match "^ *|? *" s
)
1672 (setq s
(replace-match "" nil nil s
)))
1673 (if (string-match " *|? *$" s
)
1674 (setq s
(replace-match "" nil nil s
)))
1675 (setq n
(string-to-number s
))
1677 ((and (string-match "0" s
)
1678 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
1679 ((string-match "\\`[ \t]+\\'" s
) nil
)
1680 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
1681 (let ((h (string-to-number (or (match-string 1 s
) "0")))
1682 (m (string-to-number (or (match-string 2 s
) "0")))
1683 (s (string-to-number (or (match-string 4 s
) "0"))))
1684 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
1685 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
1689 (defun org-table-current-field-formula (&optional key noerror
)
1690 "Return the formula active for the current field.
1691 Assumes that specials are in place.
1692 If KEY is given, return the key to this formula.
1693 Otherwise return the formula preceeded with \"=\" or \":=\"."
1694 (let* ((name (car (rassoc (list (org-current-line)
1695 (org-table-current-column))
1696 org-table-named-field-locations
)))
1697 (col (org-table-current-column))
1698 (scol (int-to-string col
))
1699 (ref (format "@%d$%d" (org-table-current-dline) col
))
1700 (stored-list (org-table-get-stored-formulas noerror
))
1701 (ass (or (assoc name stored-list
)
1702 (assoc ref stored-list
)
1703 (assoc scol stored-list
))))
1706 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
1709 (defun org-table-get-formula (&optional equation named
)
1710 "Read a formula from the minibuffer, offer stored formula as default.
1711 When NAMED is non-nil, look for a named equation."
1712 (let* ((stored-list (org-table-get-stored-formulas))
1713 (name (car (rassoc (list (org-current-line)
1714 (org-table-current-column))
1715 org-table-named-field-locations
)))
1716 (ref (format "@%d$%d" (org-table-current-dline)
1717 (org-table-current-column)))
1718 (refass (assoc ref stored-list
))
1721 (int-to-string (org-table-current-column))))
1722 (dummy (and (or name refass
) (not named
)
1723 (not (y-or-n-p "Replace field formula with column formula? " ))
1725 (name (or name ref
))
1726 (org-table-may-need-update nil
)
1727 (stored (cdr (assoc scol stored-list
)))
1729 ((and stored equation
(string-match "^ *=? *$" equation
))
1733 (t (org-table-formula-from-user
1735 (org-table-formula-to-user
1736 (format "%s formula %s%s="
1737 (if named
"Field" "Column")
1738 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
1740 (if stored
(org-table-formula-to-user stored
) "")
1741 'org-table-formula-history
1744 (when (not (string-match "\\S-" eq
))
1746 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
1747 (org-table-store-formulas stored-list
)
1748 (error "Formula removed"))
1749 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
1750 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
1751 (if (and name
(not named
))
1752 ;; We set the column equation, delete the named one.
1753 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
1756 (setcdr (assoc scol stored-list
) eq
)
1757 (setq stored-list
(cons (cons scol eq
) stored-list
)))
1758 (if (or mustsave
(not (equal stored eq
)))
1759 (org-table-store-formulas stored-list
))
1762 (defun org-table-store-formulas (alist)
1763 "Store the list of formulas below the current table."
1764 (setq alist
(sort alist
'org-table-formula-less-p
))
1766 (goto-char (org-table-end))
1767 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
1769 ;; don't overwrite TBLFM, we might use text properties to store stuff
1770 (goto-char (match-beginning 2))
1771 (delete-region (match-beginning 2) (match-end 0)))
1772 (insert "#+TBLFM:"))
1774 (mapconcat (lambda (x)
1776 (if (equal (string-to-char (car x
)) ?
@) "" "$")
1777 (car x
) "=" (cdr x
)))
1781 (defsubst org-table-formula-make-cmp-string
(a)
1782 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a
)
1784 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a
))) "")
1785 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a
))) "")
1786 (if (match-end 5) (concat "@@" (match-string 5 a
))))))
1788 (defun org-table-formula-less-p (a b
)
1789 "Compare two formulas for sorting."
1790 (let ((as (org-table-formula-make-cmp-string (car a
)))
1791 (bs (org-table-formula-make-cmp-string (car b
))))
1792 (and as bs
(string< as bs
))))
1794 (defun org-table-get-stored-formulas (&optional noerror
)
1795 "Return an alist with the stored formulas directly after current table."
1797 (let (scol eq eq-alist strings string seen
)
1799 (goto-char (org-table-end))
1800 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
1801 (setq strings
(org-split-string (match-string 2) " *:: *"))
1802 (while (setq string
(pop strings
))
1803 (when (string-match "\\`\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
1804 (setq scol
(if (match-end 2)
1805 (match-string 2 string
)
1806 (match-string 1 string
))
1807 eq
(match-string 3 string
)
1808 eq-alist
(cons (cons scol eq
) eq-alist
))
1809 (if (member scol seen
)
1812 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
1815 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
1816 (push scol seen
))))))
1817 (nreverse eq-alist
)))
1819 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
1820 "Modify the equations after the table structure has been edited.
1821 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
1822 For all numbers larger than LIMIT, shift them by DELTA."
1824 (goto-char (org-table-end))
1825 (when (looking-at "#\\+TBLFM:")
1826 (let ((re (concat key
"\\([0-9]+\\)"))
1830 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove
)
1831 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
1834 (while (re-search-forward re2
(point-at-eol) t
)
1835 (replace-match "")))
1836 (while (re-search-forward re
(point-at-eol) t
)
1837 (setq s
(match-string 1) n
(string-to-number s
))
1839 ((setq a
(assoc s replace
))
1840 (replace-match (concat key
(cdr a
)) t t
))
1841 ((and limit
(> n limit
))
1842 (replace-match (concat key
(int-to-string (+ n delta
))) t t
))))))))
1844 (defun org-table-get-specials ()
1845 "Get the column names and local parameters for this table."
1847 (let ((beg (org-table-begin)) (end (org-table-end))
1848 names name fields fields1 field cnt
1849 c v l line col types dlines hlines
)
1850 (setq org-table-column-names nil
1851 org-table-local-parameters nil
1852 org-table-named-field-locations nil
1853 org-table-current-begin-line nil
1854 org-table-current-begin-pos nil
1855 org-table-current-line-types nil
)
1857 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
1858 (setq names
(org-split-string (match-string 1) " *| *")
1860 (while (setq name
(pop names
))
1862 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name
)
1863 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
1864 (setq org-table-column-names
(nreverse org-table-column-names
))
1865 (setq org-table-column-name-regexp
1866 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
1868 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
1869 (setq fields
(org-split-string (match-string 1) " *| *"))
1870 (while (setq field
(pop fields
))
1871 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
1872 (push (cons (match-string 1 field
) (match-string 2 field
))
1873 org-table-local-parameters
))))
1875 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
1876 (setq c
(match-string 1)
1877 fields
(org-split-string (match-string 2) " *| *"))
1879 (beginning-of-line (if (equal c
"_") 2 0))
1880 (setq line
(org-current-line) col
1)
1881 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
1882 (setq fields1
(org-split-string (match-string 1) " *| *"))))
1883 (while (and fields1
(setq field
(pop fields
)))
1884 (setq v
(pop fields1
) col
(1+ col
))
1885 (when (and (stringp field
) (stringp v
)
1886 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field
))
1887 (push (cons field v
) org-table-local-parameters
)
1888 (push (list field line col
) org-table-named-field-locations
))))
1889 ;; Analyse the line types
1891 (setq org-table-current-begin-line
(org-current-line)
1892 org-table-current-begin-pos
(point)
1893 l org-table-current-begin-line
)
1894 (while (looking-at "[ \t]*|\\(-\\)?")
1895 (push (if (match-end 1) 'hline
'dline
) types
)
1896 (if (match-end 1) (push l hlines
) (push l dlines
))
1897 (beginning-of-line 2)
1899 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
1900 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
1901 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
)))))))
1903 (defun org-table-maybe-eval-formula ()
1904 "Check if the current field starts with \"=\" or \":=\".
1905 If yes, store the formula and apply it."
1906 ;; We already know we are in a table. Get field will only return a formula
1907 ;; when appropriate. It might return a separator line, but no problem.
1908 (when org-table-formula-evaluate-inline
1909 (let* ((field (org-trim (or (org-table-get-field) "")))
1911 (when (string-match "^:?=\\(.*\\)" field
)
1912 (setq named
(equal (string-to-char field
) ?
:)
1913 eq
(match-string 1 field
))
1914 (if (or (fboundp 'calc-eval
)
1915 (equal (substring eq
0 (min 2 (length eq
))) "'("))
1916 (org-table-eval-formula (if named
'(4) nil
)
1917 (org-table-formula-from-user eq
))
1918 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
1920 (defvar org-recalc-commands nil
1921 "List of commands triggering the recalculation of a line.
1922 Will be filled automatically during use.")
1924 (defvar org-recalc-marks
1925 '((" " .
"Unmarked: no special line, no automatic recalculation")
1926 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
1927 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
1928 ("!" .
"Column name definition line. Reference in formula as $name.")
1929 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
1930 ("_" .
"Names for values in row below this one.")
1931 ("^" .
"Names for values in row above this one.")))
1933 (defun org-table-rotate-recalc-marks (&optional newchar
)
1934 "Rotate the recalculation mark in the first column.
1935 If in any row, the first field is not consistent with a mark,
1936 insert a new column for the markers.
1937 When there is an active region, change all the lines in the region,
1938 after prompting for the marking character.
1939 After each change, a message will be displayed indicating the meaning
1942 (unless (org-at-table-p) (error "Not at a table"))
1943 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
1944 (beg (org-table-begin))
1945 (end (org-table-end))
1946 (l (org-current-line))
1947 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
1948 (l2 (if (org-region-active-p) (org-current-line (region-end))))
1952 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
1953 (col (org-table-current-column))
1954 (forcenew (car (assoc newchar org-recalc-marks
)))
1957 (message "Change region to what mark? Type # * ! $ or SPC: ")
1958 (setq newchar
(char-to-string (read-char-exclusive))
1959 forcenew
(car (assoc newchar org-recalc-marks
))))
1960 (if (and newchar
(not forcenew
))
1961 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
1963 (if l1
(goto-line l1
))
1965 (beginning-of-line 1)
1966 (unless (looking-at org-table-dataline-regexp
)
1967 (error "Not at a table data line")))
1969 (org-table-goto-column 1)
1970 (org-table-insert-column)
1971 (org-table-goto-column (1+ col
)))
1972 (setq epos
(point-at-eol))
1974 (beginning-of-line 1)
1975 (org-table-get-field
1976 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
1978 (setq new
(or forcenew
1979 (cadr (member (match-string 1) marks
))))
1985 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
1986 (and (looking-at org-table-dataline-regexp
)
1987 (org-table-get-field 1 (concat " " new
" "))))
1989 (if (not (= epos
(point-at-eol))) (org-table-align))
1991 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks
))))))
1993 (defun org-table-maybe-recalculate-line ()
1994 "Recompute the current line if marked for it, and if we haven't just done it."
1996 (and org-table-allow-automatic-line-recalculation
1997 (not (and (memq last-command org-recalc-commands
)
1998 (equal org-last-recalc-line
(org-current-line))))
1999 (save-excursion (beginning-of-line 1)
2000 (looking-at org-table-auto-recalculate-regexp
))
2001 (org-table-recalculate) t
))
2004 (defsubst org-set-calc-mode
(var &optional value
)
2006 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2007 ("R" calc-angle-mode rad
)
2008 ("F" calc-prefer-frac t
)
2009 ("S" calc-symbolic-mode t
)))
2010 value
(nth 2 var
) var
(nth 1 var
)))
2011 (if (memq var modes
)
2012 (setcar (cdr (memq var modes
)) value
)
2013 (cons var
(cons value modes
)))
2016 (defun org-table-eval-formula (&optional arg equation
2017 suppress-align suppress-const
2018 suppress-store suppress-analysis
)
2019 "Replace the table field value at the cursor by the result of a calculation.
2021 This function makes use of Dave Gillespie's Calc package, in my view the
2022 most exciting program ever written for GNU Emacs. So you need to have Calc
2023 installed in order to use this function.
2025 In a table, this command replaces the value in the current field with the
2026 result of a formula. It also installs the formula as the \"current\" column
2027 formula, by storing it in a special line below the table. When called
2028 with a `C-u' prefix, the current field must ba a named field, and the
2029 formula is installed as valid in only this specific field.
2031 When called with two `C-u' prefixes, insert the active equation
2032 for the field back into the current field, so that it can be
2033 edited there. This is useful in order to use \\[org-table-show-reference]
2034 to check the referenced fields.
2036 When called, the command first prompts for a formula, which is read in
2037 the minibuffer. Previously entered formulas are available through the
2038 history list, and the last used formula is offered as a default.
2039 These stored formulas are adapted correctly when moving, inserting, or
2040 deleting columns with the corresponding commands.
2042 The formula can be any algebraic expression understood by the Calc package.
2043 For details, see the Org-mode manual.
2045 This function can also be called from Lisp programs and offers
2046 additional arguments: EQUATION can be the formula to apply. If this
2047 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2048 used to speed-up recursive calls by by-passing unnecessary aligns.
2049 SUPPRESS-CONST suppresses the interpretation of constants in the
2050 formula, assuming that this has been done already outside the function.
2051 SUPPRESS-STORE means the formula should not be stored, either because
2052 it is already stored, or because it is a modified equation that should
2053 not overwrite the stored one."
2055 (org-table-check-inside-data-field)
2056 (or suppress-analysis
(org-table-get-specials))
2057 (if (equal arg
'(16))
2058 (let ((eq (org-table-current-field-formula)))
2059 (or eq
(error "No equation active for current field"))
2060 (org-table-get-field nil eq
)
2062 (setq org-table-may-need-update t
))
2064 (ndown (if (integerp arg
) arg
1))
2065 (org-table-automatic-realign nil
)
2066 (case-fold-search nil
)
2068 (formula (if (and equation suppress-store
)
2070 (org-table-get-formula equation
(equal arg
'(4)))))
2071 (n0 (org-table-current-column))
2072 (modes (copy-sequence org-calc-default-modes
))
2073 (numbers nil
) ; was a variable, now fixed default
2075 n form form0 bw fmt x ev orig c lispp literal
)
2076 ;; Parse the format string. Since we have a lot of modes, this is
2077 ;; a lot of work. However, I think calc still uses most of the time.
2078 (if (string-match ";" formula
)
2079 (let ((tmp (org-split-string formula
";")))
2080 (setq formula
(car tmp
)
2081 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2083 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2084 (setq c
(string-to-char (match-string 1 fmt
))
2085 n
(string-to-number (match-string 2 fmt
)))
2087 (setq modes
(org-set-calc-mode 'calc-internal-prec n
))
2088 (setq modes
(org-set-calc-mode
2090 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2091 (?s . sci
) (?e . eng
))))
2093 (setq fmt
(replace-match "" t t fmt
)))
2094 (if (string-match "[NT]" fmt
)
2095 (setq numbers
(equal (match-string 0 fmt
) "N")
2096 fmt
(replace-match "" t t fmt
)))
2097 (if (string-match "L" fmt
)
2099 fmt
(replace-match "" t t fmt
)))
2100 (if (string-match "E" fmt
)
2102 fmt
(replace-match "" t t fmt
)))
2103 (while (string-match "[DRFS]" fmt
)
2104 (setq modes
(org-set-calc-mode (match-string 0 fmt
)))
2105 (setq fmt
(replace-match "" t t fmt
)))
2106 (unless (string-match "\\S-" fmt
)
2108 (if (and (not suppress-const
) org-table-formula-use-constants
)
2109 (setq formula
(org-table-formula-substitute-names formula
)))
2110 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2112 (setq fields
(org-split-string
2114 (buffer-substring (point-at-bol) (point-at-eol)))
2117 (setq fields
(mapcar
2118 (lambda (x) (number-to-string (string-to-number x
)))
2120 (setq ndown
(1- ndown
))
2121 (setq form
(copy-sequence formula
)
2122 lispp
(and (> (length form
) 2)(equal (substring form
0 2) "'(")))
2123 (if (and lispp literal
) (setq lispp
'literal
))
2124 ;; Check for old vertical references
2125 (setq form
(org-table-rewrite-old-row-references form
))
2126 ;; Insert complex ranges
2127 (while (and (string-match org-table-range-regexp form
)
2128 (> (length (match-string 0 form
)) 1))
2132 (org-table-make-reference
2133 (org-table-get-range (match-string 0 form
) nil n0
)
2134 keep-empty numbers lispp
))
2136 ;; Insert simple ranges
2137 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2141 (org-table-make-reference
2143 fields
(string-to-number (match-string 1 form
))
2144 (string-to-number (match-string 2 form
)))
2145 keep-empty numbers lispp
))
2148 ;; Insert the references to fields in same row
2149 (while (string-match "\\$\\([0-9]+\\)" form
)
2150 (setq n
(string-to-number (match-string 1 form
))
2151 x
(nth (1- (if (= n
0) n0 n
)) fields
))
2152 (unless x
(error "Invalid field specifier \"%s\""
2153 (match-string 0 form
)))
2154 (setq form
(replace-match
2156 (org-table-make-reference x nil numbers lispp
))
2160 (setq ev
(condition-case nil
2161 (eval (eval (read form
)))
2163 ev
(if (numberp ev
) (number-to-string ev
) ev
))
2164 (or (fboundp 'calc-eval
)
2165 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2166 (setq ev
(calc-eval (cons form modes
)
2167 (if numbers
'num
))))
2169 (when org-table-formula-debug
2170 (with-output-to-temp-buffer "*Substitution History*"
2171 (princ (format "Substitution history of formula
2175 $1-> %s\n" orig formula form0 form
))
2177 (princ (format " %s^\nError: %s"
2178 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2179 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2181 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2182 (setq bw
(get-buffer-window "*Substitution History*"))
2183 (org-fit-window-to-buffer bw
)
2184 (unless (and (interactive-p) (not ndown
))
2185 (unless (let (inhibit-redisplay)
2186 (y-or-n-p "Debugging Formula. Continue to next? "))
2191 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2192 (org-table-justify-field-maybe
2193 (if fmt
(format fmt
(string-to-number ev
)) ev
))
2194 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2195 (call-interactively 'org-return
)
2197 (and down
(org-table-maybe-recalculate-line))
2198 (or suppress-align
(and org-table-may-need-update
2199 (org-table-align))))))
2201 (defun org-table-put-field-property (prop value
)
2203 (put-text-property (progn (skip-chars-backward "^|") (point))
2204 (progn (skip-chars-forward "^|") (point))
2207 (defun org-table-get-range (desc &optional tbeg col highlight
)
2208 "Get a calc vector from a column, according to descriptor DESC.
2209 Optional arguments TBEG and COL can give the beginning of the table and
2210 the current column, to avoid unnecessary parsing.
2211 HIGHLIGHT means, just highlight the range."
2212 (if (not (equal (string-to-char desc
) ?
@))
2213 (setq desc
(concat "@" desc
)))
2215 (or tbeg
(setq tbeg
(org-table-begin)))
2216 (or col
(setq col
(org-table-current-column)))
2217 (let ((thisline (org-current-line))
2218 beg end c1 c2 r1 r2 rangep tmp
)
2219 (unless (string-match org-table-range-regexp desc
)
2220 (error "Invalid table range specifier `%s'" desc
))
2221 (setq rangep
(match-end 3)
2222 r1
(and (match-end 1) (match-string 1 desc
))
2223 r2
(and (match-end 4) (match-string 4 desc
))
2224 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2225 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2227 (and c1
(setq c1
(+ (string-to-number c1
)
2228 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2229 (and c2
(setq c2
(+ (string-to-number c2
)
2230 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2231 (if (equal r1
"") (setq r1 nil
))
2232 (if (equal r2
"") (setq r2 nil
))
2233 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2234 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2235 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2236 (if (not r1
) (setq r1 thisline
))
2237 (if (not r2
) (setq r2 thisline
))
2238 (if (not c1
) (setq c1 col
))
2239 (if (not c2
) (setq c2 col
))
2240 (if (or (not rangep
) (and (= r1 r2
) (= c1 c2
)))
2244 (while (not (looking-at org-table-dataline-regexp
))
2245 (beginning-of-line 2))
2246 (prog1 (org-trim (org-table-get-field c1
))
2247 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2248 ;; A range, return a vector
2249 ;; First sort the numbers to get a regular ractangle
2250 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2251 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2253 (while (not (looking-at org-table-dataline-regexp
))
2254 (beginning-of-line 2))
2255 (org-table-goto-column c1
)
2258 (while (not (looking-at org-table-dataline-regexp
))
2259 (beginning-of-line 0))
2260 (org-table-goto-column c2
)
2263 (org-table-highlight-rectangle
2264 beg
(progn (skip-chars-forward "^|\n") (point))))
2265 ;; return string representation of calc vector
2267 (apply 'append
(org-table-copy-region beg end
)))))))
2269 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2270 "Analyze descriptor DESC and retrieve the corresponding line number.
2271 The cursor is currently in line CLINE, the table begins in line BLINE,
2272 and TABLE is a vector with line types."
2273 (if (string-match "^[0-9]+$" desc
)
2274 (aref org-table-dlines
(string-to-number desc
))
2275 (setq cline
(or cline
(org-current-line))
2276 bline
(or bline org-table-current-begin-line
)
2277 table
(or table org-table-current-line-types
))
2279 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2281 (and (not (match-end 3)) (not (match-end 6)))
2282 (and (match-end 3) (match-end 6) (not (match-end 5))))
2283 (error "invalid row descriptor `%s'" desc
))
2284 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2285 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2286 (odir (and (match-end 5) (match-string 5 desc
)))
2287 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2289 (rel (and (match-end 6)
2290 (or (and (match-end 1) (not (match-end 3)))
2292 (if (and hn
(not hdir
))
2295 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2296 (if (and (not hn
) on
(not odir
))
2297 (error "should never happen");;(aref org-table-dlines on)
2298 (if (and hn
(> hn
0))
2299 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2300 nil hn cline desc
)))
2302 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2303 rel on cline desc
)))
2306 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2307 "FIXME: Needs more documentation."
2308 (let ((l (length table
)))
2310 (while (and (setq i
(+ i
(if backwards -
1 1)))
2312 (not (eq (aref table i
) type
))
2313 (if (and relative
(eq (aref table i
) 'hline
))
2314 (if org-table-error-on-row-ref-crossing-hline
2315 (error "Row descriptor %s used in line %d crosses hline" desc cline
)
2316 (progn (setq i
(- i
(if backwards -
1 1)) n
1) nil
))
2319 (if (or (< i
0) (>= i l
))
2320 (error "Row descriptor %s used in line %d leads outside table"
2324 (defun org-table-rewrite-old-row-references (s)
2325 (if (string-match "&[-+0-9I]" s
)
2326 (error "Formula contains old &row reference, please rewrite using @-syntax")
2329 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2330 "Convert list ELEMENTS to something appropriate to insert into formula.
2331 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2332 NUMBERS indicates that everything should be converted to numbers.
2333 LISPP means to return something appropriate for a Lisp list."
2334 (if (stringp elements
) ; just a single val
2336 (if (eq lispp
'literal
)
2338 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2339 (if (equal elements
"") (setq elements
"0"))
2340 (if numbers
(setq elements
(number-to-string (string-to-number elements
))))
2341 (concat "(" elements
")"))
2345 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2347 (setq elements
(or elements
'("0")))
2351 (if (eq lispp
'literal
)
2353 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2355 (concat "[" (mapconcat
2357 (if numbers
(number-to-string (string-to-number x
)) x
))
2361 (defun org-table-recalculate (&optional all noalign
)
2362 "Recalculate the current table line by applying all stored formulas.
2363 With prefix arg ALL, do this for all lines in the table.
2364 With the prefix argument ALL is `(16)' (a double `C-c C-u' prefix), or if
2365 it is the symbol `iterate', recompute the table until it no longer changes.
2366 If NOALIGN is not nil, do not re-align the table after the computations
2367 are done. This is typically used internally to save time, if it is
2368 known that the table will be realigned a little later anyway."
2370 (or (memq this-command org-recalc-commands
)
2371 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2372 (unless (org-at-table-p) (error "Not at a table"))
2373 (if (or (eq all
'iterate
) (equal all
'(16)))
2375 (org-table-get-specials)
2376 (let* ((eqlist (sort (org-table-get-stored-formulas)
2377 (lambda (a b
) (string< (car a
) (car b
)))))
2378 (inhibit-redisplay (not debug-on-error
))
2379 (line-re org-table-dataline-regexp
)
2380 (thisline (org-current-line))
2381 (thiscol (org-table-current-column))
2382 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name
)
2383 ;; Insert constants in all formulas
2386 (setcdr x
(org-table-formula-substitute-names (cdr x
)))
2389 ;; Split the equation list
2390 (while (setq eq
(pop eqlist
))
2391 (if (<= (string-to-char (car eq
)) ?
9)
2394 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
2397 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
2398 (goto-char (setq beg
(org-table-begin)))
2399 (if (re-search-forward org-table-calculate-mark-regexp end t
)
2400 ;; This is a table with marked lines, compute selected lines
2401 (setq line-re org-table-recalculate-regexp
)
2402 ;; Move forward to the first non-header line
2403 (if (and (re-search-forward org-table-dataline-regexp end t
)
2404 (re-search-forward org-table-hline-regexp end t
)
2405 (re-search-forward org-table-dataline-regexp end t
))
2406 (setq beg
(match-beginning 0))
2407 nil
))) ;; just leave beg where it is
2408 (setq beg
(point-at-bol)
2409 end
(move-marker (make-marker) (1+ (point-at-eol)))))
2411 (and all
(message "Re-applying formulas to full table..."))
2413 ;; First find the named fields, and mark them untouchable
2414 (remove-text-properties beg end
'(org-untouchable t
))
2415 (while (setq eq
(pop eqlname
))
2417 a
(assoc name org-table-named-field-locations
))
2419 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
2422 (aref org-table-dlines
2423 (string-to-number (match-string 1 name
)))
2424 (error (error "Invalid row number in %s"
2426 (string-to-number (match-string 2 name
)))))
2427 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
2428 (message "Re-applying formula to field: %s" name
)
2429 (goto-line (nth 1 a
))
2430 (org-table-goto-column (nth 2 a
))
2431 (push (append a
(list (cdr eq
))) eqlname1
)
2432 (org-table-put-field-property :org-untouchable t
)))
2434 ;; Now evauluate the column formulas, but skip fields covered by
2437 (while (re-search-forward line-re end t
)
2438 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2439 ;; Unprotected line, recalculate
2440 (and all
(message "Re-applying formulas to full table...(line %d)"
2441 (setq cnt
(1+ cnt
))))
2442 (setq org-last-recalc-line
(org-current-line))
2444 (while (setq entry
(pop eql
))
2445 (goto-line org-last-recalc-line
)
2446 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
2447 (unless (get-text-property (point) :org-untouchable
)
2448 (org-table-eval-formula nil
(cdr entry
)
2449 'noalign
'nocst
'nostore
'noanalysis
)))))
2451 ;; Now evaluate the field formulas
2452 (while (setq eq
(pop eqlname1
))
2453 (message "Re-applying formula to field: %s" (car eq
))
2454 (goto-line (nth 1 eq
))
2455 (org-table-goto-column (nth 2 eq
))
2456 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
2457 'nostore
'noanalysis
))
2459 (goto-line thisline
)
2460 (org-table-goto-column thiscol
)
2461 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
2462 (or noalign
(and org-table-may-need-update
(org-table-align))
2463 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
2465 ;; back to initial position
2466 (message "Re-applying formulas...done")
2467 (goto-line thisline
)
2468 (org-table-goto-column thiscol
)
2469 (or noalign
(and org-table-may-need-update
(org-table-align))
2470 (and all
(message "Re-applying formulas...done"))))))
2472 (defun org-table-iterate (&optional arg
)
2473 "Recalculate the table until it does not change anymore."
2475 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
2477 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2482 (org-table-recalculate 'all
)
2483 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
2484 (if (not (string= lasttbl thistbl
))
2485 (setq lasttbl thistbl
)
2487 (message "Convergence after %d iterations" i
)
2488 (message "Table was already stable"))
2490 (error "No convergence after %d iterations" i
))))
2492 (defun org-table-formula-substitute-names (f)
2493 "Replace $const with values in string F."
2494 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
2495 ;; First, check for column names
2496 (while (setq start
(string-match org-table-column-name-regexp f start
))
2497 (setq start
(1+ start
))
2498 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
2499 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
2500 ;; Parameters and constants
2502 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start
))
2503 (setq start
(1+ start
))
2504 (if (setq a
(save-match-data
2505 (org-table-get-constant (match-string 1 f
))))
2506 (setq f
(replace-match
2507 (concat (if pp
"(") a
(if pp
")")) t t f
))))
2508 (if org-table-formula-debug
2509 (put-text-property 0 (length f
) :orig-formula f1 f
))
2512 (defun org-table-get-constant (const)
2513 "Find the value for a parameter or constant in a formula.
2514 Parameters get priority."
2515 (or (cdr (assoc const org-table-local-parameters
))
2516 (cdr (assoc const org-table-formula-constants-local
))
2517 (cdr (assoc const org-table-formula-constants
))
2518 (and (fboundp 'constants-get
) (constants-get const
))
2519 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
2520 (org-entry-get nil
(substring const
5) 'inherit
))
2523 (defvar org-table-fedit-map
2524 (let ((map (make-sparse-keymap)))
2525 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
2526 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
2527 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
2528 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
2529 (org-defkey map
"\C-c?" 'org-table-show-reference
)
2530 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
2531 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
2532 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
2533 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
2534 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
2535 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
2536 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
2537 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
2538 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
2539 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
2540 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
2541 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
2542 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
2543 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
2546 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
2548 ["Finish and Install" org-table-fedit-finish t
]
2549 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
2550 ["Abort" org-table-fedit-abort t
]
2552 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
2553 ["Complete Lisp Symbol" lisp-complete-symbol t
]
2555 "Shift Reference at Point"
2556 ["Up" org-table-fedit-ref-up t
]
2557 ["Down" org-table-fedit-ref-down t
]
2558 ["Left" org-table-fedit-ref-left t
]
2559 ["Right" org-table-fedit-ref-right t
]
2561 "Change Test Row for Column Formulas"
2562 ["Up" org-table-fedit-line-up t
]
2563 ["Down" org-table-fedit-line-down t
]
2565 ["Scroll Table Window" org-table-fedit-scroll t
]
2566 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
2567 ["Show Table Grid" org-table-fedit-toggle-coordinates
2568 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
2569 org-table-overlay-coordinates
)]
2571 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
2572 :style toggle
:selected org-table-buffer-is-an
]))
2576 (defun org-table-edit-formulas ()
2577 "Edit the formulas of the current table in a separate buffer."
2579 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
2580 (beginning-of-line 0))
2581 (unless (org-at-table-p) (error "Not at a table"))
2582 (org-table-get-specials)
2583 (let ((key (org-table-current-field-formula 'key
'noerror
))
2584 (eql (sort (org-table-get-stored-formulas 'noerror
)
2585 'org-table-formula-less-p
))
2586 (pos (move-marker (make-marker) (point)))
2588 (wc (current-window-configuration))
2589 (titles '((column .
"# Column Formulas\n")
2590 (field .
"# Field Formulas\n")
2591 (named .
"# Named Field Formulas\n")))
2593 (org-switch-to-buffer-other-window "*Edit Formulas*")
2595 ;; Keep global-font-lock-mode from turning on font-lock-mode
2596 (let ((font-lock-global-modes '(not fundamental-mode
)))
2598 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
2599 (org-set-local 'org-pos pos
)
2600 (org-set-local 'org-window-configuration wc
)
2601 (use-local-map org-table-fedit-map
)
2602 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
2603 (easy-menu-add org-table-fedit-menu
)
2604 (setq startline
(org-current-line))
2605 (while (setq entry
(pop eql
))
2607 ((equal (string-to-char (car entry
)) ?
@) 'field
)
2608 ((string-match "^[0-9]" (car entry
)) 'column
)
2610 (when (setq title
(assq type titles
))
2611 (or (bobp) (insert "\n"))
2612 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
2613 (setq titles
(delq title titles
)))
2614 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
2615 (setq s
(concat (if (equal (string-to-char (car entry
)) ?
@) "" "$")
2616 (car entry
) " = " (cdr entry
) "\n"))
2617 (remove-text-properties 0 (length s
) '(face nil
) s
)
2619 (if (eq org-table-use-standard-references t
)
2620 (org-table-fedit-toggle-ref-type))
2621 (goto-line startline
)
2622 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
2624 (defun org-table-fedit-post-command ()
2625 (when (not (memq this-command
'(lisp-complete-symbol)))
2626 (let ((win (selected-window)))
2629 (org-table-show-reference)
2631 (select-window win
)))))
2633 (defun org-table-formula-to-user (s)
2634 "Convert a formula from internal to user representation."
2635 (if (eq org-table-use-standard-references t
)
2636 (org-table-convert-refs-to-an s
)
2639 (defun org-table-formula-from-user (s)
2640 "Convert a formula from user to internal representation."
2641 (if org-table-use-standard-references
2642 (org-table-convert-refs-to-rc s
)
2645 (defun org-table-convert-refs-to-rc (s)
2646 "Convert spreadsheet references from AB7 to @7$28.
2647 Works for single references, but also for entire formulas and even the
2650 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start
)
2653 ;; format match, just advance
2654 (setq start
(match-end 0)))
2655 ((and (> (match-beginning 0) 0)
2656 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
2657 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
2658 ;; 3.e5 or something like this.
2659 (setq start
(match-end 0)))
2661 (setq start
(match-beginning 0)
2663 (if (equal (match-string 2 s
) "&")
2664 (format "$%d" (org-letters-to-number (match-string 1 s
)))
2666 (string-to-number (match-string 2 s
))
2667 (org-letters-to-number (match-string 1 s
))))
2671 (defun org-table-convert-refs-to-an (s)
2672 "Convert spreadsheet references from to @7$28 to AB7.
2673 Works for single references, but also for entire formulas and even the
2675 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
2676 (setq s
(replace-match
2678 (org-number-to-letters
2679 (string-to-number (match-string 2 s
)))
2680 (string-to-number (match-string 1 s
)))
2682 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
2683 (setq s
(replace-match (concat "\\1"
2684 (org-number-to-letters
2685 (string-to-number (match-string 2 s
))) "&")
2689 (defun org-letters-to-number (s)
2690 "Convert a base 26 number represented by letters into an integer.
2691 For example: AB -> 28."
2694 (while (> (length s
) 0)
2695 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
2699 (defun org-number-to-letters (n)
2700 "Convert an integer into a base 26 number represented by letters.
2701 For example: 28 -> AB."
2704 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
2708 (defun org-table-fedit-convert-buffer (function)
2709 "Convert all references in this buffer, using FUNCTION."
2710 (let ((line (org-current-line)))
2711 (goto-char (point-min))
2713 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
2714 (delete-region (point) (point-at-eol))
2715 (or (eobp) (forward-char 1)))
2718 (defun org-table-fedit-toggle-ref-type ()
2719 "Convert all references in the buffer from B3 to @3$2 and back."
2721 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
2722 (org-table-fedit-convert-buffer
2723 (if org-table-buffer-is-an
2724 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
2725 (message "Reference type switched to %s"
2726 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
2728 (defun org-table-fedit-ref-up ()
2729 "Shift the reference at point one row/hline up."
2731 (org-table-fedit-shift-reference 'up
))
2732 (defun org-table-fedit-ref-down ()
2733 "Shift the reference at point one row/hline down."
2735 (org-table-fedit-shift-reference 'down
))
2736 (defun org-table-fedit-ref-left ()
2737 "Shift the reference at point one field to the left."
2739 (org-table-fedit-shift-reference 'left
))
2740 (defun org-table-fedit-ref-right ()
2741 "Shift the reference at point one field to the right."
2743 (org-table-fedit-shift-reference 'right
))
2745 (defun org-table-fedit-shift-reference (dir)
2747 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
2748 (if (memq dir
'(left right
))
2749 (org-rematch-and-replace 1 (eq dir
'left
))
2750 (error "Cannot shift reference in this direction")))
2751 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
2752 ;; A B3-like reference
2753 (if (memq dir
'(up down
))
2754 (org-rematch-and-replace 2 (eq dir
'up
))
2755 (org-rematch-and-replace 1 (eq dir
'left
))))
2757 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
2758 ;; An internal reference
2759 (if (memq dir
'(up down
))
2760 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
2761 (org-rematch-and-replace 5 (eq dir
'left
))))))
2763 (defun org-rematch-and-replace (n &optional decr hline
)
2764 "Re-match the group N, and replace it with the shifted refrence."
2765 (or (match-end n
) (error "Cannot shift reference in this direction"))
2766 (goto-char (match-beginning n
))
2767 (and (looking-at (regexp-quote (match-string n
)))
2768 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
2771 (defun org-table-shift-refpart (ref &optional decr hline
)
2772 "Shift a refrence part REF.
2773 If DECR is set, decrease the references row/column, else increase.
2774 If HLINE is set, this may be a hline reference, it certainly is not
2775 a translation reference."
2777 (let* ((sign (string-match "^[-+]" ref
)) n
)
2779 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
2781 ((and hline
(string-match "^I+" ref
))
2782 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
2783 (setq n
(+ n
(if decr -
1 1)))
2784 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
2786 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
2788 (concat sign
(make-string n ?I
)))
2790 ((string-match "^[0-9]+" ref
)
2791 (setq n
(string-to-number (concat sign ref
)))
2792 (setq n
(+ n
(if decr -
1 1)))
2794 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
2795 (number-to-string (max 1 n
))))
2797 ((string-match "^[a-zA-Z]+" ref
)
2798 (org-number-to-letters
2799 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
2801 (t (error "Cannot shift reference"))))))
2803 (defun org-table-fedit-toggle-coordinates ()
2804 "Toggle the display of coordinates in the referenced table."
2806 (let ((pos (marker-position org-pos
)))
2807 (with-current-buffer (marker-buffer org-pos
)
2810 (org-table-toggle-coordinate-overlays)))))
2812 (defun org-table-fedit-finish (&optional arg
)
2813 "Parse the buffer for formula definitions and install them.
2814 With prefix ARG, apply the new formulas to the table."
2816 (org-table-remove-rectangle-highlight)
2817 (if org-table-use-standard-references
2819 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
2820 (setq org-table-buffer-is-an nil
)))
2821 (let ((pos org-pos
) eql var form
)
2822 (goto-char (point-min))
2823 (while (re-search-forward
2824 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
2826 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
2827 form
(match-string 3))
2828 (setq form
(org-trim form
))
2829 (when (not (equal form
""))
2830 (while (string-match "[ \t]*\n[ \t]*" form
)
2831 (setq form
(replace-match " " t t form
)))
2832 (when (assoc var eql
)
2833 (error "Double formulas for %s" var
))
2834 (push (cons var form
) eql
)))
2836 (set-window-configuration org-window-configuration
)
2837 (select-window (get-buffer-window (marker-buffer pos
)))
2839 (unless (org-at-table-p)
2840 (error "Lost table position - cannot install formulae"))
2841 (org-table-store-formulas eql
)
2842 (move-marker pos nil
)
2843 (kill-buffer "*Edit Formulas*")
2845 (org-table-recalculate 'all
)
2846 (message "New formulas installed - press C-u C-c C-c to apply."))))
2848 (defun org-table-fedit-abort ()
2849 "Abort editing formulas, without installing the changes."
2851 (org-table-remove-rectangle-highlight)
2852 (let ((pos org-pos
))
2853 (set-window-configuration org-window-configuration
)
2854 (select-window (get-buffer-window (marker-buffer pos
)))
2856 (move-marker pos nil
)
2857 (message "Formula editing aborted without installing changes")))
2859 (defun org-table-fedit-lisp-indent ()
2860 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
2862 (let ((pos (point)) beg end ind
)
2863 (beginning-of-line 1)
2865 ((looking-at "[ \t]")
2867 (call-interactively 'lisp-indent-line
))
2868 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
2869 ((not (fboundp 'pp-buffer
))
2870 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
2871 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
2872 (goto-char (- (match-end 0) 2))
2874 (setq ind
(make-string (current-column) ?\
))
2875 (condition-case nil
(forward-sexp 1)
2877 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
2880 (narrow-to-region beg end
)
2881 (if (eq last-command this-command
)
2883 (goto-char (point-min))
2884 (setq this-command nil
)
2885 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
2886 (replace-match " ")))
2888 (untabify (point-min) (point-max))
2889 (goto-char (1+ (point-min)))
2890 (while (re-search-forward "^." nil t
)
2891 (beginning-of-line 1)
2893 (goto-char (point-max))
2894 (backward-delete-char 1)))
2898 (defvar org-show-positions nil
)
2900 (defun org-table-show-reference (&optional local
)
2901 "Show the location/value of the $ expression at point."
2903 (org-table-remove-rectangle-highlight)
2905 (let ((pos (if local
(point) org-pos
))
2907 (org-inhibit-highlight-removal t
)
2908 (win (selected-window))
2909 (org-show-positions nil
)
2910 var name e what match dest
)
2911 (if local
(org-table-get-specials))
2913 ((or (org-at-regexp-p org-table-range-regexp2
)
2914 (org-at-regexp-p org-table-translate-regexp
)
2915 (org-at-regexp-p org-table-range-regexp
))
2918 (org-table-convert-refs-to-rc (match-string 0))))
2920 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
2921 ((org-at-regexp-p "\\$[0-9]+") 'column
)
2923 (t (error "No reference at point")))
2924 match
(and what
(or match
(match-string 0))))
2925 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
2926 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
2927 'secondary-selection
))
2928 (org-add-hook 'before-change-functions
2929 'org-table-remove-rectangle-highlight
)
2930 (if (eq what
'name
) (setq var
(substring match
1)))
2931 (when (eq what
'range
)
2932 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
2933 (setq match
(org-table-formula-substitute-names match
)))
2937 (re-search-backward "^\\S-" nil t
)
2938 (beginning-of-line 1)
2939 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
2942 (org-table-convert-refs-to-rc (match-string 1))))
2943 (org-table-add-rectangle-overlay
2944 (match-beginning 1) (match-end 1) face2
))))
2945 (if (and (markerp pos
) (marker-buffer pos
))
2946 (if (get-buffer-window (marker-buffer pos
))
2947 (select-window (get-buffer-window (marker-buffer pos
)))
2948 (org-switch-to-buffer-other-window (get-buffer-window
2949 (marker-buffer pos
)))))
2951 (org-table-force-dataline)
2953 (setq name
(substring dest
1))
2955 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
2956 (setq e
(assoc name org-table-named-field-locations
))
2957 (goto-line (nth 1 e
))
2958 (org-table-goto-column (nth 2 e
)))
2959 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
2960 (let ((l (string-to-number (match-string 1 dest
)))
2961 (c (string-to-number (match-string 2 dest
))))
2962 (goto-line (aref org-table-dlines l
))
2963 (org-table-goto-column c
)))
2964 (t (org-table-goto-column (string-to-number name
))))
2965 (move-marker pos
(point))
2966 (org-table-highlight-rectangle nil nil face2
))
2968 ((equal dest match
))
2973 (org-table-get-range match nil nil
'highlight
))
2975 ((setq e
(assoc var org-table-named-field-locations
))
2976 (goto-line (nth 1 e
))
2977 (org-table-goto-column (nth 2 e
))
2978 (org-table-highlight-rectangle (point) (point))
2979 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
2980 ((setq e
(assoc var org-table-column-names
))
2981 (org-table-goto-column (string-to-number (cdr e
)))
2982 (org-table-highlight-rectangle (point) (point))
2983 (goto-char (org-table-begin))
2984 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
2987 (goto-char (match-beginning 1))
2988 (org-table-highlight-rectangle)
2989 (message "Named column (column %s)" (cdr e
)))
2990 (error "Column name not found")))
2993 (org-table-goto-column (string-to-number (substring match
1)))
2994 (org-table-highlight-rectangle (point) (point))
2995 (message "Column %s" (substring match
1)))
2996 ((setq e
(assoc var org-table-local-parameters
))
2997 (goto-char (org-table-begin))
2998 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3000 (goto-char (match-beginning 1))
3001 (org-table-highlight-rectangle)
3002 (message "Local parameter."))
3003 (error "Parameter not found")))
3006 ((not var
) (error "No reference at point"))
3007 ((setq e
(assoc var org-table-formula-constants-local
))
3008 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3010 ((setq e
(assoc var org-table-formula-constants
))
3011 (message "Constant: $%s=%s in `org-table-formula-constants'."
3013 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3014 (message "Constant: $%s=%s, from `constants.el'%s."
3015 var e
(format " (%s units)" constants-unit-system
)))
3016 (t (error "Undefined name $%s" var
)))))
3018 (when (and org-show-positions
3019 (not (memq this-command
'(org-table-fedit-scroll
3020 org-table-fedit-scroll-down
))))
3021 (push pos org-show-positions
)
3022 (push org-table-current-begin-pos org-show-positions
)
3023 (let ((min (apply 'min org-show-positions
))
3024 (max (apply 'max org-show-positions
)))
3025 (goto-char min
) (recenter 0)
3027 (or (pos-visible-in-window-p max
) (recenter -
1))))
3028 (select-window win
))))
3030 (defun org-table-force-dataline ()
3031 "Make sure the cursor is in a dataline in a table."
3032 (unless (save-excursion
3033 (beginning-of-line 1)
3034 (looking-at org-table-dataline-regexp
))
3035 (let* ((re org-table-dataline-regexp
)
3036 (p1 (save-excursion (re-search-forward re nil
'move
)))
3037 (p2 (save-excursion (re-search-backward re nil
'move
))))
3039 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3041 ((or p1 p2
) (goto-char (or p1 p2
)))
3042 (t (error "No table dataline around here"))))))
3044 (defun org-table-fedit-line-up ()
3045 "Move cursor one line up in the window showing the table."
3047 (org-table-fedit-move 'previous-line
))
3049 (defun org-table-fedit-line-down ()
3050 "Move cursor one line down in the window showing the table."
3052 (org-table-fedit-move 'next-line
))
3054 (defun org-table-fedit-move (command)
3055 "Move the cursor in the window showing the table.
3056 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3057 (let ((org-table-allow-automatic-line-recalculation nil
)
3058 (pos org-pos
) (win (selected-window)) p
)
3059 (select-window (get-buffer-window (marker-buffer org-pos
)))
3061 (call-interactively command
)
3062 (while (and (org-at-table-p)
3063 (org-at-table-hline-p))
3064 (call-interactively command
))
3065 (or (org-at-table-p) (goto-char p
))
3066 (move-marker pos
(point))
3067 (select-window win
)))
3069 (defun org-table-fedit-scroll (N)
3071 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3072 (scroll-other-window N
)))
3074 (defun org-table-fedit-scroll-down (N)
3076 (org-table-fedit-scroll (- N
)))
3078 (defvar org-table-rectangle-overlays nil
)
3080 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3081 "Add a new overlay."
3082 (let ((ov (org-make-overlay beg end
)))
3083 (org-overlay-put ov
'face
(or face
'secondary-selection
))
3084 (push ov org-table-rectangle-overlays
)))
3086 (defun org-table-highlight-rectangle (&optional beg end face
)
3087 "Highlight rectangular region in a table."
3088 (setq beg
(or beg
(point)) end
(or end
(point)))
3089 (let ((b (min beg end
))
3092 (and (boundp 'org-show-positions
)
3093 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3094 (goto-char (min beg end
))
3095 (setq l1
(org-current-line)
3096 c1
(org-table-current-column))
3097 (goto-char (max beg end
))
3098 (setq l2
(org-current-line)
3099 c2
(org-table-current-column))
3100 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3102 (beginning-of-line 1)
3103 (loop for line from l1 to l2 do
3104 (when (looking-at org-table-dataline-regexp
)
3105 (org-table-goto-column c1
)
3106 (skip-chars-backward "^|\n") (setq beg
(point))
3107 (org-table-goto-column c2
)
3108 (skip-chars-forward "^|\n") (setq end
(point))
3109 (org-table-add-rectangle-overlay beg end face
))
3110 (beginning-of-line 2))
3112 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3114 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3115 "Remove the rectangle overlays."
3116 (unless org-inhibit-highlight-removal
3117 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3118 (mapc 'org-delete-overlay org-table-rectangle-overlays
)
3119 (setq org-table-rectangle-overlays nil
)))
3121 (defvar org-table-coordinate-overlays nil
3122 "Collects the coordinate grid overlays, so that they can be removed.")
3123 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3125 (defun org-table-overlay-coordinates ()
3126 "Add overlays to the table at point, to show row/column coordinates."
3128 (mapc 'org-delete-overlay org-table-coordinate-overlays
)
3129 (setq org-table-coordinate-overlays nil
)
3131 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3132 (goto-char (org-table-begin))
3133 (while (org-at-table-p)
3134 (setq eol
(point-at-eol))
3135 (setq ov
(org-make-overlay (point-at-bol) (1+ (point-at-bol))))
3136 (push ov org-table-coordinate-overlays
)
3137 (setq hline
(looking-at org-table-hline-regexp
))
3138 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3139 (format "%4d" (setq id
(1+ id
)))))
3140 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3143 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3144 (setq beg
(1+ (match-beginning 0))
3146 s1
(concat "$" (int-to-string ic
))
3147 s2
(org-number-to-letters ic
)
3148 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3149 (setq ov
(org-make-overlay beg
(+ beg
(length str
))))
3150 (push ov org-table-coordinate-overlays
)
3151 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3152 (beginning-of-line 2)))))
3154 (defun org-table-toggle-coordinate-overlays ()
3155 "Toggle the display of Row/Column numbers in tables."
3157 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3158 (message "Row/Column number display turned %s"
3159 (if org-table-overlay-coordinates
"on" "off"))
3160 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3162 (unless org-table-overlay-coordinates
3163 (mapc 'org-delete-overlay org-table-coordinate-overlays
)
3164 (setq org-table-coordinate-overlays nil
)))
3166 (defun org-table-toggle-formula-debugger ()
3167 "Toggle the formula debugger in tables."
3169 (setq org-table-formula-debug
(not org-table-formula-debug
))
3170 (message "Formula debugging has been turned %s"
3171 (if org-table-formula-debug
"on" "off")))
3173 ;;; The orgtbl minor mode
3175 ;; Define a minor mode which can be used in other modes in order to
3176 ;; integrate the org-mode table editor.
3178 ;; This is really a hack, because the org-mode table editor uses several
3179 ;; keys which normally belong to the major mode, for example the TAB and
3180 ;; RET keys. Here is how it works: The minor mode defines all the keys
3181 ;; necessary to operate the table editor, but wraps the commands into a
3182 ;; function which tests if the cursor is currently inside a table. If that
3183 ;; is the case, the table editor command is executed. However, when any of
3184 ;; those keys is used outside a table, the function uses `key-binding' to
3185 ;; look up if the key has an associated command in another currently active
3186 ;; keymap (minor modes, major mode, global), and executes that command.
3187 ;; There might be problems if any of the keys used by the table editor is
3188 ;; otherwise used as a prefix key.
3190 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3191 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3192 ;; addresses this by checking explicitly for both bindings.
3194 ;; The optimized version (see variable `orgtbl-optimized') takes over
3195 ;; all keys which are bound to `self-insert-command' in the *global map*.
3196 ;; Some modes bind other commands to simple characters, for example
3197 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3198 ;; active, this binding is ignored inside tables and replaced with a
3199 ;; modified self-insert.
3201 (defvar orgtbl-mode nil
3202 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
3203 table editor in arbitrary modes.")
3204 (make-variable-buffer-local 'orgtbl-mode
)
3206 (defvar orgtbl-mode-map
(make-keymap)
3207 "Keymap for `orgtbl-mode'.")
3210 (defun turn-on-orgtbl ()
3211 "Unconditionally turn on `orgtbl-mode'."
3214 (defvar org-old-auto-fill-inhibit-regexp nil
3215 "Local variable used by `orgtbl-mode'")
3217 (defconst orgtbl-line-start-regexp
"[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
3218 "Matches a line belonging to an orgtbl.")
3220 (defconst orgtbl-extra-font-lock-keywords
3221 (list (list (concat "^" orgtbl-line-start-regexp
".*")
3222 0 (quote 'org-table
) 'prepend
))
3223 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
3226 (defun orgtbl-mode (&optional arg
)
3227 "The `org-mode' table editor as a minor mode for use in other modes."
3229 (org-load-modules-maybe)
3231 ;; Exit without error, in case some hook functions calls this
3232 ;; by accident in org-mode.
3233 (message "Orgtbl-mode is not useful in org-mode, command ignored")
3235 (if arg
(> (prefix-numeric-value arg
) 0) (not orgtbl-mode
)))
3238 (and (orgtbl-setup) (defun orgtbl-setup () nil
))
3239 ;; Make sure we are first in minor-mode-map-alist
3240 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
3241 (and c
(setq minor-mode-map-alist
3242 (cons c
(delq c minor-mode-map-alist
)))))
3243 (org-set-local (quote org-table-may-need-update
) t
)
3244 (org-add-hook 'before-change-functions
'org-before-change-function
3246 (org-set-local 'org-old-auto-fill-inhibit-regexp
3247 auto-fill-inhibit-regexp
)
3248 (org-set-local 'auto-fill-inhibit-regexp
3249 (if auto-fill-inhibit-regexp
3250 (concat orgtbl-line-start-regexp
"\\|"
3251 auto-fill-inhibit-regexp
)
3252 orgtbl-line-start-regexp
))
3253 (org-add-to-invisibility-spec '(org-cwidth))
3254 (when (fboundp 'font-lock-add-keywords
)
3255 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
3256 (org-restart-font-lock))
3257 (easy-menu-add orgtbl-mode-menu
)
3258 (run-hooks 'orgtbl-mode-hook
))
3259 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
3260 (org-table-cleanup-narrow-column-properties)
3261 (org-remove-from-invisibility-spec '(org-cwidth))
3262 (remove-hook 'before-change-functions
'org-before-change-function t
)
3263 (when (fboundp 'font-lock-remove-keywords
)
3264 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
3265 (org-restart-font-lock))
3266 (easy-menu-remove orgtbl-mode-menu
)
3267 (force-mode-line-update 'all
))))
3269 (defun org-table-cleanup-narrow-column-properties ()
3270 "Remove all properties related to narrow-column invisibility."
3272 (while (setq s
(text-property-any s
(point-max)
3273 'display org-narrow-column-arrow
))
3274 (remove-text-properties s
(1+ s
) '(display t
)))
3276 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
3277 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
3279 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
3280 (remove-text-properties s
(1+ s
) '(invisible t
)))))
3282 ;; Install it as a minor mode.
3283 (put 'orgtbl-mode
:included t
)
3284 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
3285 (add-minor-mode 'orgtbl-mode
" OrgTbl" orgtbl-mode-map
)
3287 (defun orgtbl-make-binding (fun n
&rest keys
)
3288 "Create a function for binding in the table minor mode.
3289 FUN is the command to call inside a table. N is used to create a unique
3290 command name. KEYS are keys that should be checked in for a command
3291 to execute outside of tables."
3294 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
3296 (concat "In tables, run `" (symbol-name fun
) "'.\n"
3297 "Outside of tables, run the binding of `"
3298 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
3303 (list 'call-interactively
(list 'quote fun
))
3304 (list 'let
'(orgtbl-mode)
3305 (list 'call-interactively
3308 (list 'key-binding k
))
3310 '('orgtbl-error
))))))))
3312 (defun orgtbl-error ()
3313 "Error when there is no default binding for a table key."
3315 (error "This key has no function outside tables"))
3317 (defun orgtbl-setup ()
3318 "Setup orgtbl keymaps."
3322 '([(meta shift left
)] org-table-delete-column
)
3323 '([(meta left
)] org-table-move-column-left
)
3324 '([(meta right
)] org-table-move-column-right
)
3325 '([(meta shift right
)] org-table-insert-column
)
3326 '([(meta shift up
)] org-table-kill-row
)
3327 '([(meta shift down
)] org-table-insert-row
)
3328 '([(meta up
)] org-table-move-row-up
)
3329 '([(meta down
)] org-table-move-row-down
)
3330 '("\C-c\C-w" org-table-cut-region
)
3331 '("\C-c\M-w" org-table-copy-region
)
3332 '("\C-c\C-y" org-table-paste-rectangle
)
3333 '("\C-c-" org-table-insert-hline
)
3334 '("\C-c}" org-table-toggle-coordinate-overlays
)
3335 '("\C-c{" org-table-toggle-formula-debugger
)
3336 '("\C-m" org-table-next-row
)
3337 '([(shift return
)] org-table-copy-down
)
3338 '("\C-c?" org-table-field-info
)
3339 '("\C-c " org-table-blank-field
)
3340 '("\C-c+" org-table-sum
)
3341 '("\C-c=" org-table-eval-formula
)
3342 '("\C-c'" org-table-edit-formulas
)
3343 '("\C-c`" org-table-edit-field
)
3344 '("\C-c*" org-table-recalculate
)
3345 '("\C-c^" org-table-sort-lines
)
3346 '([(control ?
#)] org-table-rotate-recalc-marks
)))
3348 (while (setq elt
(pop bindings
))
3349 (setq nfunc
(1+ nfunc
))
3350 (setq key
(org-key (car elt
))
3352 cmd
(orgtbl-make-binding fun nfunc key
))
3353 (org-defkey orgtbl-mode-map key cmd
))
3355 ;; Special treatment needed for TAB and RET
3356 (org-defkey orgtbl-mode-map
[(return)]
3357 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
3358 (org-defkey orgtbl-mode-map
"\C-m"
3359 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
3361 (org-defkey orgtbl-mode-map
[(tab)]
3362 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
3363 (org-defkey orgtbl-mode-map
"\C-i"
3364 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
3366 (org-defkey orgtbl-mode-map
[(shift tab
)]
3367 (orgtbl-make-binding 'org-table-previous-field
104
3368 [(shift tab
)] [(tab)] "\C-i"))
3370 (org-defkey orgtbl-mode-map
"\M-\C-m"
3371 (orgtbl-make-binding 'org-table-wrap-region
105
3372 "\M-\C-m" [(meta return
)]))
3373 (org-defkey orgtbl-mode-map
[(meta return
)]
3374 (orgtbl-make-binding 'org-table-wrap-region
106
3375 [(meta return
)] "\M-\C-m"))
3377 (org-defkey orgtbl-mode-map
"\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c
)
3378 (org-defkey orgtbl-mode-map
"\C-c|" 'orgtbl-create-or-convert-from-region
)
3380 (when orgtbl-optimized
3381 ;; If the user wants maximum table support, we need to hijack
3382 ;; some standard editing functions
3383 (org-remap orgtbl-mode-map
3384 'self-insert-command
'orgtbl-self-insert-command
3385 'delete-char
'org-delete-char
3386 'delete-backward-char
'org-delete-backward-char
)
3387 (org-defkey orgtbl-mode-map
"|" 'org-force-self-insert
))
3388 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map
"OrgTbl menu"
3390 ["Create or convert" org-table-create-or-convert-from-region
3391 :active
(not (org-at-table-p)) :keys
"C-c |" ]
3393 ["Align" org-ctrl-c-ctrl-c
:active
(org-at-table-p) :keys
"C-c C-c"]
3394 ["Next Field" org-cycle
:active
(org-at-table-p) :keys
"TAB"]
3395 ["Previous Field" org-shifttab
:active
(org-at-table-p) :keys
"S-TAB"]
3396 ["Next Row" org-return
:active
(org-at-table-p) :keys
"RET"]
3398 ["Blank Field" org-table-blank-field
:active
(org-at-table-p) :keys
"C-c SPC"]
3399 ["Edit Field" org-table-edit-field
:active
(org-at-table-p) :keys
"C-c ` "]
3400 ["Copy Field from Above"
3401 org-table-copy-down
:active
(org-at-table-p) :keys
"S-RET"]
3404 ["Move Column Left" org-metaleft
:active
(org-at-table-p) :keys
"M-<left>"]
3405 ["Move Column Right" org-metaright
:active
(org-at-table-p) :keys
"M-<right>"]
3406 ["Delete Column" org-shiftmetaleft
:active
(org-at-table-p) :keys
"M-S-<left>"]
3407 ["Insert Column" org-shiftmetaright
:active
(org-at-table-p) :keys
"M-S-<right>"])
3409 ["Move Row Up" org-metaup
:active
(org-at-table-p) :keys
"M-<up>"]
3410 ["Move Row Down" org-metadown
:active
(org-at-table-p) :keys
"M-<down>"]
3411 ["Delete Row" org-shiftmetaup
:active
(org-at-table-p) :keys
"M-S-<up>"]
3412 ["Insert Row" org-shiftmetadown
:active
(org-at-table-p) :keys
"M-S-<down>"]
3413 ["Sort lines in region" org-table-sort-lines
:active
(org-at-table-p) :keys
"C-c ^"]
3415 ["Insert Hline" org-table-insert-hline
:active
(org-at-table-p) :keys
"C-c -"])
3417 ["Copy Rectangle" org-copy-special
:active
(org-at-table-p)]
3418 ["Cut Rectangle" org-cut-special
:active
(org-at-table-p)]
3419 ["Paste Rectangle" org-paste-special
:active
(org-at-table-p)]
3420 ["Fill Rectangle" org-table-wrap-region
:active
(org-at-table-p)])
3423 ["Insert table template" orgtbl-insert-radio-table
3424 (assq major-mode orgtbl-radio-table-templates
)]
3425 ["Comment/uncomment table" orgtbl-toggle-comment t
])
3427 ["Set Column Formula" org-table-eval-formula
:active
(org-at-table-p) :keys
"C-c ="]
3428 ["Set Field Formula" (org-table-eval-formula '(4)) :active
(org-at-table-p) :keys
"C-u C-c ="]
3429 ["Edit Formulas" org-table-edit-formulas
:active
(org-at-table-p) :keys
"C-c '"]
3430 ["Recalculate line" org-table-recalculate
:active
(org-at-table-p) :keys
"C-c *"]
3431 ["Recalculate all" (org-table-recalculate '(4)) :active
(org-at-table-p) :keys
"C-u C-c *"]
3432 ["Iterate all" (org-table-recalculate '(16)) :active
(org-at-table-p) :keys
"C-u C-u C-c *"]
3433 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks
:active
(org-at-table-p) :keys
"C-c #"]
3434 ["Sum Column/Rectangle" org-table-sum
3435 :active
(or (org-at-table-p) (org-region-active-p)) :keys
"C-c +"]
3436 ["Which Column?" org-table-current-column
:active
(org-at-table-p) :keys
"C-c ?"]
3438 org-table-toggle-formula-debugger
:active
(org-at-table-p)
3440 :style toggle
:selected org-table-formula-debug
]
3441 ["Show Col/Row Numbers"
3442 org-table-toggle-coordinate-overlays
:active
(org-at-table-p)
3444 :style toggle
:selected org-table-overlay-coordinates
]
3448 (defun orgtbl-ctrl-c-ctrl-c (arg)
3449 "If the cursor is inside a table, realign the table.
3450 It it is a table to be sent away to a receiver, do it.
3451 With prefix arg, also recompute table."
3453 (let ((pos (point)) action
)
3455 (beginning-of-line 1)
3456 (setq action
(cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
3457 ((looking-at "[ \t]*|") pos
)
3458 ((looking-at "#\\+TBLFM:") 'recalc
))))
3462 (org-table-maybe-eval-formula)
3464 (call-interactively 'org-table-recalculate
)
3465 (org-table-maybe-recalculate-line))
3466 (call-interactively 'org-table-align
)
3467 (orgtbl-send-table 'maybe
))
3468 ((eq action
'recalc
)
3470 (beginning-of-line 1)
3471 (skip-chars-backward " \r\n\t")
3472 (if (org-at-table-p)
3473 (org-call-with-arg 'org-table-recalculate t
))))
3474 (t (let (orgtbl-mode)
3475 (call-interactively (key-binding "\C-c\C-c")))))))
3477 (defun orgtbl-create-or-convert-from-region (arg)
3478 "Create table or convert region to table, if no conflicting binding.
3479 This installs the table binding `C-c |', but only if there is no
3480 conflicting binding to this key outside orgtbl-mode."
3482 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
3484 (call-interactively cmd
)
3485 (call-interactively 'org-table-create-or-convert-from-region
))))
3487 (defun orgtbl-tab (arg)
3488 "Justification and field motion for `orgtbl-mode'."
3490 (if arg
(org-table-edit-field t
)
3491 (org-table-justify-field-maybe)
3492 (org-table-next-field)))
3494 (defun orgtbl-ret ()
3495 "Justification and field motion for `orgtbl-mode'."
3499 (org-table-justify-field-maybe)
3500 (org-table-next-row)))
3502 (defun orgtbl-self-insert-command (N)
3503 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
3504 If the cursor is in a table looking at whitespace, the whitespace is
3505 overwritten, and the table is not marked as requiring realignment."
3507 (if (and (org-at-table-p)
3509 (and org-table-auto-blank-field
3510 (member last-command
3511 '(orgtbl-hijacker-command-100
3512 orgtbl-hijacker-command-101
3513 orgtbl-hijacker-command-102
3514 orgtbl-hijacker-command-103
3515 orgtbl-hijacker-command-104
3516 orgtbl-hijacker-command-105
))
3517 (org-table-blank-field))
3520 (looking-at "[^|\n]* +|"))
3521 (let (org-table-may-need-update)
3522 (goto-char (1- (match-end 0)))
3523 (delete-backward-char 1)
3524 (goto-char (match-beginning 0))
3525 (self-insert-command N
))
3526 (setq org-table-may-need-update t
)
3527 (let (orgtbl-mode a
)
3530 (or (and (listp function-key-map
)
3531 (setq a
(assoc last-input-event function-key-map
))
3533 (vector last-input-event
)))
3534 'self-insert-command
)))))
3536 (defvar orgtbl-exp-regexp
"^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
3537 "Regular expression matching exponentials as produced by calc.")
3539 (defun orgtbl-export (table target
)
3541 (let ((func (intern (concat "orgtbl-to-" (symbol-name target
))))
3542 (lines (org-split-string table
"[ \t]*\n[ \t]*"))
3543 org-table-last-alignment org-table-last-column-widths
3545 (if (not (fboundp func
))
3546 (error "Cannot export orgtbl table to %s" target
))
3547 (setq lines
(org-table-clean-before-export lines
))
3551 (if (string-match org-table-hline-regexp x
)
3553 (org-split-string (org-trim x
) "\\s-*|\\s-*")))
3555 (setq maxcol
(apply 'max
(mapcar (lambda (x) (if (listp x
) (length x
) 0))
3557 (loop for i from
(1- maxcol
) downto
0 do
3558 (setq column
(mapcar (lambda (x) (if (listp x
) (nth i x
) nil
)) table
))
3559 (setq column
(delq nil column
))
3560 (push (apply 'max
(mapcar 'string-width column
)) org-table-last-column-widths
)
3561 (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
))
3562 (funcall func table nil
)))
3564 (defun orgtbl-gather-send-defs ()
3565 "Gathers a plist of :name, :transform, :params for each destination before
3568 (goto-char (org-table-begin))
3570 (beginning-of-line 0)
3571 (while (looking-at "#\\+ORGTBL[: \t][ \t]*SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
3572 (let ((name (org-no-properties (match-string 1)))
3573 (transform (intern (match-string 2)))
3574 (params (if (match-end 3)
3575 (read (concat "(" (match-string 3) ")")))))
3576 (push (list :name name
:transform transform
:params params
)
3578 (beginning-of-line 0)))
3581 (defun orgtbl-send-replace-tbl (name txt
)
3582 "Find and replace table NAME with TXT."
3584 (goto-char (point-min))
3585 (unless (re-search-forward
3586 (concat "BEGIN RECEIVE ORGTBL +" name
"\\([ \t]\\|$\\)") nil t
)
3587 (error "Don't know where to insert translated table"))
3588 (goto-char (match-beginning 0))
3589 (beginning-of-line 2)
3591 (let ((beg (point)))
3592 (unless (re-search-forward
3593 (concat "END RECEIVE ORGTBL +" name
) nil t
)
3594 (error "Cannot find end of insertion region"))
3595 (beginning-of-line 1)
3596 (delete-region beg
(point))))
3600 (defun org-table-to-lisp (&optional txt
)
3601 "Convert the table at point to a Lisp structure.
3602 The structure will be a list. Each item is either the symbol `hline'
3603 for a horizontal separator line, or a list of field values as strings.
3604 The table is taken from the parameter TXT, or from the buffer at point."
3606 (unless (org-at-table-p)
3607 (error "No table at point")))
3609 (buffer-substring-no-properties (org-table-begin)
3611 (lines (org-split-string txt
"[ \t]*\n[ \t]*")))
3615 (if (string-match org-table-hline-regexp x
)
3617 (org-split-string (org-trim x
) "\\s-*|\\s-*")))
3620 (defun orgtbl-send-table (&optional maybe
)
3621 "Send a transformed version of this table to the receiver position.
3622 With argument MAYBE, fail quietly if no transformation is defined for
3626 (unless (org-at-table-p) (error "Not at a table"))
3627 ;; when non-interactive, we assume align has just happened.
3628 (when (interactive-p) (org-table-align))
3629 (let ((dests (orgtbl-gather-send-defs))
3630 (txt (buffer-substring-no-properties (org-table-begin)
3633 (unless dests
(if maybe
(throw 'exit nil
)
3634 (error "Don't know how to transform this table.")))
3635 (dolist (dest dests
)
3636 (let* ((name (plist-get dest
:name
))
3637 (transform (plist-get dest
:transform
))
3638 (params (plist-get dest
:params
))
3639 (skip (plist-get params
:skip
))
3640 (skipcols (plist-get params
:skipcols
))
3642 (lines (org-table-clean-before-export
3644 (org-split-string txt
"[ \t]*\n[ \t]*"))))
3645 (i0 (if org-table-clean-did-remove-column
2 1))
3648 (if (string-match org-table-hline-regexp x
)
3650 (org-remove-by-index
3651 (org-split-string (org-trim x
) "\\s-*|\\s-*")
3654 (fun (if (= i0
2) 'cdr
'identity
))
3655 (org-table-last-alignment
3656 (org-remove-by-index (funcall fun org-table-last-alignment
)
3658 (org-table-last-column-widths
3659 (org-remove-by-index (funcall fun org-table-last-column-widths
)
3661 (txt (if (fboundp transform
)
3662 (funcall transform table params
)
3663 (error "No such transformation function %s" transform
))))
3664 (orgtbl-send-replace-tbl name txt
))
3665 (setq ntbl
(1+ ntbl
)))
3666 (message "Table converted and installed at %d receiver location%s"
3667 ntbl
(if (> ntbl
1) "s" "")))))
3669 (defun org-remove-by-index (list indices
&optional i0
)
3670 "Remove the elements in LIST with indices in INDICES.
3671 First element has index 0, or I0 if given."
3674 (if (integerp indices
) (setq indices
(list indices
)))
3675 (setq i0
(1- (or i0
0)))
3676 (delq :rm
(mapcar (lambda (x)
3678 (if (memq i0 indices
) :rm x
))
3681 (defun orgtbl-toggle-comment ()
3682 "Comment or uncomment the orgtbl at point."
3684 (let* ((re1 (concat "^" (regexp-quote comment-start
) orgtbl-line-start-regexp
))
3685 (re2 (concat "^" orgtbl-line-start-regexp
))
3686 (commented (save-excursion (beginning-of-line 1)
3687 (cond ((looking-at re1
) t
)
3688 ((looking-at re2
) nil
)
3689 (t (error "Not at an org table")))))
3690 (re (if commented re1 re2
))
3693 (beginning-of-line 1)
3694 (while (looking-at re
) (beginning-of-line 0))
3695 (beginning-of-line 2)
3697 (while (looking-at re
) (beginning-of-line 2))
3699 (comment-region beg end
(if commented
'(4) nil
))))
3701 (defun orgtbl-insert-radio-table ()
3702 "Insert a radio table template appropriate for this major mode."
3704 (let* ((e (assq major-mode orgtbl-radio-table-templates
))
3707 (unless e
(error "No radio table setup defined for %s" major-mode
))
3708 (setq name
(read-string "Table name: "))
3709 (while (string-match "%n" txt
)
3710 (setq txt
(replace-match name t t txt
)))
3711 (or (bolp) (insert "\n"))
3716 ;; Dynamically bound input and output for table formatting.
3717 (defvar *orgtbl-table
* nil
3718 "Carries the current table through formatting routines.")
3719 (defvar *orgtbl-rtn
* nil
3720 "Formatting routines push the output lines here.")
3721 ;; Formatting parameters for the current table section.
3722 (defvar *orgtbl-hline
* nil
"Text used for horizontal lines")
3723 (defvar *orgtbl-sep
* nil
"Text used as a column separator")
3724 (defvar *orgtbl-default-fmt
* nil
"Default format for each entry")
3725 (defvar *orgtbl-fmt
* nil
"Format for each entry")
3726 (defvar *orgtbl-efmt
* nil
"Format for numbers")
3727 (defvar *orgtbl-lfmt
* nil
"Format for an entire line, overrides fmt")
3728 (defvar *orgtbl-llfmt
* nil
"Specializes lfmt for the last row")
3729 (defvar *orgtbl-lstart
* nil
"Text starting a row")
3730 (defvar *orgtbl-llstart
* nil
"Specializes lstart for the last row")
3731 (defvar *orgtbl-lend
* nil
"Text ending a row")
3732 (defvar *orgtbl-llend
* nil
"Specializes lend for the last row")
3734 (defsubst orgtbl-get-fmt
(fmt i
)
3735 "Retrieve the format from FMT corresponding to the Ith column."
3736 (if (and (not (functionp fmt
)) (consp fmt
))
3740 (defsubst orgtbl-apply-fmt
(fmt &rest args
)
3741 "Apply format FMT to the arguments. NIL FMTs return the first argument."
3742 (cond ((functionp fmt
) (apply fmt args
))
3743 (fmt (apply 'format fmt args
))
3747 (defsubst orgtbl-eval-str
(str)
3748 "If STR is a function, evaluate it with no arguments."
3753 (defun orgtbl-format-line (line)
3754 "Format LINE as a table row."
3755 (if (eq line
'hline
) (if *orgtbl-hline
* (push *orgtbl-hline
* *orgtbl-rtn
*))
3761 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt
* i
))
3762 (f (if (and efmt
(string-match orgtbl-exp-regexp f
))
3763 (orgtbl-apply-fmt efmt
(match-string 1 f
)
3766 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt
* i
)
3767 *orgtbl-default-fmt
*)
3770 (push (if *orgtbl-lfmt
*
3771 (orgtbl-apply-fmt *orgtbl-lfmt
* line
)
3772 (concat (orgtbl-eval-str *orgtbl-lstart
*)
3773 (mapconcat 'identity line
*orgtbl-sep
*)
3774 (orgtbl-eval-str *orgtbl-lend
*)))
3777 (defun orgtbl-format-section (section-stopper)
3778 "Format lines until the first occurrence of SECTION-STOPPER."
3781 (while (not (eq (car *orgtbl-table
*) section-stopper
))
3782 (if prevline
(orgtbl-format-line prevline
))
3783 (setq prevline
(pop *orgtbl-table
*)))
3784 (if prevline
(let ((*orgtbl-lstart
* *orgtbl-llstart
*)
3785 (*orgtbl-lend
* *orgtbl-llend
*)
3786 (*orgtbl-lfmt
* *orgtbl-llfmt
*))
3787 (orgtbl-format-line prevline
))))))
3789 (defun orgtbl-to-generic (table params
)
3790 "Convert the orgtbl-mode TABLE to some other format.
3791 This generic routine can be used for many standard cases.
3792 TABLE is a list, each entry either the symbol `hline' for a horizontal
3793 separator line, or a list of fields for that line.
3794 PARAMS is a property list of parameters that can influence the conversion.
3795 For the generic converter, some parameters are obligatory: You need to
3796 specify either :lfmt, or all of (:lstart :lend :sep).
3798 Valid parameters are
3800 :splice When set to t, return only table body lines, don't wrap
3801 them into :tstart and :tend. Default is nil. When :splice
3802 is non-nil, this also means that the exporter should not look
3803 for and interpret header and footer sections.
3805 :hline String to be inserted on horizontal separation lines.
3806 May be nil to ignore hlines.
3808 :sep Separator between two fields
3809 :remove-nil-lines Do not include lines that evaluate to nil.
3812 Each in the following group may be either a string or a function
3813 of no arguments returning a string:
3814 :tstart String to start the table. Ignored when :splice is t.
3815 :tend String to end the table. Ignored when :splice is t.
3816 :lstart String to start a new table line.
3817 :llstart String to start the last table line, defaults to :lstart.
3818 :lend String to end a table line
3819 :llend String to end the last table line, defaults to :lend.
3821 Each in the following group may be a string, a function of one
3822 argument (the field or line) returning a string, or a plist
3823 mapping columns to either of the above:
3824 :lfmt Format for entire line, with enough %s to capture all fields.
3825 If this is present, :lstart, :lend, and :sep are ignored.
3826 :llfmt Format for the entire last line, defaults to :lfmt.
3827 :fmt A format to be used to wrap the field, should contain
3828 %s for the original field value. For example, to wrap
3829 everything in dollars, you could use :fmt \"$%s$\".
3830 This may also be a property list with column numbers and
3831 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
3833 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
3834 Same as above, specific for the header lines in the table.
3835 All lines before the first hline are treated as header.
3836 If any of these is not present, the data line value is used.
3838 This may be either a string or a function of two arguments:
3839 :efmt Use this format to print numbers with exponentials.
3840 The format should have %s twice for inserting mantissa
3841 and exponent, for example \"%s\\\\times10^{%s}\". This
3842 may also be a property list with column numbers and
3843 formats. :fmt will still be applied after :efmt.
3845 In addition to this, the parameters :skip and :skipcols are always handled
3846 directly by `orgtbl-send-table'. See manual."
3849 (let* ((splicep (plist-get params
:splice
))
3850 (hline (plist-get params
:hline
))
3851 (remove-nil-linesp (plist-get params
:remove-nil-lines
))
3852 (*orgtbl-hline
* hline
)
3853 (*orgtbl-table
* table
)
3854 (*orgtbl-sep
* (plist-get params
:sep
))
3855 (*orgtbl-efmt
* (plist-get params
:efmt
))
3856 (*orgtbl-lstart
* (plist-get params
:lstart
))
3857 (*orgtbl-llstart
* (or (plist-get params
:llstart
) *orgtbl-lstart
*))
3858 (*orgtbl-lend
* (plist-get params
:lend
))
3859 (*orgtbl-llend
* (or (plist-get params
:llend
) *orgtbl-lend
*))
3860 (*orgtbl-lfmt
* (plist-get params
:lfmt
))
3861 (*orgtbl-llfmt
* (or (plist-get params
:llfmt
) *orgtbl-lfmt
*))
3862 (*orgtbl-fmt
* (plist-get params
:fmt
))
3867 (when (plist-member params
:tstart
)
3868 (let ((tstart (orgtbl-eval-str (plist-get params
:tstart
))))
3869 (if tstart
(push tstart
*orgtbl-rtn
*)))))
3871 ;; Do we have a heading section? If so, format it and handle the
3873 (if (and (not splicep
)
3874 (or (consp (car *orgtbl-table
*))
3875 (consp (nth 1 *orgtbl-table
*)))
3876 (memq 'hline
(cdr *orgtbl-table
*)))
3878 (when (eq 'hline
(car *orgtbl-table
*))
3879 ;; there is a hline before the first data line
3880 (and hline
(push hline
*orgtbl-rtn
*))
3881 (pop *orgtbl-table
*))
3882 (let* ((*orgtbl-lstart
* (or (plist-get params
:hlstart
)
3884 (*orgtbl-llstart
* (or (plist-get params
:hllstart
)
3886 (*orgtbl-lend
* (or (plist-get params
:hlend
) *orgtbl-lend
*))
3887 (*orgtbl-llend
* (or (plist-get params
:hllend
)
3888 (plist-get params
:hlend
) *orgtbl-llend
*))
3889 (*orgtbl-lfmt
* (or (plist-get params
:hlfmt
) *orgtbl-lfmt
*))
3890 (*orgtbl-llfmt
* (or (plist-get params
:hllfmt
)
3891 (plist-get params
:hlfmt
) *orgtbl-llfmt
*))
3892 (*orgtbl-sep
* (or (plist-get params
:hlsep
) *orgtbl-sep
*))
3893 (*orgtbl-fmt
* (or (plist-get params
:hfmt
) *orgtbl-fmt
*)))
3894 (orgtbl-format-section 'hline
))
3895 (if hline
(push hline
*orgtbl-rtn
*))
3896 (pop *orgtbl-table
*)))
3898 ;; Now format the main section.
3899 (orgtbl-format-section nil
)
3902 (when (plist-member params
:tend
)
3903 (let ((tend (orgtbl-eval-str (plist-get params
:tend
))))
3904 (if tend
(push tend
*orgtbl-rtn
*)))))
3906 (mapconcat 'identity
(nreverse (if remove-nil-linesp
3907 (remq nil
*orgtbl-rtn
*)
3908 *orgtbl-rtn
*)) "\n")))
3910 (defun orgtbl-to-tsv (table params
)
3911 "Convert the orgtbl-mode table to TAB separated material."
3912 (orgtbl-to-generic table
(org-combine-plists '(:sep
"\t") params
)))
3913 (defun orgtbl-to-csv (table params
)
3914 "Convert the orgtbl-mode table to CSV material.
3915 This does take care of the proper quoting of fields with comma or quotes."
3916 (orgtbl-to-generic table
(org-combine-plists
3917 '(:sep
"," :fmt org-quote-csv-field
)
3920 (defun orgtbl-to-latex (table params
)
3921 "Convert the orgtbl-mode TABLE to LaTeX.
3922 TABLE is a list, each entry either the symbol `hline' for a horizontal
3923 separator line, or a list of fields for that line.
3924 PARAMS is a property list of parameters that can influence the conversion.
3925 Supports all parameters from `orgtbl-to-generic'. Most important for
3928 :splice When set to t, return only table body lines, don't wrap
3929 them into a tabular environment. Default is nil.
3931 :fmt A format to be used to wrap the field, should contain %s for the
3932 original field value. For example, to wrap everything in dollars,
3933 use :fmt \"$%s$\". This may also be a property list with column
3934 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
3935 The format may also be a function that formats its one argument.
3937 :efmt Format for transforming numbers with exponentials. The format
3938 should have %s twice for inserting mantissa and exponent, for
3939 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
3940 This may also be a property list with column numbers and formats.
3941 The format may also be a function that formats its two arguments.
3943 :llend If you find too much space below the last line of a table,
3944 pass a value of \"\" for :llend to suppress the final \\\\.
3946 The general parameters :skip and :skipcols have already been applied when
3947 this function is called."
3948 (let* ((alignment (mapconcat (lambda (x) (if x
"r" "l"))
3949 org-table-last-alignment
""))
3952 :tstart
(concat "\\begin{tabular}{" alignment
"}")
3953 :tend
"\\end{tabular}"
3954 :lstart
"" :lend
" \\\\" :sep
" & "
3955 :efmt
"%s\\,(%s)" :hline
"\\hline")))
3956 (orgtbl-to-generic table
(org-combine-plists params2 params
))))
3958 (defun orgtbl-to-html (table params
)
3959 "Convert the orgtbl-mode TABLE to LaTeX.
3960 TABLE is a list, each entry either the symbol `hline' for a horizontal
3961 separator line, or a list of fields for that line.
3962 PARAMS is a property list of parameters that can influence the conversion.
3963 Currently this function recognizes the following parameters:
3965 :splice When set to t, return only table body lines, don't wrap
3966 them into a <table> environment. Default is nil.
3968 The general parameters :skip and :skipcols have already been applied when
3969 this function is called. The function does *not* use `orgtbl-to-generic',
3970 so you cannot specify parameters for it."
3971 (let* ((splicep (plist-get params
:splice
))
3972 (html-table-tag org-export-html-table-tag
)
3974 ;; Just call the formatter we already have
3975 ;; We need to make text lines for it, so put the fields back together.
3976 (setq html
(org-format-org-table-html
3981 (concat "| " (mapconcat 'identity x
" | ") " |")))
3984 (if (string-match "\n+\\'" html
)
3985 (setq html
(replace-match "" t t html
)))
3988 (defun orgtbl-to-texinfo (table params
)
3989 "Convert the orgtbl-mode TABLE to TeXInfo.
3990 TABLE is a list, each entry either the symbol `hline' for a horizontal
3991 separator line, or a list of fields for that line.
3992 PARAMS is a property list of parameters that can influence the conversion.
3993 Supports all parameters from `orgtbl-to-generic'. Most important for
3996 :splice nil/t When set to t, return only table body lines, don't wrap
3997 them into a multitable environment. Default is nil.
3999 :fmt fmt A format to be used to wrap the field, should contain
4000 %s for the original field value. For example, to wrap
4001 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4002 This may also be a property list with column numbers and
4003 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4004 Each format also may be a function that formats its one
4007 :cf \"f1 f2..\" The column fractions for the table. By default these
4008 are computed automatically from the width of the columns
4011 The general parameters :skip and :skipcols have already been applied when
4012 this function is called."
4013 (let* ((total (float (apply '+ org-table-last-column-widths
)))
4014 (colfrac (or (plist-get params
:cf
)
4016 (lambda (x) (format "%.3f" (/ (float x
) total
)))
4017 org-table-last-column-widths
" ")))
4020 :tstart
(concat "@multitable @columnfractions " colfrac
)
4021 :tend
"@end multitable"
4022 :lstart
"@item " :lend
"" :sep
" @tab "
4023 :hlstart
"@headitem ")))
4024 (orgtbl-to-generic table
(org-combine-plists params2 params
))))
4026 (defun orgtbl-to-orgtbl (table params
)
4027 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4028 Useful when slicing one table into many. The :hline, :sep,
4029 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4030 and :tend suppress strings without splicing; they can be set to
4031 provide ORGTBL directives for the generated table."
4034 :tstart nil
:tend nil
4039 (params (org-combine-plists params2 params
)))
4040 (orgtbl-to-generic table params
)))
4042 (provide 'org-table
)
4044 ;; arch-tag: 4d21cfdd-0268-440a-84b0-09237a0fe0ef
4046 ;;; org-table.el ends here