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 (car dlines
)
1902 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
)))))))
1904 (defun org-table-maybe-eval-formula ()
1905 "Check if the current field starts with \"=\" or \":=\".
1906 If yes, store the formula and apply it."
1907 ;; We already know we are in a table. Get field will only return a formula
1908 ;; when appropriate. It might return a separator line, but no problem.
1909 (when org-table-formula-evaluate-inline
1910 (let* ((field (org-trim (or (org-table-get-field) "")))
1912 (when (string-match "^:?=\\(.*\\)" field
)
1913 (setq named
(equal (string-to-char field
) ?
:)
1914 eq
(match-string 1 field
))
1915 (if (or (fboundp 'calc-eval
)
1916 (equal (substring eq
0 (min 2 (length eq
))) "'("))
1917 (org-table-eval-formula (if named
'(4) nil
)
1918 (org-table-formula-from-user eq
))
1919 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
1921 (defvar org-recalc-commands nil
1922 "List of commands triggering the recalculation of a line.
1923 Will be filled automatically during use.")
1925 (defvar org-recalc-marks
1926 '((" " .
"Unmarked: no special line, no automatic recalculation")
1927 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
1928 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
1929 ("!" .
"Column name definition line. Reference in formula as $name.")
1930 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
1931 ("_" .
"Names for values in row below this one.")
1932 ("^" .
"Names for values in row above this one.")))
1934 (defun org-table-rotate-recalc-marks (&optional newchar
)
1935 "Rotate the recalculation mark in the first column.
1936 If in any row, the first field is not consistent with a mark,
1937 insert a new column for the markers.
1938 When there is an active region, change all the lines in the region,
1939 after prompting for the marking character.
1940 After each change, a message will be displayed indicating the meaning
1943 (unless (org-at-table-p) (error "Not at a table"))
1944 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
1945 (beg (org-table-begin))
1946 (end (org-table-end))
1947 (l (org-current-line))
1948 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
1949 (l2 (if (org-region-active-p) (org-current-line (region-end))))
1953 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
1954 (col (org-table-current-column))
1955 (forcenew (car (assoc newchar org-recalc-marks
)))
1958 (message "Change region to what mark? Type # * ! $ or SPC: ")
1959 (setq newchar
(char-to-string (read-char-exclusive))
1960 forcenew
(car (assoc newchar org-recalc-marks
))))
1961 (if (and newchar
(not forcenew
))
1962 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
1964 (if l1
(goto-line l1
))
1966 (beginning-of-line 1)
1967 (unless (looking-at org-table-dataline-regexp
)
1968 (error "Not at a table data line")))
1970 (org-table-goto-column 1)
1971 (org-table-insert-column)
1972 (org-table-goto-column (1+ col
)))
1973 (setq epos
(point-at-eol))
1975 (beginning-of-line 1)
1976 (org-table-get-field
1977 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
1979 (setq new
(or forcenew
1980 (cadr (member (match-string 1) marks
))))
1986 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
1987 (and (looking-at org-table-dataline-regexp
)
1988 (org-table-get-field 1 (concat " " new
" "))))
1990 (if (not (= epos
(point-at-eol))) (org-table-align))
1992 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks
))))))
1994 (defun org-table-maybe-recalculate-line ()
1995 "Recompute the current line if marked for it, and if we haven't just done it."
1997 (and org-table-allow-automatic-line-recalculation
1998 (not (and (memq last-command org-recalc-commands
)
1999 (equal org-last-recalc-line
(org-current-line))))
2000 (save-excursion (beginning-of-line 1)
2001 (looking-at org-table-auto-recalculate-regexp
))
2002 (org-table-recalculate) t
))
2005 (defsubst org-set-calc-mode
(var &optional value
)
2007 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2008 ("R" calc-angle-mode rad
)
2009 ("F" calc-prefer-frac t
)
2010 ("S" calc-symbolic-mode t
)))
2011 value
(nth 2 var
) var
(nth 1 var
)))
2012 (if (memq var modes
)
2013 (setcar (cdr (memq var modes
)) value
)
2014 (cons var
(cons value modes
)))
2017 (defun org-table-eval-formula (&optional arg equation
2018 suppress-align suppress-const
2019 suppress-store suppress-analysis
)
2020 "Replace the table field value at the cursor by the result of a calculation.
2022 This function makes use of Dave Gillespie's Calc package, in my view the
2023 most exciting program ever written for GNU Emacs. So you need to have Calc
2024 installed in order to use this function.
2026 In a table, this command replaces the value in the current field with the
2027 result of a formula. It also installs the formula as the \"current\" column
2028 formula, by storing it in a special line below the table. When called
2029 with a `C-u' prefix, the current field must ba a named field, and the
2030 formula is installed as valid in only this specific field.
2032 When called with two `C-u' prefixes, insert the active equation
2033 for the field back into the current field, so that it can be
2034 edited there. This is useful in order to use \\[org-table-show-reference]
2035 to check the referenced fields.
2037 When called, the command first prompts for a formula, which is read in
2038 the minibuffer. Previously entered formulas are available through the
2039 history list, and the last used formula is offered as a default.
2040 These stored formulas are adapted correctly when moving, inserting, or
2041 deleting columns with the corresponding commands.
2043 The formula can be any algebraic expression understood by the Calc package.
2044 For details, see the Org-mode manual.
2046 This function can also be called from Lisp programs and offers
2047 additional arguments: EQUATION can be the formula to apply. If this
2048 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2049 used to speed-up recursive calls by by-passing unnecessary aligns.
2050 SUPPRESS-CONST suppresses the interpretation of constants in the
2051 formula, assuming that this has been done already outside the function.
2052 SUPPRESS-STORE means the formula should not be stored, either because
2053 it is already stored, or because it is a modified equation that should
2054 not overwrite the stored one."
2056 (org-table-check-inside-data-field)
2057 (or suppress-analysis
(org-table-get-specials))
2058 (if (equal arg
'(16))
2059 (let ((eq (org-table-current-field-formula)))
2060 (or eq
(error "No equation active for current field"))
2061 (org-table-get-field nil eq
)
2063 (setq org-table-may-need-update t
))
2065 (ndown (if (integerp arg
) arg
1))
2066 (org-table-automatic-realign nil
)
2067 (case-fold-search nil
)
2069 (formula (if (and equation suppress-store
)
2071 (org-table-get-formula equation
(equal arg
'(4)))))
2072 (n0 (org-table-current-column))
2073 (modes (copy-sequence org-calc-default-modes
))
2074 (numbers nil
) ; was a variable, now fixed default
2076 n form form0 bw fmt x ev orig c lispp literal
)
2077 ;; Parse the format string. Since we have a lot of modes, this is
2078 ;; a lot of work. However, I think calc still uses most of the time.
2079 (if (string-match ";" formula
)
2080 (let ((tmp (org-split-string formula
";")))
2081 (setq formula
(car tmp
)
2082 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2084 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2085 (setq c
(string-to-char (match-string 1 fmt
))
2086 n
(string-to-number (match-string 2 fmt
)))
2088 (setq modes
(org-set-calc-mode 'calc-internal-prec n
))
2089 (setq modes
(org-set-calc-mode
2091 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2092 (?s . sci
) (?e . eng
))))
2094 (setq fmt
(replace-match "" t t fmt
)))
2095 (if (string-match "[NT]" fmt
)
2096 (setq numbers
(equal (match-string 0 fmt
) "N")
2097 fmt
(replace-match "" t t fmt
)))
2098 (if (string-match "L" fmt
)
2100 fmt
(replace-match "" t t fmt
)))
2101 (if (string-match "E" fmt
)
2103 fmt
(replace-match "" t t fmt
)))
2104 (while (string-match "[DRFS]" fmt
)
2105 (setq modes
(org-set-calc-mode (match-string 0 fmt
)))
2106 (setq fmt
(replace-match "" t t fmt
)))
2107 (unless (string-match "\\S-" fmt
)
2109 (if (and (not suppress-const
) org-table-formula-use-constants
)
2110 (setq formula
(org-table-formula-substitute-names formula
)))
2111 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2113 (setq fields
(org-split-string
2115 (buffer-substring (point-at-bol) (point-at-eol)))
2118 (setq fields
(mapcar
2119 (lambda (x) (number-to-string (string-to-number x
)))
2121 (setq ndown
(1- ndown
))
2122 (setq form
(copy-sequence formula
)
2123 lispp
(and (> (length form
) 2)(equal (substring form
0 2) "'(")))
2124 (if (and lispp literal
) (setq lispp
'literal
))
2125 ;; Check for old vertical references
2126 (setq form
(org-table-rewrite-old-row-references form
))
2127 ;; Insert complex ranges
2128 (while (and (string-match org-table-range-regexp form
)
2129 (> (length (match-string 0 form
)) 1))
2133 (org-table-make-reference
2134 (org-table-get-range (match-string 0 form
) nil n0
)
2135 keep-empty numbers lispp
))
2137 ;; Insert simple ranges
2138 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2142 (org-table-make-reference
2144 fields
(string-to-number (match-string 1 form
))
2145 (string-to-number (match-string 2 form
)))
2146 keep-empty numbers lispp
))
2149 ;; Insert the references to fields in same row
2150 (while (string-match "\\$\\([0-9]+\\)" form
)
2151 (setq n
(string-to-number (match-string 1 form
))
2152 x
(nth (1- (if (= n
0) n0 n
)) fields
))
2153 (unless x
(error "Invalid field specifier \"%s\""
2154 (match-string 0 form
)))
2155 (setq form
(replace-match
2157 (org-table-make-reference x nil numbers lispp
))
2161 (setq ev
(condition-case nil
2162 (eval (eval (read form
)))
2164 ev
(if (numberp ev
) (number-to-string ev
) ev
))
2165 (or (fboundp 'calc-eval
)
2166 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2167 (setq ev
(calc-eval (cons form modes
)
2168 (if numbers
'num
))))
2170 (when org-table-formula-debug
2171 (with-output-to-temp-buffer "*Substitution History*"
2172 (princ (format "Substitution history of formula
2176 $1-> %s\n" orig formula form0 form
))
2178 (princ (format " %s^\nError: %s"
2179 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2180 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2182 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2183 (setq bw
(get-buffer-window "*Substitution History*"))
2184 (org-fit-window-to-buffer bw
)
2185 (unless (and (interactive-p) (not ndown
))
2186 (unless (let (inhibit-redisplay)
2187 (y-or-n-p "Debugging Formula. Continue to next? "))
2192 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2193 (org-table-justify-field-maybe
2194 (if fmt
(format fmt
(string-to-number ev
)) ev
))
2195 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2196 (call-interactively 'org-return
)
2198 (and down
(org-table-maybe-recalculate-line))
2199 (or suppress-align
(and org-table-may-need-update
2200 (org-table-align))))))
2202 (defun org-table-put-field-property (prop value
)
2204 (put-text-property (progn (skip-chars-backward "^|") (point))
2205 (progn (skip-chars-forward "^|") (point))
2208 (defun org-table-get-range (desc &optional tbeg col highlight
)
2209 "Get a calc vector from a column, according to descriptor DESC.
2210 Optional arguments TBEG and COL can give the beginning of the table and
2211 the current column, to avoid unnecessary parsing.
2212 HIGHLIGHT means, just highlight the range."
2213 (if (not (equal (string-to-char desc
) ?
@))
2214 (setq desc
(concat "@" desc
)))
2216 (or tbeg
(setq tbeg
(org-table-begin)))
2217 (or col
(setq col
(org-table-current-column)))
2218 (let ((thisline (org-current-line))
2219 beg end c1 c2 r1 r2 rangep tmp
)
2220 (unless (string-match org-table-range-regexp desc
)
2221 (error "Invalid table range specifier `%s'" desc
))
2222 (setq rangep
(match-end 3)
2223 r1
(and (match-end 1) (match-string 1 desc
))
2224 r2
(and (match-end 4) (match-string 4 desc
))
2225 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2226 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2228 (and c1
(setq c1
(+ (string-to-number c1
)
2229 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2230 (and c2
(setq c2
(+ (string-to-number c2
)
2231 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2232 (if (equal r1
"") (setq r1 nil
))
2233 (if (equal r2
"") (setq r2 nil
))
2234 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2235 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2236 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2237 (if (not r1
) (setq r1 thisline
))
2238 (if (not r2
) (setq r2 thisline
))
2239 (if (not c1
) (setq c1 col
))
2240 (if (not c2
) (setq c2 col
))
2241 (if (or (not rangep
) (and (= r1 r2
) (= c1 c2
)))
2245 (while (not (looking-at org-table-dataline-regexp
))
2246 (beginning-of-line 2))
2247 (prog1 (org-trim (org-table-get-field c1
))
2248 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2249 ;; A range, return a vector
2250 ;; First sort the numbers to get a regular ractangle
2251 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2252 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2254 (while (not (looking-at org-table-dataline-regexp
))
2255 (beginning-of-line 2))
2256 (org-table-goto-column c1
)
2259 (while (not (looking-at org-table-dataline-regexp
))
2260 (beginning-of-line 0))
2261 (org-table-goto-column c2
)
2264 (org-table-highlight-rectangle
2265 beg
(progn (skip-chars-forward "^|\n") (point))))
2266 ;; return string representation of calc vector
2268 (apply 'append
(org-table-copy-region beg end
)))))))
2270 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2271 "Analyze descriptor DESC and retrieve the corresponding line number.
2272 The cursor is currently in line CLINE, the table begins in line BLINE,
2273 and TABLE is a vector with line types."
2274 (if (string-match "^[0-9]+$" desc
)
2275 (aref org-table-dlines
(string-to-number desc
))
2276 (setq cline
(or cline
(org-current-line))
2277 bline
(or bline org-table-current-begin-line
)
2278 table
(or table org-table-current-line-types
))
2280 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2282 (and (not (match-end 3)) (not (match-end 6)))
2283 (and (match-end 3) (match-end 6) (not (match-end 5))))
2284 (error "invalid row descriptor `%s'" desc
))
2285 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2286 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2287 (odir (and (match-end 5) (match-string 5 desc
)))
2288 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2290 (rel (and (match-end 6)
2291 (or (and (match-end 1) (not (match-end 3)))
2293 (if (and hn
(not hdir
))
2296 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2297 (if (and (not hn
) on
(not odir
))
2298 (error "should never happen");;(aref org-table-dlines on)
2299 (if (and hn
(> hn
0))
2300 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2301 nil hn cline desc
)))
2303 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2304 rel on cline desc
)))
2307 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2308 "FIXME: Needs more documentation."
2309 (let ((l (length table
)))
2311 (while (and (setq i
(+ i
(if backwards -
1 1)))
2313 (not (eq (aref table i
) type
))
2314 (if (and relative
(eq (aref table i
) 'hline
))
2315 (if org-table-error-on-row-ref-crossing-hline
2316 (error "Row descriptor %s used in line %d crosses hline" desc cline
)
2317 (progn (setq i
(- i
(if backwards -
1 1)) n
1) nil
))
2320 (if (or (< i
0) (>= i l
))
2321 (error "Row descriptor %s used in line %d leads outside table"
2325 (defun org-table-rewrite-old-row-references (s)
2326 (if (string-match "&[-+0-9I]" s
)
2327 (error "Formula contains old &row reference, please rewrite using @-syntax")
2330 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2331 "Convert list ELEMENTS to something appropriate to insert into formula.
2332 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2333 NUMBERS indicates that everything should be converted to numbers.
2334 LISPP means to return something appropriate for a Lisp list."
2335 (if (stringp elements
) ; just a single val
2337 (if (eq lispp
'literal
)
2339 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2340 (if (equal elements
"") (setq elements
"0"))
2341 (if numbers
(setq elements
(number-to-string (string-to-number elements
))))
2342 (concat "(" elements
")"))
2346 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2348 (setq elements
(or elements
'("0")))
2352 (if (eq lispp
'literal
)
2354 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2356 (concat "[" (mapconcat
2358 (if numbers
(number-to-string (string-to-number x
)) x
))
2362 (defun org-table-recalculate (&optional all noalign
)
2363 "Recalculate the current table line by applying all stored formulas.
2364 With prefix arg ALL, do this for all lines in the table.
2365 With the prefix argument ALL is `(16)' (a double `C-c C-u' prefix), or if
2366 it is the symbol `iterate', recompute the table until it no longer changes.
2367 If NOALIGN is not nil, do not re-align the table after the computations
2368 are done. This is typically used internally to save time, if it is
2369 known that the table will be realigned a little later anyway."
2371 (or (memq this-command org-recalc-commands
)
2372 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2373 (unless (org-at-table-p) (error "Not at a table"))
2374 (if (or (eq all
'iterate
) (equal all
'(16)))
2376 (org-table-get-specials)
2377 (let* ((eqlist (sort (org-table-get-stored-formulas)
2378 (lambda (a b
) (string< (car a
) (car b
)))))
2379 (inhibit-redisplay (not debug-on-error
))
2380 (line-re org-table-dataline-regexp
)
2381 (thisline (org-current-line))
2382 (thiscol (org-table-current-column))
2383 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name
)
2384 ;; Insert constants in all formulas
2387 (setcdr x
(org-table-formula-substitute-names (cdr x
)))
2390 ;; Split the equation list
2391 (while (setq eq
(pop eqlist
))
2392 (if (<= (string-to-char (car eq
)) ?
9)
2395 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
2398 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
2399 (goto-char (setq beg
(org-table-begin)))
2400 (if (re-search-forward org-table-calculate-mark-regexp end t
)
2401 ;; This is a table with marked lines, compute selected lines
2402 (setq line-re org-table-recalculate-regexp
)
2403 ;; Move forward to the first non-header line
2404 (if (and (re-search-forward org-table-dataline-regexp end t
)
2405 (re-search-forward org-table-hline-regexp end t
)
2406 (re-search-forward org-table-dataline-regexp end t
))
2407 (setq beg
(match-beginning 0))
2408 nil
))) ;; just leave beg where it is
2409 (setq beg
(point-at-bol)
2410 end
(move-marker (make-marker) (1+ (point-at-eol)))))
2412 (and all
(message "Re-applying formulas to full table..."))
2414 ;; First find the named fields, and mark them untouchable
2415 (remove-text-properties beg end
'(org-untouchable t
))
2416 (while (setq eq
(pop eqlname
))
2418 a
(assoc name org-table-named-field-locations
))
2420 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
2423 (aref org-table-dlines
2424 (string-to-number (match-string 1 name
)))
2425 (error (error "Invalid row number in %s"
2427 (string-to-number (match-string 2 name
)))))
2428 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
2429 (message "Re-applying formula to field: %s" name
)
2430 (goto-line (nth 1 a
))
2431 (org-table-goto-column (nth 2 a
))
2432 (push (append a
(list (cdr eq
))) eqlname1
)
2433 (org-table-put-field-property :org-untouchable t
)))
2435 ;; Now evauluate the column formulas, but skip fields covered by
2438 (while (re-search-forward line-re end t
)
2439 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2440 ;; Unprotected line, recalculate
2441 (and all
(message "Re-applying formulas to full table...(line %d)"
2442 (setq cnt
(1+ cnt
))))
2443 (setq org-last-recalc-line
(org-current-line))
2445 (while (setq entry
(pop eql
))
2446 (goto-line org-last-recalc-line
)
2447 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
2448 (unless (get-text-property (point) :org-untouchable
)
2449 (org-table-eval-formula nil
(cdr entry
)
2450 'noalign
'nocst
'nostore
'noanalysis
)))))
2452 ;; Now evaluate the field formulas
2453 (while (setq eq
(pop eqlname1
))
2454 (message "Re-applying formula to field: %s" (car eq
))
2455 (goto-line (nth 1 eq
))
2456 (org-table-goto-column (nth 2 eq
))
2457 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
2458 'nostore
'noanalysis
))
2460 (goto-line thisline
)
2461 (org-table-goto-column thiscol
)
2462 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
2463 (or noalign
(and org-table-may-need-update
(org-table-align))
2464 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
2466 ;; back to initial position
2467 (message "Re-applying formulas...done")
2468 (goto-line thisline
)
2469 (org-table-goto-column thiscol
)
2470 (or noalign
(and org-table-may-need-update
(org-table-align))
2471 (and all
(message "Re-applying formulas...done"))))))
2473 (defun org-table-iterate (&optional arg
)
2474 "Recalculate the table until it does not change anymore."
2476 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
2478 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2483 (org-table-recalculate 'all
)
2484 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
2485 (if (not (string= lasttbl thistbl
))
2486 (setq lasttbl thistbl
)
2488 (message "Convergence after %d iterations" i
)
2489 (message "Table was already stable"))
2491 (error "No convergence after %d iterations" i
))))
2493 (defun org-table-formula-substitute-names (f)
2494 "Replace $const with values in string F."
2495 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
2496 ;; First, check for column names
2497 (while (setq start
(string-match org-table-column-name-regexp f start
))
2498 (setq start
(1+ start
))
2499 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
2500 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
2501 ;; Parameters and constants
2503 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start
))
2504 (setq start
(1+ start
))
2505 (if (setq a
(save-match-data
2506 (org-table-get-constant (match-string 1 f
))))
2507 (setq f
(replace-match
2508 (concat (if pp
"(") a
(if pp
")")) t t f
))))
2509 (if org-table-formula-debug
2510 (put-text-property 0 (length f
) :orig-formula f1 f
))
2513 (defun org-table-get-constant (const)
2514 "Find the value for a parameter or constant in a formula.
2515 Parameters get priority."
2516 (or (cdr (assoc const org-table-local-parameters
))
2517 (cdr (assoc const org-table-formula-constants-local
))
2518 (cdr (assoc const org-table-formula-constants
))
2519 (and (fboundp 'constants-get
) (constants-get const
))
2520 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
2521 (org-entry-get nil
(substring const
5) 'inherit
))
2524 (defvar org-table-fedit-map
2525 (let ((map (make-sparse-keymap)))
2526 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
2527 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
2528 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
2529 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
2530 (org-defkey map
"\C-c?" 'org-table-show-reference
)
2531 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
2532 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
2533 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
2534 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
2535 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
2536 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
2537 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
2538 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
2539 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
2540 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
2541 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
2542 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
2543 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
2544 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
2547 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
2549 ["Finish and Install" org-table-fedit-finish t
]
2550 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
2551 ["Abort" org-table-fedit-abort t
]
2553 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
2554 ["Complete Lisp Symbol" lisp-complete-symbol t
]
2556 "Shift Reference at Point"
2557 ["Up" org-table-fedit-ref-up t
]
2558 ["Down" org-table-fedit-ref-down t
]
2559 ["Left" org-table-fedit-ref-left t
]
2560 ["Right" org-table-fedit-ref-right t
]
2562 "Change Test Row for Column Formulas"
2563 ["Up" org-table-fedit-line-up t
]
2564 ["Down" org-table-fedit-line-down t
]
2566 ["Scroll Table Window" org-table-fedit-scroll t
]
2567 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
2568 ["Show Table Grid" org-table-fedit-toggle-coordinates
2569 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
2570 org-table-overlay-coordinates
)]
2572 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
2573 :style toggle
:selected org-table-buffer-is-an
]))
2577 (defun org-table-edit-formulas ()
2578 "Edit the formulas of the current table in a separate buffer."
2580 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
2581 (beginning-of-line 0))
2582 (unless (org-at-table-p) (error "Not at a table"))
2583 (org-table-get-specials)
2584 (let ((key (org-table-current-field-formula 'key
'noerror
))
2585 (eql (sort (org-table-get-stored-formulas 'noerror
)
2586 'org-table-formula-less-p
))
2587 (pos (move-marker (make-marker) (point)))
2589 (wc (current-window-configuration))
2590 (titles '((column .
"# Column Formulas\n")
2591 (field .
"# Field Formulas\n")
2592 (named .
"# Named Field Formulas\n")))
2594 (org-switch-to-buffer-other-window "*Edit Formulas*")
2596 ;; Keep global-font-lock-mode from turning on font-lock-mode
2597 (let ((font-lock-global-modes '(not fundamental-mode
)))
2599 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
2600 (org-set-local 'org-pos pos
)
2601 (org-set-local 'org-window-configuration wc
)
2602 (use-local-map org-table-fedit-map
)
2603 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
2604 (easy-menu-add org-table-fedit-menu
)
2605 (setq startline
(org-current-line))
2606 (while (setq entry
(pop eql
))
2608 ((equal (string-to-char (car entry
)) ?
@) 'field
)
2609 ((string-match "^[0-9]" (car entry
)) 'column
)
2611 (when (setq title
(assq type titles
))
2612 (or (bobp) (insert "\n"))
2613 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
2614 (setq titles
(delq title titles
)))
2615 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
2616 (setq s
(concat (if (equal (string-to-char (car entry
)) ?
@) "" "$")
2617 (car entry
) " = " (cdr entry
) "\n"))
2618 (remove-text-properties 0 (length s
) '(face nil
) s
)
2620 (if (eq org-table-use-standard-references t
)
2621 (org-table-fedit-toggle-ref-type))
2622 (goto-line startline
)
2623 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
2625 (defun org-table-fedit-post-command ()
2626 (when (not (memq this-command
'(lisp-complete-symbol)))
2627 (let ((win (selected-window)))
2630 (org-table-show-reference)
2632 (select-window win
)))))
2634 (defun org-table-formula-to-user (s)
2635 "Convert a formula from internal to user representation."
2636 (if (eq org-table-use-standard-references t
)
2637 (org-table-convert-refs-to-an s
)
2640 (defun org-table-formula-from-user (s)
2641 "Convert a formula from user to internal representation."
2642 (if org-table-use-standard-references
2643 (org-table-convert-refs-to-rc s
)
2646 (defun org-table-convert-refs-to-rc (s)
2647 "Convert spreadsheet references from AB7 to @7$28.
2648 Works for single references, but also for entire formulas and even the
2651 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start
)
2654 ;; format match, just advance
2655 (setq start
(match-end 0)))
2656 ((and (> (match-beginning 0) 0)
2657 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
2658 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
2659 ;; 3.e5 or something like this.
2660 (setq start
(match-end 0)))
2662 (setq start
(match-beginning 0)
2664 (if (equal (match-string 2 s
) "&")
2665 (format "$%d" (org-letters-to-number (match-string 1 s
)))
2667 (string-to-number (match-string 2 s
))
2668 (org-letters-to-number (match-string 1 s
))))
2672 (defun org-table-convert-refs-to-an (s)
2673 "Convert spreadsheet references from to @7$28 to AB7.
2674 Works for single references, but also for entire formulas and even the
2676 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
2677 (setq s
(replace-match
2679 (org-number-to-letters
2680 (string-to-number (match-string 2 s
)))
2681 (string-to-number (match-string 1 s
)))
2683 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
2684 (setq s
(replace-match (concat "\\1"
2685 (org-number-to-letters
2686 (string-to-number (match-string 2 s
))) "&")
2690 (defun org-letters-to-number (s)
2691 "Convert a base 26 number represented by letters into an integer.
2692 For example: AB -> 28."
2695 (while (> (length s
) 0)
2696 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
2700 (defun org-number-to-letters (n)
2701 "Convert an integer into a base 26 number represented by letters.
2702 For example: 28 -> AB."
2705 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
2709 (defun org-table-fedit-convert-buffer (function)
2710 "Convert all references in this buffer, using FUNCTION."
2711 (let ((line (org-current-line)))
2712 (goto-char (point-min))
2714 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
2715 (delete-region (point) (point-at-eol))
2716 (or (eobp) (forward-char 1)))
2719 (defun org-table-fedit-toggle-ref-type ()
2720 "Convert all references in the buffer from B3 to @3$2 and back."
2722 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
2723 (org-table-fedit-convert-buffer
2724 (if org-table-buffer-is-an
2725 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
2726 (message "Reference type switched to %s"
2727 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
2729 (defun org-table-fedit-ref-up ()
2730 "Shift the reference at point one row/hline up."
2732 (org-table-fedit-shift-reference 'up
))
2733 (defun org-table-fedit-ref-down ()
2734 "Shift the reference at point one row/hline down."
2736 (org-table-fedit-shift-reference 'down
))
2737 (defun org-table-fedit-ref-left ()
2738 "Shift the reference at point one field to the left."
2740 (org-table-fedit-shift-reference 'left
))
2741 (defun org-table-fedit-ref-right ()
2742 "Shift the reference at point one field to the right."
2744 (org-table-fedit-shift-reference 'right
))
2746 (defun org-table-fedit-shift-reference (dir)
2748 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
2749 (if (memq dir
'(left right
))
2750 (org-rematch-and-replace 1 (eq dir
'left
))
2751 (error "Cannot shift reference in this direction")))
2752 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
2753 ;; A B3-like reference
2754 (if (memq dir
'(up down
))
2755 (org-rematch-and-replace 2 (eq dir
'up
))
2756 (org-rematch-and-replace 1 (eq dir
'left
))))
2758 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
2759 ;; An internal reference
2760 (if (memq dir
'(up down
))
2761 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
2762 (org-rematch-and-replace 5 (eq dir
'left
))))))
2764 (defun org-rematch-and-replace (n &optional decr hline
)
2765 "Re-match the group N, and replace it with the shifted refrence."
2766 (or (match-end n
) (error "Cannot shift reference in this direction"))
2767 (goto-char (match-beginning n
))
2768 (and (looking-at (regexp-quote (match-string n
)))
2769 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
2772 (defun org-table-shift-refpart (ref &optional decr hline
)
2773 "Shift a refrence part REF.
2774 If DECR is set, decrease the references row/column, else increase.
2775 If HLINE is set, this may be a hline reference, it certainly is not
2776 a translation reference."
2778 (let* ((sign (string-match "^[-+]" ref
)) n
)
2780 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
2782 ((and hline
(string-match "^I+" ref
))
2783 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
2784 (setq n
(+ n
(if decr -
1 1)))
2785 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
2787 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
2789 (concat sign
(make-string n ?I
)))
2791 ((string-match "^[0-9]+" ref
)
2792 (setq n
(string-to-number (concat sign ref
)))
2793 (setq n
(+ n
(if decr -
1 1)))
2795 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
2796 (number-to-string (max 1 n
))))
2798 ((string-match "^[a-zA-Z]+" ref
)
2799 (org-number-to-letters
2800 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
2802 (t (error "Cannot shift reference"))))))
2804 (defun org-table-fedit-toggle-coordinates ()
2805 "Toggle the display of coordinates in the referenced table."
2807 (let ((pos (marker-position org-pos
)))
2808 (with-current-buffer (marker-buffer org-pos
)
2811 (org-table-toggle-coordinate-overlays)))))
2813 (defun org-table-fedit-finish (&optional arg
)
2814 "Parse the buffer for formula definitions and install them.
2815 With prefix ARG, apply the new formulas to the table."
2817 (org-table-remove-rectangle-highlight)
2818 (if org-table-use-standard-references
2820 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
2821 (setq org-table-buffer-is-an nil
)))
2822 (let ((pos org-pos
) eql var form
)
2823 (goto-char (point-min))
2824 (while (re-search-forward
2825 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
2827 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
2828 form
(match-string 3))
2829 (setq form
(org-trim form
))
2830 (when (not (equal form
""))
2831 (while (string-match "[ \t]*\n[ \t]*" form
)
2832 (setq form
(replace-match " " t t form
)))
2833 (when (assoc var eql
)
2834 (error "Double formulas for %s" var
))
2835 (push (cons var form
) eql
)))
2837 (set-window-configuration org-window-configuration
)
2838 (select-window (get-buffer-window (marker-buffer pos
)))
2840 (unless (org-at-table-p)
2841 (error "Lost table position - cannot install formulae"))
2842 (org-table-store-formulas eql
)
2843 (move-marker pos nil
)
2844 (kill-buffer "*Edit Formulas*")
2846 (org-table-recalculate 'all
)
2847 (message "New formulas installed - press C-u C-c C-c to apply."))))
2849 (defun org-table-fedit-abort ()
2850 "Abort editing formulas, without installing the changes."
2852 (org-table-remove-rectangle-highlight)
2853 (let ((pos org-pos
))
2854 (set-window-configuration org-window-configuration
)
2855 (select-window (get-buffer-window (marker-buffer pos
)))
2857 (move-marker pos nil
)
2858 (message "Formula editing aborted without installing changes")))
2860 (defun org-table-fedit-lisp-indent ()
2861 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
2863 (let ((pos (point)) beg end ind
)
2864 (beginning-of-line 1)
2866 ((looking-at "[ \t]")
2868 (call-interactively 'lisp-indent-line
))
2869 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
2870 ((not (fboundp 'pp-buffer
))
2871 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
2872 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
2873 (goto-char (- (match-end 0) 2))
2875 (setq ind
(make-string (current-column) ?\
))
2876 (condition-case nil
(forward-sexp 1)
2878 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
2881 (narrow-to-region beg end
)
2882 (if (eq last-command this-command
)
2884 (goto-char (point-min))
2885 (setq this-command nil
)
2886 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
2887 (replace-match " ")))
2889 (untabify (point-min) (point-max))
2890 (goto-char (1+ (point-min)))
2891 (while (re-search-forward "^." nil t
)
2892 (beginning-of-line 1)
2894 (goto-char (point-max))
2895 (backward-delete-char 1)))
2899 (defvar org-show-positions nil
)
2901 (defun org-table-show-reference (&optional local
)
2902 "Show the location/value of the $ expression at point."
2904 (org-table-remove-rectangle-highlight)
2906 (let ((pos (if local
(point) org-pos
))
2908 (org-inhibit-highlight-removal t
)
2909 (win (selected-window))
2910 (org-show-positions nil
)
2911 var name e what match dest
)
2912 (if local
(org-table-get-specials))
2914 ((or (org-at-regexp-p org-table-range-regexp2
)
2915 (org-at-regexp-p org-table-translate-regexp
)
2916 (org-at-regexp-p org-table-range-regexp
))
2919 (org-table-convert-refs-to-rc (match-string 0))))
2921 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
2922 ((org-at-regexp-p "\\$[0-9]+") 'column
)
2924 (t (error "No reference at point")))
2925 match
(and what
(or match
(match-string 0))))
2926 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
2927 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
2928 'secondary-selection
))
2929 (org-add-hook 'before-change-functions
2930 'org-table-remove-rectangle-highlight
)
2931 (if (eq what
'name
) (setq var
(substring match
1)))
2932 (when (eq what
'range
)
2933 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
2934 (setq match
(org-table-formula-substitute-names match
)))
2938 (re-search-backward "^\\S-" nil t
)
2939 (beginning-of-line 1)
2940 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
2943 (org-table-convert-refs-to-rc (match-string 1))))
2944 (org-table-add-rectangle-overlay
2945 (match-beginning 1) (match-end 1) face2
))))
2946 (if (and (markerp pos
) (marker-buffer pos
))
2947 (if (get-buffer-window (marker-buffer pos
))
2948 (select-window (get-buffer-window (marker-buffer pos
)))
2949 (org-switch-to-buffer-other-window (get-buffer-window
2950 (marker-buffer pos
)))))
2952 (org-table-force-dataline)
2954 (setq name
(substring dest
1))
2956 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
2957 (setq e
(assoc name org-table-named-field-locations
))
2958 (goto-line (nth 1 e
))
2959 (org-table-goto-column (nth 2 e
)))
2960 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
2961 (let ((l (string-to-number (match-string 1 dest
)))
2962 (c (string-to-number (match-string 2 dest
))))
2963 (goto-line (aref org-table-dlines l
))
2964 (org-table-goto-column c
)))
2965 (t (org-table-goto-column (string-to-number name
))))
2966 (move-marker pos
(point))
2967 (org-table-highlight-rectangle nil nil face2
))
2969 ((equal dest match
))
2974 (org-table-get-range match nil nil
'highlight
))
2976 ((setq e
(assoc var org-table-named-field-locations
))
2977 (goto-line (nth 1 e
))
2978 (org-table-goto-column (nth 2 e
))
2979 (org-table-highlight-rectangle (point) (point))
2980 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
2981 ((setq e
(assoc var org-table-column-names
))
2982 (org-table-goto-column (string-to-number (cdr e
)))
2983 (org-table-highlight-rectangle (point) (point))
2984 (goto-char (org-table-begin))
2985 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
2988 (goto-char (match-beginning 1))
2989 (org-table-highlight-rectangle)
2990 (message "Named column (column %s)" (cdr e
)))
2991 (error "Column name not found")))
2994 (org-table-goto-column (string-to-number (substring match
1)))
2995 (org-table-highlight-rectangle (point) (point))
2996 (message "Column %s" (substring match
1)))
2997 ((setq e
(assoc var org-table-local-parameters
))
2998 (goto-char (org-table-begin))
2999 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3001 (goto-char (match-beginning 1))
3002 (org-table-highlight-rectangle)
3003 (message "Local parameter."))
3004 (error "Parameter not found")))
3007 ((not var
) (error "No reference at point"))
3008 ((setq e
(assoc var org-table-formula-constants-local
))
3009 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3011 ((setq e
(assoc var org-table-formula-constants
))
3012 (message "Constant: $%s=%s in `org-table-formula-constants'."
3014 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3015 (message "Constant: $%s=%s, from `constants.el'%s."
3016 var e
(format " (%s units)" constants-unit-system
)))
3017 (t (error "Undefined name $%s" var
)))))
3019 (when (and org-show-positions
3020 (not (memq this-command
'(org-table-fedit-scroll
3021 org-table-fedit-scroll-down
))))
3022 (push pos org-show-positions
)
3023 (push org-table-current-begin-pos org-show-positions
)
3024 (let ((min (apply 'min org-show-positions
))
3025 (max (apply 'max org-show-positions
)))
3026 (goto-char min
) (recenter 0)
3028 (or (pos-visible-in-window-p max
) (recenter -
1))))
3029 (select-window win
))))
3031 (defun org-table-force-dataline ()
3032 "Make sure the cursor is in a dataline in a table."
3033 (unless (save-excursion
3034 (beginning-of-line 1)
3035 (looking-at org-table-dataline-regexp
))
3036 (let* ((re org-table-dataline-regexp
)
3037 (p1 (save-excursion (re-search-forward re nil
'move
)))
3038 (p2 (save-excursion (re-search-backward re nil
'move
))))
3040 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3042 ((or p1 p2
) (goto-char (or p1 p2
)))
3043 (t (error "No table dataline around here"))))))
3045 (defun org-table-fedit-line-up ()
3046 "Move cursor one line up in the window showing the table."
3048 (org-table-fedit-move 'previous-line
))
3050 (defun org-table-fedit-line-down ()
3051 "Move cursor one line down in the window showing the table."
3053 (org-table-fedit-move 'next-line
))
3055 (defun org-table-fedit-move (command)
3056 "Move the cursor in the window showing the table.
3057 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3058 (let ((org-table-allow-automatic-line-recalculation nil
)
3059 (pos org-pos
) (win (selected-window)) p
)
3060 (select-window (get-buffer-window (marker-buffer org-pos
)))
3062 (call-interactively command
)
3063 (while (and (org-at-table-p)
3064 (org-at-table-hline-p))
3065 (call-interactively command
))
3066 (or (org-at-table-p) (goto-char p
))
3067 (move-marker pos
(point))
3068 (select-window win
)))
3070 (defun org-table-fedit-scroll (N)
3072 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3073 (scroll-other-window N
)))
3075 (defun org-table-fedit-scroll-down (N)
3077 (org-table-fedit-scroll (- N
)))
3079 (defvar org-table-rectangle-overlays nil
)
3081 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3082 "Add a new overlay."
3083 (let ((ov (org-make-overlay beg end
)))
3084 (org-overlay-put ov
'face
(or face
'secondary-selection
))
3085 (push ov org-table-rectangle-overlays
)))
3087 (defun org-table-highlight-rectangle (&optional beg end face
)
3088 "Highlight rectangular region in a table."
3089 (setq beg
(or beg
(point)) end
(or end
(point)))
3090 (let ((b (min beg end
))
3093 (and (boundp 'org-show-positions
)
3094 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3095 (goto-char (min beg end
))
3096 (setq l1
(org-current-line)
3097 c1
(org-table-current-column))
3098 (goto-char (max beg end
))
3099 (setq l2
(org-current-line)
3100 c2
(org-table-current-column))
3101 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3103 (beginning-of-line 1)
3104 (loop for line from l1 to l2 do
3105 (when (looking-at org-table-dataline-regexp
)
3106 (org-table-goto-column c1
)
3107 (skip-chars-backward "^|\n") (setq beg
(point))
3108 (org-table-goto-column c2
)
3109 (skip-chars-forward "^|\n") (setq end
(point))
3110 (org-table-add-rectangle-overlay beg end face
))
3111 (beginning-of-line 2))
3113 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3115 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3116 "Remove the rectangle overlays."
3117 (unless org-inhibit-highlight-removal
3118 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3119 (mapc 'org-delete-overlay org-table-rectangle-overlays
)
3120 (setq org-table-rectangle-overlays nil
)))
3122 (defvar org-table-coordinate-overlays nil
3123 "Collects the coordinate grid overlays, so that they can be removed.")
3124 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3126 (defun org-table-overlay-coordinates ()
3127 "Add overlays to the table at point, to show row/column coordinates."
3129 (mapc 'org-delete-overlay org-table-coordinate-overlays
)
3130 (setq org-table-coordinate-overlays nil
)
3132 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3133 (goto-char (org-table-begin))
3134 (while (org-at-table-p)
3135 (setq eol
(point-at-eol))
3136 (setq ov
(org-make-overlay (point-at-bol) (1+ (point-at-bol))))
3137 (push ov org-table-coordinate-overlays
)
3138 (setq hline
(looking-at org-table-hline-regexp
))
3139 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3140 (format "%4d" (setq id
(1+ id
)))))
3141 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3144 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3145 (setq beg
(1+ (match-beginning 0))
3147 s1
(concat "$" (int-to-string ic
))
3148 s2
(org-number-to-letters ic
)
3149 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3150 (setq ov
(org-make-overlay beg
(+ beg
(length str
))))
3151 (push ov org-table-coordinate-overlays
)
3152 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3153 (beginning-of-line 2)))))
3155 (defun org-table-toggle-coordinate-overlays ()
3156 "Toggle the display of Row/Column numbers in tables."
3158 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3159 (message "Row/Column number display turned %s"
3160 (if org-table-overlay-coordinates
"on" "off"))
3161 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3163 (unless org-table-overlay-coordinates
3164 (mapc 'org-delete-overlay org-table-coordinate-overlays
)
3165 (setq org-table-coordinate-overlays nil
)))
3167 (defun org-table-toggle-formula-debugger ()
3168 "Toggle the formula debugger in tables."
3170 (setq org-table-formula-debug
(not org-table-formula-debug
))
3171 (message "Formula debugging has been turned %s"
3172 (if org-table-formula-debug
"on" "off")))
3174 ;;; The orgtbl minor mode
3176 ;; Define a minor mode which can be used in other modes in order to
3177 ;; integrate the org-mode table editor.
3179 ;; This is really a hack, because the org-mode table editor uses several
3180 ;; keys which normally belong to the major mode, for example the TAB and
3181 ;; RET keys. Here is how it works: The minor mode defines all the keys
3182 ;; necessary to operate the table editor, but wraps the commands into a
3183 ;; function which tests if the cursor is currently inside a table. If that
3184 ;; is the case, the table editor command is executed. However, when any of
3185 ;; those keys is used outside a table, the function uses `key-binding' to
3186 ;; look up if the key has an associated command in another currently active
3187 ;; keymap (minor modes, major mode, global), and executes that command.
3188 ;; There might be problems if any of the keys used by the table editor is
3189 ;; otherwise used as a prefix key.
3191 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3192 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3193 ;; addresses this by checking explicitly for both bindings.
3195 ;; The optimized version (see variable `orgtbl-optimized') takes over
3196 ;; all keys which are bound to `self-insert-command' in the *global map*.
3197 ;; Some modes bind other commands to simple characters, for example
3198 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3199 ;; active, this binding is ignored inside tables and replaced with a
3200 ;; modified self-insert.
3202 (defvar orgtbl-mode nil
3203 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
3204 table editor in arbitrary modes.")
3205 (make-variable-buffer-local 'orgtbl-mode
)
3207 (defvar orgtbl-mode-map
(make-keymap)
3208 "Keymap for `orgtbl-mode'.")
3211 (defun turn-on-orgtbl ()
3212 "Unconditionally turn on `orgtbl-mode'."
3215 (defvar org-old-auto-fill-inhibit-regexp nil
3216 "Local variable used by `orgtbl-mode'")
3218 (defconst orgtbl-line-start-regexp
"[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
3219 "Matches a line belonging to an orgtbl.")
3221 (defconst orgtbl-extra-font-lock-keywords
3222 (list (list (concat "^" orgtbl-line-start-regexp
".*")
3223 0 (quote 'org-table
) 'prepend
))
3224 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
3227 (defun orgtbl-mode (&optional arg
)
3228 "The `org-mode' table editor as a minor mode for use in other modes."
3230 (org-load-modules-maybe)
3232 ;; Exit without error, in case some hook functions calls this
3233 ;; by accident in org-mode.
3234 (message "Orgtbl-mode is not useful in org-mode, command ignored")
3236 (if arg
(> (prefix-numeric-value arg
) 0) (not orgtbl-mode
)))
3239 (and (orgtbl-setup) (defun orgtbl-setup () nil
))
3240 ;; Make sure we are first in minor-mode-map-alist
3241 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
3242 (and c
(setq minor-mode-map-alist
3243 (cons c
(delq c minor-mode-map-alist
)))))
3244 (org-set-local (quote org-table-may-need-update
) t
)
3245 (org-add-hook 'before-change-functions
'org-before-change-function
3247 (org-set-local 'org-old-auto-fill-inhibit-regexp
3248 auto-fill-inhibit-regexp
)
3249 (org-set-local 'auto-fill-inhibit-regexp
3250 (if auto-fill-inhibit-regexp
3251 (concat orgtbl-line-start-regexp
"\\|"
3252 auto-fill-inhibit-regexp
)
3253 orgtbl-line-start-regexp
))
3254 (org-add-to-invisibility-spec '(org-cwidth))
3255 (when (fboundp 'font-lock-add-keywords
)
3256 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
3257 (org-restart-font-lock))
3258 (easy-menu-add orgtbl-mode-menu
)
3259 (run-hooks 'orgtbl-mode-hook
))
3260 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
3261 (org-table-cleanup-narrow-column-properties)
3262 (org-remove-from-invisibility-spec '(org-cwidth))
3263 (remove-hook 'before-change-functions
'org-before-change-function t
)
3264 (when (fboundp 'font-lock-remove-keywords
)
3265 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
3266 (org-restart-font-lock))
3267 (easy-menu-remove orgtbl-mode-menu
)
3268 (force-mode-line-update 'all
))))
3270 (defun org-table-cleanup-narrow-column-properties ()
3271 "Remove all properties related to narrow-column invisibility."
3273 (while (setq s
(text-property-any s
(point-max)
3274 'display org-narrow-column-arrow
))
3275 (remove-text-properties s
(1+ s
) '(display t
)))
3277 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
3278 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
3280 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
3281 (remove-text-properties s
(1+ s
) '(invisible t
)))))
3283 ;; Install it as a minor mode.
3284 (put 'orgtbl-mode
:included t
)
3285 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
3286 (add-minor-mode 'orgtbl-mode
" OrgTbl" orgtbl-mode-map
)
3288 (defun orgtbl-make-binding (fun n
&rest keys
)
3289 "Create a function for binding in the table minor mode.
3290 FUN is the command to call inside a table. N is used to create a unique
3291 command name. KEYS are keys that should be checked in for a command
3292 to execute outside of tables."
3295 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
3297 (concat "In tables, run `" (symbol-name fun
) "'.\n"
3298 "Outside of tables, run the binding of `"
3299 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
3304 (list 'call-interactively
(list 'quote fun
))
3305 (list 'let
'(orgtbl-mode)
3306 (list 'call-interactively
3309 (list 'key-binding k
))
3311 '('orgtbl-error
))))))))
3313 (defun orgtbl-error ()
3314 "Error when there is no default binding for a table key."
3316 (error "This key has no function outside tables"))
3318 (defun orgtbl-setup ()
3319 "Setup orgtbl keymaps."
3323 '([(meta shift left
)] org-table-delete-column
)
3324 '([(meta left
)] org-table-move-column-left
)
3325 '([(meta right
)] org-table-move-column-right
)
3326 '([(meta shift right
)] org-table-insert-column
)
3327 '([(meta shift up
)] org-table-kill-row
)
3328 '([(meta shift down
)] org-table-insert-row
)
3329 '([(meta up
)] org-table-move-row-up
)
3330 '([(meta down
)] org-table-move-row-down
)
3331 '("\C-c\C-w" org-table-cut-region
)
3332 '("\C-c\M-w" org-table-copy-region
)
3333 '("\C-c\C-y" org-table-paste-rectangle
)
3334 '("\C-c-" org-table-insert-hline
)
3335 '("\C-c}" org-table-toggle-coordinate-overlays
)
3336 '("\C-c{" org-table-toggle-formula-debugger
)
3337 '("\C-m" org-table-next-row
)
3338 '([(shift return
)] org-table-copy-down
)
3339 '("\C-c?" org-table-field-info
)
3340 '("\C-c " org-table-blank-field
)
3341 '("\C-c+" org-table-sum
)
3342 '("\C-c=" org-table-eval-formula
)
3343 '("\C-c'" org-table-edit-formulas
)
3344 '("\C-c`" org-table-edit-field
)
3345 '("\C-c*" org-table-recalculate
)
3346 '("\C-c^" org-table-sort-lines
)
3347 '([(control ?
#)] org-table-rotate-recalc-marks
)))
3349 (while (setq elt
(pop bindings
))
3350 (setq nfunc
(1+ nfunc
))
3351 (setq key
(org-key (car elt
))
3353 cmd
(orgtbl-make-binding fun nfunc key
))
3354 (org-defkey orgtbl-mode-map key cmd
))
3356 ;; Special treatment needed for TAB and RET
3357 (org-defkey orgtbl-mode-map
[(return)]
3358 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
3359 (org-defkey orgtbl-mode-map
"\C-m"
3360 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
3362 (org-defkey orgtbl-mode-map
[(tab)]
3363 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
3364 (org-defkey orgtbl-mode-map
"\C-i"
3365 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
3367 (org-defkey orgtbl-mode-map
[(shift tab
)]
3368 (orgtbl-make-binding 'org-table-previous-field
104
3369 [(shift tab
)] [(tab)] "\C-i"))
3371 (org-defkey orgtbl-mode-map
"\M-\C-m"
3372 (orgtbl-make-binding 'org-table-wrap-region
105
3373 "\M-\C-m" [(meta return
)]))
3374 (org-defkey orgtbl-mode-map
[(meta return
)]
3375 (orgtbl-make-binding 'org-table-wrap-region
106
3376 [(meta return
)] "\M-\C-m"))
3378 (org-defkey orgtbl-mode-map
"\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c
)
3379 (org-defkey orgtbl-mode-map
"\C-c|" 'orgtbl-create-or-convert-from-region
)
3381 (when orgtbl-optimized
3382 ;; If the user wants maximum table support, we need to hijack
3383 ;; some standard editing functions
3384 (org-remap orgtbl-mode-map
3385 'self-insert-command
'orgtbl-self-insert-command
3386 'delete-char
'org-delete-char
3387 'delete-backward-char
'org-delete-backward-char
)
3388 (org-defkey orgtbl-mode-map
"|" 'org-force-self-insert
))
3389 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map
"OrgTbl menu"
3391 ["Create or convert" org-table-create-or-convert-from-region
3392 :active
(not (org-at-table-p)) :keys
"C-c |" ]
3394 ["Align" org-ctrl-c-ctrl-c
:active
(org-at-table-p) :keys
"C-c C-c"]
3395 ["Next Field" org-cycle
:active
(org-at-table-p) :keys
"TAB"]
3396 ["Previous Field" org-shifttab
:active
(org-at-table-p) :keys
"S-TAB"]
3397 ["Next Row" org-return
:active
(org-at-table-p) :keys
"RET"]
3399 ["Blank Field" org-table-blank-field
:active
(org-at-table-p) :keys
"C-c SPC"]
3400 ["Edit Field" org-table-edit-field
:active
(org-at-table-p) :keys
"C-c ` "]
3401 ["Copy Field from Above"
3402 org-table-copy-down
:active
(org-at-table-p) :keys
"S-RET"]
3405 ["Move Column Left" org-metaleft
:active
(org-at-table-p) :keys
"M-<left>"]
3406 ["Move Column Right" org-metaright
:active
(org-at-table-p) :keys
"M-<right>"]
3407 ["Delete Column" org-shiftmetaleft
:active
(org-at-table-p) :keys
"M-S-<left>"]
3408 ["Insert Column" org-shiftmetaright
:active
(org-at-table-p) :keys
"M-S-<right>"])
3410 ["Move Row Up" org-metaup
:active
(org-at-table-p) :keys
"M-<up>"]
3411 ["Move Row Down" org-metadown
:active
(org-at-table-p) :keys
"M-<down>"]
3412 ["Delete Row" org-shiftmetaup
:active
(org-at-table-p) :keys
"M-S-<up>"]
3413 ["Insert Row" org-shiftmetadown
:active
(org-at-table-p) :keys
"M-S-<down>"]
3414 ["Sort lines in region" org-table-sort-lines
:active
(org-at-table-p) :keys
"C-c ^"]
3416 ["Insert Hline" org-table-insert-hline
:active
(org-at-table-p) :keys
"C-c -"])
3418 ["Copy Rectangle" org-copy-special
:active
(org-at-table-p)]
3419 ["Cut Rectangle" org-cut-special
:active
(org-at-table-p)]
3420 ["Paste Rectangle" org-paste-special
:active
(org-at-table-p)]
3421 ["Fill Rectangle" org-table-wrap-region
:active
(org-at-table-p)])
3424 ["Insert table template" orgtbl-insert-radio-table
3425 (assq major-mode orgtbl-radio-table-templates
)]
3426 ["Comment/uncomment table" orgtbl-toggle-comment t
])
3428 ["Set Column Formula" org-table-eval-formula
:active
(org-at-table-p) :keys
"C-c ="]
3429 ["Set Field Formula" (org-table-eval-formula '(4)) :active
(org-at-table-p) :keys
"C-u C-c ="]
3430 ["Edit Formulas" org-table-edit-formulas
:active
(org-at-table-p) :keys
"C-c '"]
3431 ["Recalculate line" org-table-recalculate
:active
(org-at-table-p) :keys
"C-c *"]
3432 ["Recalculate all" (org-table-recalculate '(4)) :active
(org-at-table-p) :keys
"C-u C-c *"]
3433 ["Iterate all" (org-table-recalculate '(16)) :active
(org-at-table-p) :keys
"C-u C-u C-c *"]
3434 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks
:active
(org-at-table-p) :keys
"C-c #"]
3435 ["Sum Column/Rectangle" org-table-sum
3436 :active
(or (org-at-table-p) (org-region-active-p)) :keys
"C-c +"]
3437 ["Which Column?" org-table-current-column
:active
(org-at-table-p) :keys
"C-c ?"]
3439 org-table-toggle-formula-debugger
:active
(org-at-table-p)
3441 :style toggle
:selected org-table-formula-debug
]
3442 ["Show Col/Row Numbers"
3443 org-table-toggle-coordinate-overlays
:active
(org-at-table-p)
3445 :style toggle
:selected org-table-overlay-coordinates
]
3449 (defun orgtbl-ctrl-c-ctrl-c (arg)
3450 "If the cursor is inside a table, realign the table.
3451 It it is a table to be sent away to a receiver, do it.
3452 With prefix arg, also recompute table."
3454 (let ((pos (point)) action
)
3456 (beginning-of-line 1)
3457 (setq action
(cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
3458 ((looking-at "[ \t]*|") pos
)
3459 ((looking-at "#\\+TBLFM:") 'recalc
))))
3463 (org-table-maybe-eval-formula)
3465 (call-interactively 'org-table-recalculate
)
3466 (org-table-maybe-recalculate-line))
3467 (call-interactively 'org-table-align
)
3468 (orgtbl-send-table 'maybe
))
3469 ((eq action
'recalc
)
3471 (beginning-of-line 1)
3472 (skip-chars-backward " \r\n\t")
3473 (if (org-at-table-p)
3474 (org-call-with-arg 'org-table-recalculate t
))))
3475 (t (let (orgtbl-mode)
3476 (call-interactively (key-binding "\C-c\C-c")))))))
3478 (defun orgtbl-create-or-convert-from-region (arg)
3479 "Create table or convert region to table, if no conflicting binding.
3480 This installs the table binding `C-c |', but only if there is no
3481 conflicting binding to this key outside orgtbl-mode."
3483 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
3485 (call-interactively cmd
)
3486 (call-interactively 'org-table-create-or-convert-from-region
))))
3488 (defun orgtbl-tab (arg)
3489 "Justification and field motion for `orgtbl-mode'."
3491 (if arg
(org-table-edit-field t
)
3492 (org-table-justify-field-maybe)
3493 (org-table-next-field)))
3495 (defun orgtbl-ret ()
3496 "Justification and field motion for `orgtbl-mode'."
3500 (org-table-justify-field-maybe)
3501 (org-table-next-row)))
3503 (defun orgtbl-self-insert-command (N)
3504 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
3505 If the cursor is in a table looking at whitespace, the whitespace is
3506 overwritten, and the table is not marked as requiring realignment."
3508 (if (and (org-at-table-p)
3510 (and org-table-auto-blank-field
3511 (member last-command
3512 '(orgtbl-hijacker-command-100
3513 orgtbl-hijacker-command-101
3514 orgtbl-hijacker-command-102
3515 orgtbl-hijacker-command-103
3516 orgtbl-hijacker-command-104
3517 orgtbl-hijacker-command-105
))
3518 (org-table-blank-field))
3521 (looking-at "[^|\n]* +|"))
3522 (let (org-table-may-need-update)
3523 (goto-char (1- (match-end 0)))
3524 (delete-backward-char 1)
3525 (goto-char (match-beginning 0))
3526 (self-insert-command N
))
3527 (setq org-table-may-need-update t
)
3528 (let (orgtbl-mode a
)
3531 (or (and (listp function-key-map
)
3532 (setq a
(assoc last-input-event function-key-map
))
3534 (vector last-input-event
)))
3535 'self-insert-command
)))))
3537 (defvar orgtbl-exp-regexp
"^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
3538 "Regular expression matching exponentials as produced by calc.")
3540 (defun orgtbl-export (table target
)
3542 (let ((func (intern (concat "orgtbl-to-" (symbol-name target
))))
3543 (lines (org-split-string table
"[ \t]*\n[ \t]*"))
3544 org-table-last-alignment org-table-last-column-widths
3546 (if (not (fboundp func
))
3547 (error "Cannot export orgtbl table to %s" target
))
3548 (setq lines
(org-table-clean-before-export lines
))
3552 (if (string-match org-table-hline-regexp x
)
3554 (org-split-string (org-trim x
) "\\s-*|\\s-*")))
3556 (setq maxcol
(apply 'max
(mapcar (lambda (x) (if (listp x
) (length x
) 0))
3558 (loop for i from
(1- maxcol
) downto
0 do
3559 (setq column
(mapcar (lambda (x) (if (listp x
) (nth i x
) nil
)) table
))
3560 (setq column
(delq nil column
))
3561 (push (apply 'max
(mapcar 'string-width column
)) org-table-last-column-widths
)
3562 (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
))
3563 (funcall func table nil
)))
3565 (defun orgtbl-gather-send-defs ()
3566 "Gathers a plist of :name, :transform, :params for each destination before
3569 (goto-char (org-table-begin))
3571 (beginning-of-line 0)
3572 (while (looking-at "#\\+ORGTBL[: \t][ \t]*SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
3573 (let ((name (org-no-properties (match-string 1)))
3574 (transform (intern (match-string 2)))
3575 (params (if (match-end 3)
3576 (read (concat "(" (match-string 3) ")")))))
3577 (push (list :name name
:transform transform
:params params
)
3579 (beginning-of-line 0)))
3582 (defun orgtbl-send-replace-tbl (name txt
)
3583 "Find and replace table NAME with TXT."
3585 (goto-char (point-min))
3586 (unless (re-search-forward
3587 (concat "BEGIN RECEIVE ORGTBL +" name
"\\([ \t]\\|$\\)") nil t
)
3588 (error "Don't know where to insert translated table"))
3589 (goto-char (match-beginning 0))
3590 (beginning-of-line 2)
3592 (let ((beg (point)))
3593 (unless (re-search-forward
3594 (concat "END RECEIVE ORGTBL +" name
) nil t
)
3595 (error "Cannot find end of insertion region"))
3596 (beginning-of-line 1)
3597 (delete-region beg
(point))))
3601 (defun org-table-to-lisp (&optional txt
)
3602 "Convert the table at point to a Lisp structure.
3603 The structure will be a list. Each item is either the symbol `hline'
3604 for a horizontal separator line, or a list of field values as strings.
3605 The table is taken from the parameter TXT, or from the buffer at point."
3607 (unless (org-at-table-p)
3608 (error "No table at point")))
3610 (buffer-substring-no-properties (org-table-begin)
3612 (lines (org-split-string txt
"[ \t]*\n[ \t]*")))
3616 (if (string-match org-table-hline-regexp x
)
3618 (org-split-string (org-trim x
) "\\s-*|\\s-*")))
3621 (defun orgtbl-send-table (&optional maybe
)
3622 "Send a transformed version of this table to the receiver position.
3623 With argument MAYBE, fail quietly if no transformation is defined for
3627 (unless (org-at-table-p) (error "Not at a table"))
3628 ;; when non-interactive, we assume align has just happened.
3629 (when (interactive-p) (org-table-align))
3630 (let ((dests (orgtbl-gather-send-defs))
3631 (txt (buffer-substring-no-properties (org-table-begin)
3634 (unless dests
(if maybe
(throw 'exit nil
)
3635 (error "Don't know how to transform this table.")))
3636 (dolist (dest dests
)
3637 (let* ((name (plist-get dest
:name
))
3638 (transform (plist-get dest
:transform
))
3639 (params (plist-get dest
:params
))
3640 (skip (plist-get params
:skip
))
3641 (skipcols (plist-get params
:skipcols
))
3643 (lines (org-table-clean-before-export
3645 (org-split-string txt
"[ \t]*\n[ \t]*"))))
3646 (i0 (if org-table-clean-did-remove-column
2 1))
3649 (if (string-match org-table-hline-regexp x
)
3651 (org-remove-by-index
3652 (org-split-string (org-trim x
) "\\s-*|\\s-*")
3655 (fun (if (= i0
2) 'cdr
'identity
))
3656 (org-table-last-alignment
3657 (org-remove-by-index (funcall fun org-table-last-alignment
)
3659 (org-table-last-column-widths
3660 (org-remove-by-index (funcall fun org-table-last-column-widths
)
3662 (txt (if (fboundp transform
)
3663 (funcall transform table params
)
3664 (error "No such transformation function %s" transform
))))
3665 (orgtbl-send-replace-tbl name txt
))
3666 (setq ntbl
(1+ ntbl
)))
3667 (message "Table converted and installed at %d receiver location%s"
3668 ntbl
(if (> ntbl
1) "s" "")))))
3670 (defun org-remove-by-index (list indices
&optional i0
)
3671 "Remove the elements in LIST with indices in INDICES.
3672 First element has index 0, or I0 if given."
3675 (if (integerp indices
) (setq indices
(list indices
)))
3676 (setq i0
(1- (or i0
0)))
3677 (delq :rm
(mapcar (lambda (x)
3679 (if (memq i0 indices
) :rm x
))
3682 (defun orgtbl-toggle-comment ()
3683 "Comment or uncomment the orgtbl at point."
3685 (let* ((re1 (concat "^" (regexp-quote comment-start
) orgtbl-line-start-regexp
))
3686 (re2 (concat "^" orgtbl-line-start-regexp
))
3687 (commented (save-excursion (beginning-of-line 1)
3688 (cond ((looking-at re1
) t
)
3689 ((looking-at re2
) nil
)
3690 (t (error "Not at an org table")))))
3691 (re (if commented re1 re2
))
3694 (beginning-of-line 1)
3695 (while (looking-at re
) (beginning-of-line 0))
3696 (beginning-of-line 2)
3698 (while (looking-at re
) (beginning-of-line 2))
3700 (comment-region beg end
(if commented
'(4) nil
))))
3702 (defun orgtbl-insert-radio-table ()
3703 "Insert a radio table template appropriate for this major mode."
3705 (let* ((e (assq major-mode orgtbl-radio-table-templates
))
3708 (unless e
(error "No radio table setup defined for %s" major-mode
))
3709 (setq name
(read-string "Table name: "))
3710 (while (string-match "%n" txt
)
3711 (setq txt
(replace-match name t t txt
)))
3712 (or (bolp) (insert "\n"))
3717 ;; Dynamically bound input and output for table formatting.
3718 (defvar *orgtbl-table
* nil
3719 "Carries the current table through formatting routines.")
3720 (defvar *orgtbl-rtn
* nil
3721 "Formatting routines push the output lines here.")
3722 ;; Formatting parameters for the current table section.
3723 (defvar *orgtbl-hline
* nil
"Text used for horizontal lines")
3724 (defvar *orgtbl-sep
* nil
"Text used as a column separator")
3725 (defvar *orgtbl-default-fmt
* nil
"Default format for each entry")
3726 (defvar *orgtbl-fmt
* nil
"Format for each entry")
3727 (defvar *orgtbl-efmt
* nil
"Format for numbers")
3728 (defvar *orgtbl-lfmt
* nil
"Format for an entire line, overrides fmt")
3729 (defvar *orgtbl-llfmt
* nil
"Specializes lfmt for the last row")
3730 (defvar *orgtbl-lstart
* nil
"Text starting a row")
3731 (defvar *orgtbl-llstart
* nil
"Specializes lstart for the last row")
3732 (defvar *orgtbl-lend
* nil
"Text ending a row")
3733 (defvar *orgtbl-llend
* nil
"Specializes lend for the last row")
3735 (defsubst orgtbl-get-fmt
(fmt i
)
3736 "Retrieve the format from FMT corresponding to the Ith column."
3737 (if (and (not (functionp fmt
)) (consp fmt
))
3741 (defsubst orgtbl-apply-fmt
(fmt &rest args
)
3742 "Apply format FMT to the arguments. NIL FMTs return the first argument."
3743 (cond ((functionp fmt
) (apply fmt args
))
3744 (fmt (apply 'format fmt args
))
3748 (defsubst orgtbl-eval-str
(str)
3749 "If STR is a function, evaluate it with no arguments."
3754 (defun orgtbl-format-line (line)
3755 "Format LINE as a table row."
3756 (if (eq line
'hline
) (if *orgtbl-hline
* (push *orgtbl-hline
* *orgtbl-rtn
*))
3762 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt
* i
))
3763 (f (if (and efmt
(string-match orgtbl-exp-regexp f
))
3764 (orgtbl-apply-fmt efmt
(match-string 1 f
)
3767 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt
* i
)
3768 *orgtbl-default-fmt
*)
3771 (push (if *orgtbl-lfmt
*
3772 (orgtbl-apply-fmt *orgtbl-lfmt
* line
)
3773 (concat (orgtbl-eval-str *orgtbl-lstart
*)
3774 (mapconcat 'identity line
*orgtbl-sep
*)
3775 (orgtbl-eval-str *orgtbl-lend
*)))
3778 (defun orgtbl-format-section (section-stopper)
3779 "Format lines until the first occurrence of SECTION-STOPPER."
3782 (while (not (eq (car *orgtbl-table
*) section-stopper
))
3783 (if prevline
(orgtbl-format-line prevline
))
3784 (setq prevline
(pop *orgtbl-table
*)))
3785 (if prevline
(let ((*orgtbl-lstart
* *orgtbl-llstart
*)
3786 (*orgtbl-lend
* *orgtbl-llend
*)
3787 (*orgtbl-lfmt
* *orgtbl-llfmt
*))
3788 (orgtbl-format-line prevline
))))))
3790 (defun orgtbl-to-generic (table params
)
3791 "Convert the orgtbl-mode TABLE to some other format.
3792 This generic routine can be used for many standard cases.
3793 TABLE is a list, each entry either the symbol `hline' for a horizontal
3794 separator line, or a list of fields for that line.
3795 PARAMS is a property list of parameters that can influence the conversion.
3796 For the generic converter, some parameters are obligatory: You need to
3797 specify either :lfmt, or all of (:lstart :lend :sep).
3799 Valid parameters are
3801 :splice When set to t, return only table body lines, don't wrap
3802 them into :tstart and :tend. Default is nil. When :splice
3803 is non-nil, this also means that the exporter should not look
3804 for and interpret header and footer sections.
3806 :hline String to be inserted on horizontal separation lines.
3807 May be nil to ignore hlines.
3809 :sep Separator between two fields
3810 :remove-nil-lines Do not include lines that evaluate to nil.
3813 Each in the following group may be either a string or a function
3814 of no arguments returning a string:
3815 :tstart String to start the table. Ignored when :splice is t.
3816 :tend String to end the table. Ignored when :splice is t.
3817 :lstart String to start a new table line.
3818 :llstart String to start the last table line, defaults to :lstart.
3819 :lend String to end a table line
3820 :llend String to end the last table line, defaults to :lend.
3822 Each in the following group may be a string, a function of one
3823 argument (the field or line) returning a string, or a plist
3824 mapping columns to either of the above:
3825 :lfmt Format for entire line, with enough %s to capture all fields.
3826 If this is present, :lstart, :lend, and :sep are ignored.
3827 :llfmt Format for the entire last line, defaults to :lfmt.
3828 :fmt A format to be used to wrap the field, should contain
3829 %s for the original field value. For example, to wrap
3830 everything in dollars, you could use :fmt \"$%s$\".
3831 This may also be a property list with column numbers and
3832 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
3834 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
3835 Same as above, specific for the header lines in the table.
3836 All lines before the first hline are treated as header.
3837 If any of these is not present, the data line value is used.
3839 This may be either a string or a function of two arguments:
3840 :efmt Use this format to print numbers with exponentials.
3841 The format should have %s twice for inserting mantissa
3842 and exponent, for example \"%s\\\\times10^{%s}\". This
3843 may also be a property list with column numbers and
3844 formats. :fmt will still be applied after :efmt.
3846 In addition to this, the parameters :skip and :skipcols are always handled
3847 directly by `orgtbl-send-table'. See manual."
3850 (let* ((splicep (plist-get params
:splice
))
3851 (hline (plist-get params
:hline
))
3852 (remove-nil-linesp (plist-get params
:remove-nil-lines
))
3853 (*orgtbl-hline
* hline
)
3854 (*orgtbl-table
* table
)
3855 (*orgtbl-sep
* (plist-get params
:sep
))
3856 (*orgtbl-efmt
* (plist-get params
:efmt
))
3857 (*orgtbl-lstart
* (plist-get params
:lstart
))
3858 (*orgtbl-llstart
* (or (plist-get params
:llstart
) *orgtbl-lstart
*))
3859 (*orgtbl-lend
* (plist-get params
:lend
))
3860 (*orgtbl-llend
* (or (plist-get params
:llend
) *orgtbl-lend
*))
3861 (*orgtbl-lfmt
* (plist-get params
:lfmt
))
3862 (*orgtbl-llfmt
* (or (plist-get params
:llfmt
) *orgtbl-lfmt
*))
3863 (*orgtbl-fmt
* (plist-get params
:fmt
))
3868 (when (plist-member params
:tstart
)
3869 (let ((tstart (orgtbl-eval-str (plist-get params
:tstart
))))
3870 (if tstart
(push tstart
*orgtbl-rtn
*)))))
3872 ;; Do we have a heading section? If so, format it and handle the
3874 (if (and (not splicep
)
3875 (or (consp (car *orgtbl-table
*))
3876 (consp (nth 1 *orgtbl-table
*)))
3877 (memq 'hline
(cdr *orgtbl-table
*)))
3879 (when (eq 'hline
(car *orgtbl-table
*))
3880 ;; there is a hline before the first data line
3881 (and hline
(push hline
*orgtbl-rtn
*))
3882 (pop *orgtbl-table
*))
3883 (let* ((*orgtbl-lstart
* (or (plist-get params
:hlstart
)
3885 (*orgtbl-llstart
* (or (plist-get params
:hllstart
)
3887 (*orgtbl-lend
* (or (plist-get params
:hlend
) *orgtbl-lend
*))
3888 (*orgtbl-llend
* (or (plist-get params
:hllend
)
3889 (plist-get params
:hlend
) *orgtbl-llend
*))
3890 (*orgtbl-lfmt
* (or (plist-get params
:hlfmt
) *orgtbl-lfmt
*))
3891 (*orgtbl-llfmt
* (or (plist-get params
:hllfmt
)
3892 (plist-get params
:hlfmt
) *orgtbl-llfmt
*))
3893 (*orgtbl-sep
* (or (plist-get params
:hlsep
) *orgtbl-sep
*))
3894 (*orgtbl-fmt
* (or (plist-get params
:hfmt
) *orgtbl-fmt
*)))
3895 (orgtbl-format-section 'hline
))
3896 (if hline
(push hline
*orgtbl-rtn
*))
3897 (pop *orgtbl-table
*)))
3899 ;; Now format the main section.
3900 (orgtbl-format-section nil
)
3903 (when (plist-member params
:tend
)
3904 (let ((tend (orgtbl-eval-str (plist-get params
:tend
))))
3905 (if tend
(push tend
*orgtbl-rtn
*)))))
3907 (mapconcat 'identity
(nreverse (if remove-nil-linesp
3908 (remq nil
*orgtbl-rtn
*)
3909 *orgtbl-rtn
*)) "\n")))
3911 (defun orgtbl-to-tsv (table params
)
3912 "Convert the orgtbl-mode table to TAB separated material."
3913 (orgtbl-to-generic table
(org-combine-plists '(:sep
"\t") params
)))
3914 (defun orgtbl-to-csv (table params
)
3915 "Convert the orgtbl-mode table to CSV material.
3916 This does take care of the proper quoting of fields with comma or quotes."
3917 (orgtbl-to-generic table
(org-combine-plists
3918 '(:sep
"," :fmt org-quote-csv-field
)
3921 (defun orgtbl-to-latex (table params
)
3922 "Convert the orgtbl-mode TABLE to LaTeX.
3923 TABLE is a list, each entry either the symbol `hline' for a horizontal
3924 separator line, or a list of fields for that line.
3925 PARAMS is a property list of parameters that can influence the conversion.
3926 Supports all parameters from `orgtbl-to-generic'. Most important for
3929 :splice When set to t, return only table body lines, don't wrap
3930 them into a tabular environment. Default is nil.
3932 :fmt A format to be used to wrap the field, should contain %s for the
3933 original field value. For example, to wrap everything in dollars,
3934 use :fmt \"$%s$\". This may also be a property list with column
3935 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
3936 The format may also be a function that formats its one argument.
3938 :efmt Format for transforming numbers with exponentials. The format
3939 should have %s twice for inserting mantissa and exponent, for
3940 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
3941 This may also be a property list with column numbers and formats.
3942 The format may also be a function that formats its two arguments.
3944 :llend If you find too much space below the last line of a table,
3945 pass a value of \"\" for :llend to suppress the final \\\\.
3947 The general parameters :skip and :skipcols have already been applied when
3948 this function is called."
3949 (let* ((alignment (mapconcat (lambda (x) (if x
"r" "l"))
3950 org-table-last-alignment
""))
3953 :tstart
(concat "\\begin{tabular}{" alignment
"}")
3954 :tend
"\\end{tabular}"
3955 :lstart
"" :lend
" \\\\" :sep
" & "
3956 :efmt
"%s\\,(%s)" :hline
"\\hline")))
3957 (orgtbl-to-generic table
(org-combine-plists params2 params
))))
3959 (defun orgtbl-to-html (table params
)
3960 "Convert the orgtbl-mode TABLE to LaTeX.
3961 TABLE is a list, each entry either the symbol `hline' for a horizontal
3962 separator line, or a list of fields for that line.
3963 PARAMS is a property list of parameters that can influence the conversion.
3964 Currently this function recognizes the following parameters:
3966 :splice When set to t, return only table body lines, don't wrap
3967 them into a <table> environment. Default is nil.
3969 The general parameters :skip and :skipcols have already been applied when
3970 this function is called. The function does *not* use `orgtbl-to-generic',
3971 so you cannot specify parameters for it."
3972 (let* ((splicep (plist-get params
:splice
))
3973 (html-table-tag org-export-html-table-tag
)
3975 ;; Just call the formatter we already have
3976 ;; We need to make text lines for it, so put the fields back together.
3977 (setq html
(org-format-org-table-html
3982 (concat "| " (mapconcat 'identity x
" | ") " |")))
3985 (if (string-match "\n+\\'" html
)
3986 (setq html
(replace-match "" t t html
)))
3989 (defun orgtbl-to-texinfo (table params
)
3990 "Convert the orgtbl-mode TABLE to TeXInfo.
3991 TABLE is a list, each entry either the symbol `hline' for a horizontal
3992 separator line, or a list of fields for that line.
3993 PARAMS is a property list of parameters that can influence the conversion.
3994 Supports all parameters from `orgtbl-to-generic'. Most important for
3997 :splice nil/t When set to t, return only table body lines, don't wrap
3998 them into a multitable environment. Default is nil.
4000 :fmt fmt A format to be used to wrap the field, should contain
4001 %s for the original field value. For example, to wrap
4002 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4003 This may also be a property list with column numbers and
4004 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4005 Each format also may be a function that formats its one
4008 :cf \"f1 f2..\" The column fractions for the table. By default these
4009 are computed automatically from the width of the columns
4012 The general parameters :skip and :skipcols have already been applied when
4013 this function is called."
4014 (let* ((total (float (apply '+ org-table-last-column-widths
)))
4015 (colfrac (or (plist-get params
:cf
)
4017 (lambda (x) (format "%.3f" (/ (float x
) total
)))
4018 org-table-last-column-widths
" ")))
4021 :tstart
(concat "@multitable @columnfractions " colfrac
)
4022 :tend
"@end multitable"
4023 :lstart
"@item " :lend
"" :sep
" @tab "
4024 :hlstart
"@headitem ")))
4025 (orgtbl-to-generic table
(org-combine-plists params2 params
))))
4027 (defun orgtbl-to-orgtbl (table params
)
4028 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4029 Useful when slicing one table into many. The :hline, :sep,
4030 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4031 and :tend suppress strings without splicing; they can be set to
4032 provide ORGTBL directives for the generated table."
4035 :tstart nil
:tend nil
4040 (params (org-combine-plists params2 params
)))
4041 (orgtbl-to-generic table params
)))
4043 (provide 'org-table
)
4045 ;; arch-tag: 4d21cfdd-0268-440a-84b0-09237a0fe0ef
4047 ;;; org-table.el ends here