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, or (at your option)
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; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
30 ;; This file contains the table editor and spreadsheed for Org-mode.
32 ;; Watch out: Here we are talking about two different kind of tables.
33 ;; Most of the code is for the tables created with the Org-mode table editor.
34 ;; Sometimes, we talk about tables created and edited with the table.el
35 ;; Emacs package. We call the former org-type tables, and the latter
36 ;; table.el-type tables.
44 (declare-function org-table-clean-before-export
"org-exp" (lines))
45 (declare-function org-format-org-table-html
"org-exp" (lines &optional splice
))
46 (defvar orgtbl-mode
) ; defined below
47 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
49 (defvar constants-unit-system
)
51 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
52 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
53 In the optimized version, the table editor takes over all simple keys that
54 normally just insert a character. In tables, the characters are inserted
55 in a way to minimize disturbing the table structure (i.e. in overwrite mode
56 for empty fields). Outside tables, the correct binding of the keys is
59 The default for this option is t if the optimized version is also used in
60 Org-mode. See the variable `org-enable-table-editor' for details. Changing
61 this variable requires a restart of Emacs to become effective."
65 (defcustom orgtbl-radio-table-templates
66 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
67 % END RECEIVE ORGTBL %n
69 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
72 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
73 @c END RECEIVE ORGTBL %n
75 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
78 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
79 <!-- END RECEIVE ORGTBL %n -->
81 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
84 "Templates for radio tables in different major modes.
85 All occurrences of %n in a template will be replaced with the name of the
86 table, obtained by prompting the user."
89 (list (symbol :tag
"Major mode")
90 (string :tag
"Format"))))
92 (defgroup org-table-settings nil
93 "Settings for tables in Org-mode."
94 :tag
"Org Table Settings"
97 (defcustom org-table-default-size
"5x2"
98 "The default size for newly created tables, Columns x Rows."
99 :group
'org-table-settings
102 (defcustom org-table-number-regexp
103 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
104 "Regular expression for recognizing numbers in table columns.
105 If a table column contains mostly numbers, it will be aligned to the
106 right. If not, it will be aligned to the left.
108 The default value of this option is a regular expression which allows
109 anything which looks remotely like a number as used in scientific
110 context. For example, all of the following will be considered a
112 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
114 Other options offered by the customize interface are more restrictive."
115 :group
'org-table-settings
117 (const :tag
"Positive Integers"
119 (const :tag
"Integers"
121 (const :tag
"Floating Point Numbers"
122 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
123 (const :tag
"Floating Point Number or Integer"
124 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
125 (const :tag
"Exponential, Floating point, Integer"
126 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
127 (const :tag
"Very General Number-Like, including hex"
128 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
129 (string :tag
"Regexp:")))
131 (defcustom org-table-number-fraction
0.5
132 "Fraction of numbers in a column required to make the column align right.
133 In a column all non-white fields are considered. If at least this
134 fraction of fields is matched by `org-table-number-fraction',
135 alignment to the right border applies."
136 :group
'org-table-settings
139 (defgroup org-table-editing nil
140 "Behavior of tables during editing in Org-mode."
141 :tag
"Org Table Editing"
144 (defcustom org-table-automatic-realign t
145 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
146 When nil, aligning is only done with \\[org-table-align], or after column
148 :group
'org-table-editing
151 (defcustom org-table-auto-blank-field t
152 "Non-nil means, automatically blank table field when starting to type into it.
153 This only happens when typing immediately after a field motion
154 command (TAB, S-TAB or RET).
155 Only relevant when `org-enable-table-editor' is equal to `optimized'."
156 :group
'org-table-editing
159 (defcustom org-table-tab-jumps-over-hlines t
160 "Non-nil means, tab in the last column of a table with jump over a hline.
161 If a horizontal separator line is following the current line,
162 `org-table-next-field' can either create a new row before that line, or jump
163 over the line. When this option is nil, a new line will be created before
165 :group
'org-table-editing
168 (defgroup org-table-calculation nil
169 "Options concerning tables in Org-mode."
170 :tag
"Org Table Calculation"
173 (defcustom org-table-use-standard-references t
174 "Should org-mode work with table refrences like B3 instead of @3$2?
177 from accept as input, do not present for editing
178 t: accept as input and present for editing"
179 :group
'org-table-calculation
181 (const :tag
"Never, don't even check user input for them" nil
)
182 (const :tag
"Always, both as user input, and when editing" t
)
183 (const :tag
"Convert user input, don't offer during editing" 'from
)))
185 (defcustom org-table-copy-increment t
186 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
187 :group
'org-table-calculation
190 (defcustom org-calc-default-modes
191 '(calc-internal-prec 12
192 calc-float-format
(float 5)
195 calc-symbolic-mode nil
196 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " HH
":" mm
))
197 calc-display-working-message t
199 "List with Calc mode settings for use in calc-eval for table formulas.
200 The list must contain alternating symbols (Calc modes variables and values).
201 Don't remove any of the default settings, just change the values. Org-mode
202 relies on the variables to be present in the list."
203 :group
'org-table-calculation
206 (defcustom org-table-formula-evaluate-inline t
207 "Non-nil means, TAB and RET evaluate a formula in current table field.
208 If the current field starts with an equal sign, it is assumed to be a formula
209 which should be evaluated as described in the manual and in the documentation
210 string of the command `org-table-eval-formula'. This feature requires the
212 When this variable is nil, formula calculation is only available through
213 the command \\[org-table-eval-formula]."
214 :group
'org-table-calculation
217 (defcustom org-table-formula-use-constants t
218 "Non-nil means, interpret constants in formulas in tables.
219 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
220 by the value given in `org-table-formula-constants', or by a value obtained
221 from the `constants.el' package."
222 :group
'org-table-calculation
225 (defcustom org-table-formula-constants nil
226 "Alist with constant names and values, for use in table formulas.
227 The car of each element is a name of a constant, without the `$' before it.
228 The cdr is the value as a string. For example, if you'd like to use the
229 speed of light in a formula, you would configure
231 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
233 and then use it in an equation like `$1*$c'.
235 Constants can also be defined on a per-file basis using a line like
237 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
238 :group
'org-table-calculation
240 (cons (string :tag
"name")
241 (string :tag
"value"))))
243 (defcustom org-table-allow-automatic-line-recalculation t
244 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
245 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
246 :group
'org-table-calculation
249 (defgroup org-table-import-export nil
250 "Options concerning table import and export in Org-mode."
251 :tag
"Org Table Import Export"
254 (defcustom org-table-export-default-format
255 "orgtbl-to-generic :splice t :sep \"\t\""
256 "Default export parameters for org-table-export. These can be
257 overridden on for a specific table by setting the
258 TABLE_EXPORT_FORMAT parameter. See orgtbl-export for the
259 different export transforms and available parameters."
260 :group
'org-table-import-export
263 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
264 "Detects a table line marked for automatic recalculation.")
265 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
266 "Detects a table line marked for automatic recalculation.")
267 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
268 "Detects a table line marked for automatic recalculation.")
269 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
270 "Searching from within a table (any type) this finds the first line
272 (defvar org-table-last-highlighted-reference nil
)
273 (defvar org-table-formula-history nil
)
275 (defvar org-table-column-names nil
276 "Alist with column names, derived from the `!' line.")
277 (defvar org-table-column-name-regexp nil
278 "Regular expression matching the current column names.")
279 (defvar org-table-local-parameters nil
280 "Alist with parameter names, derived from the `$' line.")
281 (defvar org-table-named-field-locations nil
282 "Alist with locations of named fields.")
284 (defvar org-table-current-line-types nil
285 "Table row types, non-nil only for the duration of a comand.")
286 (defvar org-table-current-begin-line nil
287 "Table begin line, non-nil only for the duration of a comand.")
288 (defvar org-table-current-begin-pos nil
289 "Table begin position, non-nil only for the duration of a comand.")
290 (defvar org-table-dlines nil
291 "Vector of data line line numbers in the current table.")
292 (defvar org-table-hlines nil
293 "Vector of hline line numbers in the current table.")
295 (defconst org-table-range-regexp
296 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
298 "Regular expression for matching ranges in formulas.")
300 (defconst org-table-range-regexp2
302 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
304 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
305 "Match a range for reference display.")
307 (defconst org-table-translate-regexp
308 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
309 "Match a reference that needs translation, for reference display.")
311 (defun org-table-create-with-table.el
()
312 "Use the table.el package to insert a new table.
313 If there is already a table at point, convert between Org-mode tables
314 and table.el tables."
319 (if (y-or-n-p "Convert table to Org-mode table? ")
320 (org-table-convert)))
322 (if (y-or-n-p "Convert table to table.el table? ")
323 (org-table-convert)))
324 (t (call-interactively 'table-insert
))))
326 (defun org-table-create-or-convert-from-region (arg)
327 "Convert region to table, or create an empty table.
328 If there is an active region, convert it to a table, using the function
329 `org-table-convert-region'. See the documentation of that function
330 to learn how the prefix argument is interpreted to determine the field
332 If there is no such region, create an empty table with `org-table-create'."
334 (if (org-region-active-p)
335 (org-table-convert-region (region-beginning) (region-end) arg
)
336 (org-table-create arg
)))
338 (defun org-table-create (&optional size
)
339 "Query for a size and insert a table skeleton.
340 SIZE is a string Columns x Rows like for example \"3x2\"."
343 (setq size
(read-string
344 (concat "Table size Columns x Rows [e.g. "
345 org-table-default-size
"]: ")
346 "" nil org-table-default-size
)))
349 (indent (make-string (current-column) ?\
))
350 (split (org-split-string size
" *x *"))
351 (rows (string-to-number (nth 1 split
)))
352 (columns (string-to-number (car split
)))
353 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
355 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
356 (point-at-bol) (point)))
357 (beginning-of-line 1)
359 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
360 (dotimes (i rows
) (insert line
))
363 ;; Insert a hline after the first row.
370 (defun org-table-convert-region (beg0 end0
&optional separator
)
371 "Convert region to a table.
372 The region goes from BEG0 to END0, but these borders will be moved
373 slightly, to make sure a beginning of line in the first line is included.
375 SEPARATOR specifies the field separator in the lines. It can have the
378 '(4) Use the comma as a field separator
379 '(16) Use a TAB as field separator
380 integer When a number, use that many spaces as field separator
381 nil When nil, the command tries to be smart and figure out the
382 separator in the following way:
383 - when each line contains a TAB, assume TAB-separated material
384 - when each line contains a comme, assume CSV material
385 - else, assume one or more SPACE charcters as separator."
387 (let* ((beg (min beg0 end0
))
388 (end (max beg0 end0
))
391 (beginning-of-line 1)
392 (setq beg
(move-marker (make-marker) (point)))
394 (if (bolp) (backward-char 1) (end-of-line 1))
395 (setq end
(move-marker (make-marker) (point)))
396 ;; Get the right field separator
401 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
402 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
405 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
406 ((equal separator
'(16)) "^\\|\t")
407 ((integerp separator
)
408 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
))
409 (t (error "This should not happen"))))
411 (while (re-search-forward re end t
)
412 (replace-match "| " t t
))
417 (defun org-table-import (file arg
)
418 "Import FILE as a table.
419 The file is assumed to be tab-separated. Such files can be produced by most
420 spreadsheet and database applications. If no tabs (at least one per line)
421 are found, lines will be split on whitespace into fields."
423 (or (bolp) (newline))
426 (insert-file-contents file
)
427 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
430 (defvar org-table-last-alignment
)
431 (defvar org-table-last-column-widths
)
432 (defun org-table-export (&optional file format
)
433 "Export table as a tab-separated file.
434 Such a file can be imported into a spreadsheet program like Excel.
435 FILE can be the output file name. If not given, it will be taken from
436 a TABLE_EXPORT_FILE property in the current entry or higher up in the
437 hierarchy, or the user will be prompted for a file name.
438 FORMAT can be an export format, of the same kind as it used when
439 orgtbl-mode sends a table in a different format. The default format can
440 be found in the variable `org-table-export-default-format', but the function
441 first checks if there is an export format specified in a TABLE_EXPORT_FORMAT
442 property, locally or anywhere up in the hierarchy."
444 (org-table-align) ;; make sure we have everything we need
445 (let* ((beg (org-table-begin))
446 (end (org-table-end))
447 (txt (buffer-substring-no-properties beg end
))
448 (file (or file
(org-entry-get beg
"TABLE_EXPORT_FILE" t
)
449 (read-file-name "Export table to: ")))
450 (format (or (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)
451 org-table-export-default-format
))
453 (unless (or (not (file-exists-p file
))
454 (y-or-n-p (format "Overwrite file %s? " file
)))
458 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
459 (let* ((transform (intern (match-string 1 format
)))
460 (params (if (match-end 2)
461 (read (concat "(" (match-string 2 format
) ")"))))
462 (skip (plist-get params
:skip
))
463 (skipcols (plist-get params
:skipcols
))
464 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
465 (lines (org-table-clean-before-export lines
))
466 (i0 (if org-table-clean-did-remove-column
2 1))
469 (if (string-match org-table-hline-regexp x
)
472 (org-split-string (org-trim x
) "\\s-*|\\s-*")
475 (fun (if (= i0
2) 'cdr
'identity
))
476 (org-table-last-alignment
477 (org-remove-by-index (funcall fun org-table-last-alignment
)
479 (org-table-last-column-widths
480 (org-remove-by-index (funcall fun org-table-last-column-widths
)
483 (unless (fboundp transform
)
484 (error "No such transformation function %s" transform
))
485 (setq txt
(funcall transform table params
))
487 (with-current-buffer (find-file-noselect file
)
488 (setq buf
(current-buffer))
494 (message "Export done."))
495 (error "TABLE_EXPORT_FORMAT invalid"))))
497 (defvar org-table-aligned-begin-marker
(make-marker)
498 "Marker at the beginning of the table last aligned.
499 Used to check if cursor still is in that table, to minimize realignment.")
500 (defvar org-table-aligned-end-marker
(make-marker)
501 "Marker at the end of the table last aligned.
502 Used to check if cursor still is in that table, to minimize realignment.")
503 (defvar org-table-last-alignment nil
504 "List of flags for flushright alignment, from the last re-alignment.
505 This is being used to correctly align a single field after TAB or RET.")
506 (defvar org-table-last-column-widths nil
507 "List of max width of fields in each column.
508 This is being used to correctly align a single field after TAB or RET.")
509 (defvar org-table-formula-debug nil
510 "Non-nil means, debug table formulas.
511 When nil, simply write \"#ERROR\" in corrupted fields.")
512 (make-variable-buffer-local 'org-table-formula-debug
)
513 (defvar org-table-overlay-coordinates nil
514 "Overlay coordinates after each align of a table.")
515 (make-variable-buffer-local 'org-table-overlay-coordinates
)
517 (defvar org-last-recalc-line nil
)
518 (defconst org-narrow-column-arrow
"=>"
519 "Used as display property in narrowed table columns.")
521 (defun org-table-align ()
522 "Align the table at point by aligning all vertical bars."
526 (beg (org-table-begin))
527 (end (org-table-end))
528 ;; Current cursor position
529 (linepos (org-current-line))
530 (colpos (org-table-current-column))
531 (winstart (window-start))
532 (winstartline (org-current-line (min winstart
(1- (point-max)))))
533 lines
(new "") lengths l typenums ty fields maxfields i
541 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
543 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
544 emptystrings links dates emph narrow fmax f1 len c e
)
546 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
547 ;; Check if we have links or dates
549 (setq links
(re-search-forward org-bracket-link-regexp end t
))
551 (setq emph
(and org-hide-emphasis-markers
552 (re-search-forward org-emph-re end t
)))
554 (setq dates
(and org-display-custom-times
555 (re-search-forward org-ts-regexp-both end t
)))
556 ;; Make sure the link properties are right
557 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
558 ;; Make sure the date properties are right
559 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
560 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
562 ;; Check if we are narrowing any columns
564 (setq narrow
(and org-format-transports-properties-p
565 (re-search-forward "<[0-9]+>" end t
)))
567 (setq lines
(org-split-string
568 (buffer-substring beg end
) "\n"))
569 ;; Store the indentation of the first line
570 (if (string-match "^ *" (car lines
))
571 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
572 ;; Mark the hlines by setting the corresponding element to nil
573 ;; At the same time, we remove trailing space.
574 (setq lines
(mapcar (lambda (l)
575 (if (string-match "^ *|-" l
)
577 (if (string-match "[ \t]+$" l
)
578 (substring l
0 (match-beginning 0))
581 ;; Get the data fields by splitting the lines.
584 (org-split-string l
" *| *"))
585 (delq nil
(copy-sequence lines
))))
586 ;; How many fields in the longest line?
588 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
590 (kill-region beg end
)
591 (org-table-create org-table-default-size
)
592 (error "Empty table - created default table")))
593 ;; A list of empty strings to fill any short rows on output
594 (setq emptystrings
(make-list maxfields
""))
595 ;; Check for special formatting.
597 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
598 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
599 ;; Check if there is an explicit width specified
601 (setq c column fmax nil
)
604 (if (and (stringp e
) (string-match "^<\\([0-9]+\\)>$" e
))
605 (setq fmax
(string-to-number (match-string 1 e
)) c nil
)))
606 ;; Find fields that are wider than fmax, and shorten them
608 (loop for xx in column do
609 (when (and (stringp xx
)
610 (> (org-string-width xx
) fmax
))
611 (org-add-props xx nil
613 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
614 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
616 (error "Cannot narrow field starting with wide link \"%s\""
617 (match-string 0 xx
)))
618 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
619 (add-text-properties (- f1
2) f1
620 (list 'display org-narrow-column-arrow
)
622 ;; Get the maximum width for each column
623 (push (apply 'max
1 (mapcar 'org-string-width column
)) lengths
)
624 ;; Get the fraction of numbers, to decide about alignment of the column
625 (setq cnt
0 frac
0.0)
626 (loop for x in column do
629 (setq frac
( / (+ (* frac cnt
)
630 (if (string-match org-table-number-regexp x
) 1 0))
631 (setq cnt
(1+ cnt
))))))
632 (push (>= frac org-table-number-fraction
) typenums
))
633 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
635 ;; Store the alignment of this table, for later editing of single fields
636 (setq org-table-last-alignment typenums
637 org-table-last-column-widths lengths
)
639 ;; With invisible characters, `format' does not get the field width right
640 ;; So we need to make these fields wide by hand.
641 (when (or links emph
)
642 (loop for i from
0 upto
(1- maxfields
) do
643 (setq len
(nth i lengths
))
644 (loop for j from
0 upto
(1- (length fields
)) do
645 (setq c
(nthcdr i
(car (nthcdr j fields
))))
646 (if (and (stringp (car c
))
647 (text-property-any 0 (length (car c
)) 'invisible
'org-link
(car c
))
648 ; (string-match org-bracket-link-regexp (car c))
649 (< (org-string-width (car c
)) len
))
650 (setcar c
(concat (car c
) (make-string (- len
(org-string-width (car c
))) ?\
)))))))
652 ;; Compute the formats needed for output of the table
653 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
654 (while (setq l
(pop lengths
))
655 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
656 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
657 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
658 (setq rfmt
(concat rfmt
"\n")
659 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
663 (if l
(apply 'format rfmt
664 (append (pop fields
) emptystrings
))
667 ;; Replace the old one
668 (delete-region beg end
)
669 (move-marker end nil
)
670 (move-marker org-table-aligned-begin-marker
(point))
672 (move-marker org-table-aligned-end-marker
(point))
673 (when (and orgtbl-mode
(not (org-mode-p)))
674 (goto-char org-table-aligned-begin-marker
)
675 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
676 ;; Try to move to the old location
677 (goto-line winstartline
)
678 (setq winstart
(point-at-bol))
680 (set-window-start (selected-window) winstart
'noforce
)
681 (org-table-goto-column colpos
)
682 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
683 (setq org-table-may-need-update nil
)
694 (defun org-table-begin (&optional table-type
)
695 "Find the beginning of the table and return its position.
696 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
698 (if (not (re-search-backward
699 (if table-type org-table-any-border-regexp
700 org-table-border-regexp
)
702 (progn (goto-char (point-min)) (point))
703 (goto-char (match-beginning 0))
704 (beginning-of-line 2)
707 (defun org-table-end (&optional table-type
)
708 "Find the end of the table and return its position.
709 With argument TABLE-TYPE, go to the end of a table.el-type table."
711 (if (not (re-search-forward
712 (if table-type org-table-any-border-regexp
713 org-table-border-regexp
)
715 (goto-char (point-max))
716 (goto-char (match-beginning 0)))
719 (defun org-table-justify-field-maybe (&optional new
)
720 "Justify the current field, text to left, number to right.
721 Optional argument NEW may specify text to replace the current field content."
723 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
724 ((org-at-table-hline-p))
726 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
728 (< (point) org-table-aligned-begin-marker
)
729 (>= (point) org-table-aligned-end-marker
)))
730 ;; This is not the same table, force a full re-align
731 (setq org-table-may-need-update t
))
732 (t ;; realign the current field, based on previous full realign
733 (let* ((pos (point)) s
734 (col (org-table-current-column))
735 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
738 (skip-chars-backward "^|\n")
739 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
741 (setq s
(match-string 1)
743 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
744 e
(not (= (match-beginning 2) (match-end 2))))
745 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
746 l
(if e
"|" (setq org-table-may-need-update t
) ""))
749 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
750 (setq n
(format f new
))
751 (setq n
(concat new
"|") org-table-may-need-update t
)))
753 (let (org-table-may-need-update)
754 (replace-match n t t
))))
755 (setq org-table-may-need-update t
))
758 (defun org-table-next-field ()
759 "Go to the next field in the current table, creating new lines as needed.
760 Before doing so, re-align the table if necessary."
762 (org-table-maybe-eval-formula)
763 (org-table-maybe-recalculate-line)
764 (if (and org-table-automatic-realign
765 org-table-may-need-update
)
767 (let ((end (org-table-end)))
768 (if (org-at-table-hline-p)
772 (re-search-forward "|" end
)
773 (if (looking-at "[ \t]*$")
774 (re-search-forward "|" end
))
775 (if (and (looking-at "-")
776 org-table-tab-jumps-over-hlines
777 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
778 (goto-char (match-beginning 1)))
781 (beginning-of-line 0)
782 (org-table-insert-row 'below
))
783 (if (looking-at " ") (forward-char 1))))
785 (org-table-insert-row 'below
)))))
787 (defun org-table-previous-field ()
788 "Go to the previous field in the table.
789 Before doing so, re-align the table if necessary."
791 (org-table-justify-field-maybe)
792 (org-table-maybe-recalculate-line)
793 (if (and org-table-automatic-realign
794 org-table-may-need-update
)
796 (if (org-at-table-hline-p)
798 (re-search-backward "|" (org-table-begin))
799 (re-search-backward "|" (org-table-begin))
800 (while (looking-at "|\\(-\\|[ \t]*$\\)")
801 (re-search-backward "|" (org-table-begin)))
802 (if (looking-at "| ?")
803 (goto-char (match-end 0))))
805 (defun org-table-next-row ()
806 "Go to the next row (same column) in the current table.
807 Before doing so, re-align the table if necessary."
809 (org-table-maybe-eval-formula)
810 (org-table-maybe-recalculate-line)
811 (if (or (looking-at "[ \t]*$")
812 (save-excursion (skip-chars-backward " \t") (bolp)))
814 (if (and org-table-automatic-realign
815 org-table-may-need-update
)
817 (let ((col (org-table-current-column)))
818 (beginning-of-line 2)
819 (if (or (not (org-at-table-p))
820 (org-at-table-hline-p))
822 (beginning-of-line 0)
823 (org-table-insert-row 'below
)))
824 (org-table-goto-column col
)
825 (skip-chars-backward "^|\n\r")
826 (if (looking-at " ") (forward-char 1)))))
828 (defun org-table-copy-down (n)
829 "Copy a field down in the current column.
830 If the field at the cursor is empty, copy into it the content of the nearest
831 non-empty field above. With argument N, use the Nth non-empty field.
832 If the current field is not empty, it is copied down to the next row, and
833 the cursor is moved with it. Therefore, repeating this command causes the
834 column to be filled row-by-row.
835 If the variable `org-table-copy-increment' is non-nil and the field is an
836 integer or a timestamp, it will be incremented while copying. In the case of
837 a timestamp, if the cursor is on the year, change the year. If it is on the
838 month or the day, change that. Point will stay on the current date field
839 in order to easily repeat the interval."
841 (let* ((colpos (org-table-current-column))
842 (col (current-column))
843 (field (org-table-get-field))
844 (non-empty (string-match "[^ \t]" field
))
845 (beg (org-table-begin))
847 (org-table-check-inside-data-field)
850 (setq txt
(org-trim field
))
852 (org-table-blank-field))
856 (while (progn (beginning-of-line 1)
857 (re-search-backward org-table-dataline-regexp
859 (org-table-goto-column colpos t
)
861 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
862 (= (setq n
(1- n
)) 0))
863 (throw 'exit
(match-string 1))))))))
866 (if (and org-table-copy-increment
867 (string-match "^[0-9]+$" txt
))
868 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
871 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
873 (org-table-maybe-recalculate-line))
875 (move-to-column col
))
876 (error "No non-empty field found"))))
878 (defun org-table-check-inside-data-field ()
879 "Is point inside a table data field?
880 I.e. not on a hline or before the first or after the last column?
881 This actually throws an error, so it aborts the current command."
882 (if (or (not (org-at-table-p))
883 (= (org-table-current-column) 0)
884 (org-at-table-hline-p)
885 (looking-at "[ \t]*$"))
886 (error "Not in table data field")))
888 (defvar org-table-clip nil
889 "Clipboard for table regions.")
891 (defun org-table-blank-field ()
892 "Blank the current table field or active region."
894 (org-table-check-inside-data-field)
895 (if (and (interactive-p) (org-region-active-p))
896 (let (org-table-clip)
897 (org-table-cut-region (region-beginning) (region-end)))
898 (skip-chars-backward "^|")
900 (if (looking-at "|[^|\n]+")
901 (let* ((pos (match-beginning 0))
902 (match (match-string 0))
903 (len (org-string-width match
)))
904 (replace-match (concat "|" (make-string (1- len
) ?\
)))
905 (goto-char (+ 2 pos
))
906 (substring match
1)))))
908 (defun org-table-get-field (&optional n replace
)
909 "Return the value of the field in column N of current row.
910 N defaults to current field.
911 If REPLACE is a string, replace field with this value. The return value
912 is always the old value."
913 (and n
(org-table-goto-column n
))
914 (skip-chars-backward "^|\n")
916 (if (looking-at "|[^|\r\n]*")
917 (let* ((pos (match-beginning 0))
918 (val (buffer-substring (1+ pos
) (match-end 0))))
920 (replace-match (concat "|" replace
) t t
))
921 (goto-char (min (point-at-eol) (+ 2 pos
)))
923 (forward-char 1) ""))
925 (defun org-table-field-info (arg)
926 "Show info about the current field, and highlight any reference at point."
928 (org-table-get-specials)
931 (col (org-table-current-column))
932 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
933 (name (car (rassoc (list (org-current-line) col
)
934 org-table-named-field-locations
)))
935 (eql (org-table-get-stored-formulas))
936 (dline (org-table-current-dline))
937 (ref (format "@%d$%d" dline col
))
938 (ref1 (org-table-convert-refs-to-an ref
))
939 (fequation (or (assoc name eql
) (assoc ref eql
)))
940 (cequation (assoc (int-to-string col
) eql
))
941 (eqn (or fequation cequation
)))
944 (org-table-show-reference 'local
)
946 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
948 (if cname
(concat " or $" cname
) "")
950 (if name
(concat " or $" name
) "")
951 ;; FIXME: formula info not correct if special table line
953 (concat ", formula: "
954 (org-table-formula-to-user
956 (if (string-match "^[$@]"(car eqn
)) "" "$")
957 (car eqn
) "=" (cdr eqn
))))
960 (defun org-table-current-column ()
961 "Find out which column we are in."
963 (let ((cnt 0) (pos (point)))
964 (beginning-of-line 1)
965 (while (search-forward "|" pos t
)
969 (defun org-table-current-dline ()
970 "Find out what table data line we are in.
971 Only datalins count for this."
973 (if (interactive-p) (org-table-check-inside-data-field))
975 (let ((cnt 0) (pos (point)))
976 (goto-char (org-table-begin))
977 (while (<= (point) pos
)
978 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
979 (beginning-of-line 2))
980 (if (interactive-p) (message "This is table line %d" cnt
))
983 (defun org-table-goto-column (n &optional on-delim force
)
984 "Move the cursor to the Nth column in the current table line.
985 With optional argument ON-DELIM, stop with point before the left delimiter
987 If there are less than N fields, just go to after the last delimiter.
988 However, when FORCE is non-nil, create new columns if necessary."
990 (let ((pos (point-at-eol)))
991 (beginning-of-line 1)
993 (while (and (> (setq n
(1- n
)) -
1)
994 (or (search-forward "|" pos t
)
996 (progn (end-of-line 1)
997 (skip-chars-backward "^|")
999 ; (backward-char 2) t)))))
1000 (when (and force
(not (looking-at ".*|")))
1001 (save-excursion (end-of-line 1) (insert " | ")))
1004 (if (looking-at " ") (forward-char 1))))))
1007 (defun org-table-insert-column ()
1008 "Insert a new column into the table."
1010 (if (not (org-at-table-p))
1011 (error "Not at a table"))
1012 (org-table-find-dataline)
1013 (let* ((col (max 1 (org-table-current-column)))
1014 (beg (org-table-begin))
1015 (end (org-table-end))
1016 ;; Current cursor position
1017 (linepos (org-current-line))
1020 (while (< (point) end
)
1021 (if (org-at-table-hline-p)
1023 (org-table-goto-column col t
)
1025 (beginning-of-line 2))
1026 (move-marker end nil
)
1028 (org-table-goto-column colpos
)
1030 (org-table-fix-formulas "$" nil
(1- col
) 1)))
1032 (defun org-table-find-dataline ()
1033 "Find a dataline in the current table, which is needed for column commands."
1034 (if (and (org-at-table-p)
1035 (not (org-at-table-hline-p)))
1037 (let ((col (current-column))
1038 (end (org-table-end)))
1039 (move-to-column col
)
1040 (while (and (< (point) end
)
1041 (or (not (= (current-column) col
))
1042 (org-at-table-hline-p)))
1043 (beginning-of-line 2)
1044 (move-to-column col
))
1045 (if (and (org-at-table-p)
1046 (not (org-at-table-hline-p)))
1049 "Please position cursor in a data line for column operations")))))
1051 (defun org-table-delete-column ()
1052 "Delete a column from the table."
1054 (if (not (org-at-table-p))
1055 (error "Not at a table"))
1056 (org-table-find-dataline)
1057 (org-table-check-inside-data-field)
1058 (let* ((col (org-table-current-column))
1059 (beg (org-table-begin))
1060 (end (org-table-end))
1061 ;; Current cursor position
1062 (linepos (org-current-line))
1065 (while (< (point) end
)
1066 (if (org-at-table-hline-p)
1068 (org-table-goto-column col t
)
1069 (and (looking-at "|[^|\n]+|")
1070 (replace-match "|")))
1071 (beginning-of-line 2))
1072 (move-marker end nil
)
1074 (org-table-goto-column colpos
)
1076 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1079 (defun org-table-move-column-right ()
1080 "Move column to the right."
1082 (org-table-move-column nil
))
1083 (defun org-table-move-column-left ()
1084 "Move column to the left."
1086 (org-table-move-column 'left
))
1088 (defun org-table-move-column (&optional left
)
1089 "Move the current column to the right. With arg LEFT, move to the left."
1091 (if (not (org-at-table-p))
1092 (error "Not at a table"))
1093 (org-table-find-dataline)
1094 (org-table-check-inside-data-field)
1095 (let* ((col (org-table-current-column))
1096 (col1 (if left
(1- col
) col
))
1097 (beg (org-table-begin))
1098 (end (org-table-end))
1099 ;; Current cursor position
1100 (linepos (org-current-line))
1101 (colpos (if left
(1- col
) (1+ col
))))
1102 (if (and left
(= col
1))
1103 (error "Cannot move column further left"))
1104 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1105 (error "Cannot move column further right"))
1107 (while (< (point) end
)
1108 (if (org-at-table-hline-p)
1110 (org-table-goto-column col1 t
)
1111 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1112 (replace-match "|\\2|\\1|")))
1113 (beginning-of-line 2))
1114 (move-marker end nil
)
1116 (org-table-goto-column colpos
)
1118 (org-table-fix-formulas
1119 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1120 (cons (number-to-string colpos
) (number-to-string col
))))))
1122 (defun org-table-move-row-down ()
1123 "Move table row down."
1125 (org-table-move-row nil
))
1126 (defun org-table-move-row-up ()
1127 "Move table row up."
1129 (org-table-move-row 'up
))
1131 (defun org-table-move-row (&optional up
)
1132 "Move the current table line down. With arg UP, move it up."
1134 (let* ((col (current-column))
1136 (hline1p (save-excursion (beginning-of-line 1)
1137 (looking-at org-table-hline-regexp
)))
1138 (dline1 (org-table-current-dline))
1139 (dline2 (+ dline1
(if up -
1 1)))
1142 (beginning-of-line tonew
)
1143 (unless (org-at-table-p)
1145 (error "Cannot move row further"))
1146 (setq hline2p
(looking-at org-table-hline-regexp
))
1148 (beginning-of-line 1)
1150 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1151 (delete-region (point) (1+ (point-at-eol)))
1152 (beginning-of-line tonew
)
1154 (beginning-of-line 0)
1155 (move-to-column col
)
1156 (unless (or hline1p hline2p
)
1157 (org-table-fix-formulas
1158 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1159 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1161 (defun org-table-insert-row (&optional arg
)
1162 "Insert a new row above the current line into the table.
1163 With prefix ARG, insert below the current line."
1165 (if (not (org-at-table-p))
1166 (error "Not at a table"))
1167 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1168 (new (org-table-clean-line line
)))
1169 ;; Fix the first field if necessary
1170 (if (string-match "^[ \t]*| *[#$] *|" line
)
1171 (setq new
(replace-match (match-string 0 line
) t t new
)))
1172 (beginning-of-line (if arg
2 1))
1173 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1174 (beginning-of-line 0)
1175 (re-search-forward "| ?" (point-at-eol) t
)
1176 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1178 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1)))
1180 (defun org-table-insert-hline (&optional above
)
1181 "Insert a horizontal-line below the current line into the table.
1182 With prefix ABOVE, insert above the current line."
1184 (if (not (org-at-table-p))
1185 (error "Not at a table"))
1186 (let ((line (org-table-clean-line
1187 (buffer-substring (point-at-bol) (point-at-eol))))
1188 (col (current-column)))
1189 (while (string-match "|\\( +\\)|" line
)
1190 (setq line
(replace-match
1191 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1192 ?-
) "|") t t line
)))
1193 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1194 (beginning-of-line (if above
1 2))
1196 (beginning-of-line (if above
1 -
1))
1197 (move-to-column col
)
1198 (and org-table-overlay-coordinates
(org-table-align))))
1200 (defun org-table-hline-and-move (&optional same-column
)
1201 "Insert a hline and move to the row below that line."
1203 (let ((col (org-table-current-column)))
1204 (org-table-maybe-eval-formula)
1205 (org-table-maybe-recalculate-line)
1206 (org-table-insert-hline)
1208 (if (looking-at "\n[ \t]*|-")
1209 (progn (insert "\n|") (org-table-align))
1210 (org-table-next-field))
1211 (if same-column
(org-table-goto-column col
))))
1213 (defun org-table-clean-line (s)
1214 "Convert a table line S into a string with only \"|\" and space.
1215 In particular, this does handle wide and invisible characters."
1216 (if (string-match "^[ \t]*|-" s
)
1217 ;; It's a hline, just map the characters
1218 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1219 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1220 (setq s
(replace-match
1221 (concat "|" (make-string (org-string-width (match-string 1 s
))
1226 (defun org-table-kill-row ()
1227 "Delete the current row or horizontal line from the table."
1229 (if (not (org-at-table-p))
1230 (error "Not at a table"))
1231 (let ((col (current-column))
1232 (dline (org-table-current-dline)))
1233 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1234 (if (not (org-at-table-p)) (beginning-of-line 0))
1235 (move-to-column col
)
1236 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1239 (defun org-table-sort-lines (with-case &optional sorting-type
)
1240 "Sort table lines according to the column at point.
1242 The position of point indicates the column to be used for
1243 sorting, and the range of lines is the range between the nearest
1244 horizontal separator lines, or the entire table of no such lines
1245 exist. If point is before the first column, you will be prompted
1246 for the sorting column. If there is an active region, the mark
1247 specifies the first line and the sorting column, while point
1248 should be in the last line to be included into the sorting.
1250 The command then prompts for the sorting type which can be
1251 alphabetically, numerically, or by time (as given in a time stamp
1252 in the field). Sorting in reverse order is also possible.
1254 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1256 If SORTING-TYPE is specified when this function is called from a Lisp
1257 program, no prompting will take place. SORTING-TYPE must be a character,
1258 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1259 should be done in reverse order."
1261 (let* ((thisline (org-current-line))
1262 (thiscol (org-table-current-column))
1263 beg end bcol ecol tend tbeg column lns pos
)
1264 (when (equal thiscol
0)
1268 (read-string "Use column N for sorting: ")))
1270 (org-table-goto-column thiscol
))
1271 (org-table-check-inside-data-field)
1272 (if (org-region-active-p)
1274 (setq beg
(region-beginning) end
(region-end))
1276 (setq column
(org-table-current-column)
1279 (setq end
(point-at-bol 2)))
1280 (setq column
(org-table-current-column)
1282 tbeg
(org-table-begin)
1283 tend
(org-table-end))
1284 (if (re-search-backward org-table-hline-regexp tbeg t
)
1285 (setq beg
(point-at-bol 2))
1287 (setq beg
(point-at-bol 1)))
1289 (if (re-search-forward org-table-hline-regexp tend t
)
1290 (setq end
(point-at-bol 1))
1292 (setq end
(point-at-bol))))
1293 (setq beg
(move-marker (make-marker) beg
)
1294 end
(move-marker (make-marker) end
))
1297 (org-table-goto-column column
)
1298 (skip-chars-backward "^|")
1299 (setq bcol
(current-column))
1300 (org-table-goto-column (1+ column
))
1301 (skip-chars-backward "^|")
1302 (setq ecol
(1- (current-column)))
1303 (org-table-goto-column column
)
1304 (setq lns
(mapcar (lambda(x) (cons
1305 (org-sort-remove-invisible
1307 (org-split-string x
"[ \t]*|[ \t]*")))
1309 (org-split-string (buffer-substring beg end
) "\n")))
1310 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1311 (delete-region beg end
)
1312 (move-marker beg nil
)
1313 (move-marker end nil
)
1314 (insert (mapconcat 'cdr lns
"\n") "\n")
1315 (goto-line thisline
)
1316 (org-table-goto-column thiscol
)
1317 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1320 (defun org-table-cut-region (beg end
)
1321 "Copy region in table to the clipboard and blank all relevant fields."
1323 (org-table-copy-region beg end
'cut
))
1325 (defun org-table-copy-region (beg end
&optional cut
)
1326 "Copy rectangular region in table to clipboard.
1327 A special clipboard is used which can only be accessed
1328 with `org-table-paste-rectangle'."
1330 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1332 (rpl (if cut
" " nil
)))
1334 (org-table-check-inside-data-field)
1335 (setq l01
(org-current-line)
1336 c01
(org-table-current-column))
1338 (org-table-check-inside-data-field)
1339 (setq l02
(org-current-line)
1340 c02
(org-table-current-column))
1341 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1342 c1
(min c01 c02
) c2
(max c01 c02
))
1346 (if (> l1 l2
) (throw 'exit t
))
1348 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1349 (setq cols nil ic1 c1 ic2 c2
)
1350 (while (< ic1
(1+ ic2
))
1351 (push (org-table-get-field ic1 rpl
) cols
)
1352 (setq ic1
(1+ ic1
)))
1353 (push (nreverse cols
) region
)
1354 (setq l1
(1+ l1
)))))
1355 (setq org-table-clip
(nreverse region
))
1356 (if cut
(org-table-align))
1359 (defun org-table-paste-rectangle ()
1360 "Paste a rectangular region into a table.
1361 The upper right corner ends up in the current field. All involved fields
1362 will be overwritten. If the rectangle does not fit into the present table,
1363 the table is enlarged as needed. The process ignores horizontal separator
1366 (unless (and org-table-clip
(listp org-table-clip
))
1367 (error "First cut/copy a region to paste!"))
1368 (org-table-check-inside-data-field)
1369 (let* ((clip org-table-clip
)
1370 (line (org-current-line))
1371 (col (org-table-current-column))
1372 (org-enable-table-editor t
)
1373 (org-table-automatic-realign nil
)
1375 (while (setq cols
(pop clip
))
1376 (while (org-at-table-hline-p) (beginning-of-line 2))
1377 (if (not (org-at-table-p))
1378 (progn (end-of-line 0) (org-table-next-field)))
1380 (while (setq field
(pop cols
))
1381 (org-table-goto-column c nil
'force
)
1382 (org-table-get-field nil field
)
1384 (beginning-of-line 2))
1386 (org-table-goto-column col
)
1389 (defun org-table-convert ()
1390 "Convert from `org-mode' table to table.el and back.
1391 Obviously, this only works within limits. When an Org-mode table is
1392 converted to table.el, all horizontal separator lines get lost, because
1393 table.el uses these as cell boundaries and has no notion of horizontal lines.
1394 A table.el table can be converted to an Org-mode table only if it does not
1395 do row or column spanning. Multiline cells will become multiple cells.
1396 Beware, Org-mode does not test if the table can be successfully converted - it
1397 blindly applies a recipe that works for simple tables."
1400 (if (org-at-table.el-p
)
1401 ;; convert to Org-mode table
1402 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1403 (end (move-marker (make-marker) (org-table-end t
))))
1404 (table-unrecognize-region beg end
)
1406 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1409 (if (org-at-table-p)
1410 ;; convert to table.el table
1411 (let ((beg (move-marker (make-marker) (org-table-begin)))
1412 (end (move-marker (make-marker) (org-table-end))))
1413 ;; first, get rid of all horizontal lines
1415 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1417 ;; insert a hline before first
1419 (org-table-insert-hline 'above
)
1420 (beginning-of-line -
1)
1421 ;; insert a hline after each line
1422 (while (progn (beginning-of-line 3) (< (point) end
))
1423 (org-table-insert-hline))
1425 (setq end
(move-marker end
(org-table-end)))
1426 ;; replace "+" at beginning and ending of hlines
1427 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1428 (replace-match "\\1+-"))
1430 (while (re-search-forward "-|[ \t]*$" end t
)
1431 (replace-match "-+"))
1434 (defun org-table-wrap-region (arg)
1435 "Wrap several fields in a column like a paragraph.
1436 This is useful if you'd like to spread the contents of a field over several
1437 lines, in order to keep the table compact.
1439 If there is an active region, and both point and mark are in the same column,
1440 the text in the column is wrapped to minimum width for the given number of
1441 lines. Generally, this makes the table more compact. A prefix ARG may be
1442 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1443 formats the selected text to two lines. If the region was longer than two
1444 lines, the remaining lines remain empty. A negative prefix argument reduces
1445 the current number of lines by that amount. The wrapped text is pasted back
1446 into the table. If you formatted it to more lines than it was before, fields
1447 further down in the table get overwritten - so you might need to make space in
1450 If there is no region, the current field is split at the cursor position and
1451 the text fragment to the right of the cursor is prepended to the field one
1454 If there is no region, but you specify a prefix ARG, the current field gets
1455 blank, and the content is appended to the field above."
1457 (org-table-check-inside-data-field)
1458 (if (org-region-active-p)
1459 ;; There is a region: fill as a paragraph
1460 (let* ((beg (region-beginning))
1461 (cline (save-excursion (goto-char beg
) (org-current-line)))
1462 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1464 (org-table-cut-region (region-beginning) (region-end))
1465 (if (> (length (car org-table-clip
)) 1)
1466 (error "Region must be limited to single column"))
1467 (setq nlines
(if arg
1469 (+ (length org-table-clip
) arg
)
1471 (length org-table-clip
)))
1472 (setq org-table-clip
1473 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1476 (org-table-goto-column ccol
)
1477 (org-table-paste-rectangle))
1478 ;; No region, split the current field at point
1479 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1480 (skip-chars-forward "^\r\n|"))
1482 ;; combine with field above
1483 (let ((s (org-table-blank-field))
1484 (col (org-table-current-column)))
1485 (beginning-of-line 0)
1486 (while (org-at-table-hline-p) (beginning-of-line 0))
1487 (org-table-goto-column col
)
1488 (skip-chars-forward "^|")
1489 (skip-chars-backward " ")
1490 (insert " " (org-trim s
))
1493 (if (looking-at "\\([^|]+\\)+|")
1494 (let ((s (match-string 1)))
1495 (replace-match " |")
1496 (goto-char (match-beginning 0))
1497 (org-table-next-row)
1498 (insert (org-trim s
) " ")
1500 (org-table-next-row)))))
1502 (defvar org-field-marker nil
)
1504 (defun org-table-edit-field (arg)
1505 "Edit table field in a different window.
1506 This is mainly useful for fields that contain hidden parts.
1507 When called with a \\[universal-argument] prefix, just make the full field visible so that
1508 it can be edited in place."
1511 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1512 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1513 (remove-text-properties b e
'(org-cwidth t invisible t
1514 display t intangible t
))
1515 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1516 (font-lock-fontify-block)))
1517 (let ((pos (move-marker (make-marker) (point)))
1518 (field (org-table-get-field))
1519 (cw (current-window-configuration))
1521 (org-switch-to-buffer-other-window "*Org tmp*")
1523 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
1524 (let ((org-inhibit-startup t
)) (org-mode))
1525 (goto-char (setq p
(point-max)))
1526 (insert (org-trim field
))
1527 (remove-text-properties p
(point-max)
1528 '(invisible t org-cwidth t display t
1531 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1532 (org-set-local 'org-window-configuration cw
)
1533 (org-set-local 'org-field-marker pos
)
1534 (message "Edit and finish with C-c C-c"))))
1536 (defun org-table-finish-edit-field ()
1537 "Finish editing a table data field.
1538 Remove all newline characters, insert the result into the table, realign
1539 the table and kill the editing buffer."
1540 (let ((pos org-field-marker
)
1541 (cw org-window-configuration
)
1542 (cb (current-buffer))
1544 (goto-char (point-min))
1545 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1546 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1547 (replace-match " "))
1548 (setq text
(org-trim (buffer-string)))
1549 (set-window-configuration cw
)
1551 (select-window (get-buffer-window (marker-buffer pos
)))
1553 (move-marker pos nil
)
1554 (org-table-check-inside-data-field)
1555 (org-table-get-field nil text
)
1557 (message "New field value inserted")))
1576 (defvar org-timecnt
) ; dynamically scoped parameter
1578 (defun org-table-sum (&optional beg end nlast
)
1579 "Sum numbers in region of current table column.
1580 The result will be displayed in the echo area, and will be available
1581 as kill to be inserted with \\[yank].
1583 If there is an active region, it is interpreted as a rectangle and all
1584 numbers in that rectangle will be summed. If there is no active
1585 region and point is located in a table column, sum all numbers in that
1588 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1589 numbers are assumed to be times as well (in decimal hours) and the
1590 numbers are added as such.
1592 If NLAST is a number, only the NLAST fields will actually be summed."
1595 (let (col (org-timecnt 0) diff h m s org-table-clip
)
1597 ((and beg end
)) ; beg and end given explicitly
1598 ((org-region-active-p)
1599 (setq beg
(region-beginning) end
(region-end)))
1601 (setq col
(org-table-current-column))
1602 (goto-char (org-table-begin))
1603 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
1604 (error "No table data"))
1605 (org-table-goto-column col
)
1607 (goto-char (org-table-end))
1608 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
1609 (error "No table data"))
1610 (org-table-goto-column col
)
1611 (setq end
(point))))
1612 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
1613 (items1 (cond ((not nlast
) items
)
1614 ((>= nlast
(length items
)) items
)
1615 (t (setq items
(reverse items
))
1616 (setcdr (nthcdr (1- nlast
) items
) nil
)
1618 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
1620 (res (apply '+ numbers
))
1621 (sres (if (= org-timecnt
0)
1623 (setq diff
(* 3600 res
)
1624 h
(floor (/ diff
3600)) diff
(mod diff
3600)
1625 m
(floor (/ diff
60)) diff
(mod diff
60)
1627 (format "%d:%02d:%02d" h m s
))))
1631 (substitute-command-keys
1632 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
1633 (length numbers
) sres
))))
1636 (defun org-table-get-number-for-summing (s)
1638 (if (string-match "^ *|? *" s
)
1639 (setq s
(replace-match "" nil nil s
)))
1640 (if (string-match " *|? *$" s
)
1641 (setq s
(replace-match "" nil nil s
)))
1642 (setq n
(string-to-number s
))
1644 ((and (string-match "0" s
)
1645 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
1646 ((string-match "\\`[ \t]+\\'" s
) nil
)
1647 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
1648 (let ((h (string-to-number (or (match-string 1 s
) "0")))
1649 (m (string-to-number (or (match-string 2 s
) "0")))
1650 (s (string-to-number (or (match-string 4 s
) "0"))))
1651 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
1652 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
1656 (defun org-table-current-field-formula (&optional key noerror
)
1657 "Return the formula active for the current field.
1658 Assumes that specials are in place.
1659 If KEY is given, return the key to this formula.
1660 Otherwise return the formula preceeded with \"=\" or \":=\"."
1661 (let* ((name (car (rassoc (list (org-current-line)
1662 (org-table-current-column))
1663 org-table-named-field-locations
)))
1664 (col (org-table-current-column))
1665 (scol (int-to-string col
))
1666 (ref (format "@%d$%d" (org-table-current-dline) col
))
1667 (stored-list (org-table-get-stored-formulas noerror
))
1668 (ass (or (assoc name stored-list
)
1669 (assoc ref stored-list
)
1670 (assoc scol stored-list
))))
1673 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
1676 (defun org-table-get-formula (&optional equation named
)
1677 "Read a formula from the minibuffer, offer stored formula as default.
1678 When NAMED is non-nil, look for a named equation."
1679 (let* ((stored-list (org-table-get-stored-formulas))
1680 (name (car (rassoc (list (org-current-line)
1681 (org-table-current-column))
1682 org-table-named-field-locations
)))
1683 (ref (format "@%d$%d" (org-table-current-dline)
1684 (org-table-current-column)))
1685 (refass (assoc ref stored-list
))
1688 (int-to-string (org-table-current-column))))
1689 (dummy (and (or name refass
) (not named
)
1690 (not (y-or-n-p "Replace field formula with column formula? " ))
1692 (name (or name ref
))
1693 (org-table-may-need-update nil
)
1694 (stored (cdr (assoc scol stored-list
)))
1696 ((and stored equation
(string-match "^ *=? *$" equation
))
1700 (t (org-table-formula-from-user
1702 (org-table-formula-to-user
1703 (format "%s formula %s%s="
1704 (if named
"Field" "Column")
1705 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
1707 (if stored
(org-table-formula-to-user stored
) "")
1708 'org-table-formula-history
1711 (when (not (string-match "\\S-" eq
))
1713 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
1714 (org-table-store-formulas stored-list
)
1715 (error "Formula removed"))
1716 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
1717 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
1718 (if (and name
(not named
))
1719 ;; We set the column equation, delete the named one.
1720 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
1723 (setcdr (assoc scol stored-list
) eq
)
1724 (setq stored-list
(cons (cons scol eq
) stored-list
)))
1725 (if (or mustsave
(not (equal stored eq
)))
1726 (org-table-store-formulas stored-list
))
1729 (defun org-table-store-formulas (alist)
1730 "Store the list of formulas below the current table."
1731 (setq alist
(sort alist
'org-table-formula-less-p
))
1733 (goto-char (org-table-end))
1734 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
1736 ;; don't overwrite TBLFM, we might use text properties to store stuff
1737 (goto-char (match-beginning 2))
1738 (delete-region (match-beginning 2) (match-end 0)))
1739 (insert "#+TBLFM:"))
1741 (mapconcat (lambda (x)
1743 (if (equal (string-to-char (car x
)) ?
@) "" "$")
1744 (car x
) "=" (cdr x
)))
1748 (defsubst org-table-formula-make-cmp-string
(a)
1749 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a
)
1751 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a
))) "")
1752 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a
))) "")
1753 (if (match-end 5) (concat "@@" (match-string 5 a
))))))
1755 (defun org-table-formula-less-p (a b
)
1756 "Compare two formulas for sorting."
1757 (let ((as (org-table-formula-make-cmp-string (car a
)))
1758 (bs (org-table-formula-make-cmp-string (car b
))))
1759 (and as bs
(string< as bs
))))
1761 (defun org-table-get-stored-formulas (&optional noerror
)
1762 "Return an alist with the stored formulas directly after current table."
1764 (let (scol eq eq-alist strings string seen
)
1766 (goto-char (org-table-end))
1767 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
1768 (setq strings
(org-split-string (match-string 2) " *:: *"))
1769 (while (setq string
(pop strings
))
1770 (when (string-match "\\`\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
1771 (setq scol
(if (match-end 2)
1772 (match-string 2 string
)
1773 (match-string 1 string
))
1774 eq
(match-string 3 string
)
1775 eq-alist
(cons (cons scol eq
) eq-alist
))
1776 (if (member scol seen
)
1779 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
1782 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
1783 (push scol seen
))))))
1784 (nreverse eq-alist
)))
1786 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
1787 "Modify the equations after the table structure has been edited.
1788 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
1789 For all numbers larger than LIMIT, shift them by DELTA."
1791 (goto-char (org-table-end))
1792 (when (looking-at "#\\+TBLFM:")
1793 (let ((re (concat key
"\\([0-9]+\\)"))
1797 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove
)
1798 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
1801 (while (re-search-forward re2
(point-at-eol) t
)
1802 (replace-match "")))
1803 (while (re-search-forward re
(point-at-eol) t
)
1804 (setq s
(match-string 1) n
(string-to-number s
))
1806 ((setq a
(assoc s replace
))
1807 (replace-match (concat key
(cdr a
)) t t
))
1808 ((and limit
(> n limit
))
1809 (replace-match (concat key
(int-to-string (+ n delta
))) t t
))))))))
1811 (defun org-table-get-specials ()
1812 "Get the column names and local parameters for this table."
1814 (let ((beg (org-table-begin)) (end (org-table-end))
1815 names name fields fields1 field cnt
1816 c v l line col types dlines hlines
)
1817 (setq org-table-column-names nil
1818 org-table-local-parameters nil
1819 org-table-named-field-locations nil
1820 org-table-current-begin-line nil
1821 org-table-current-begin-pos nil
1822 org-table-current-line-types nil
)
1824 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
1825 (setq names
(org-split-string (match-string 1) " *| *")
1827 (while (setq name
(pop names
))
1829 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name
)
1830 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
1831 (setq org-table-column-names
(nreverse org-table-column-names
))
1832 (setq org-table-column-name-regexp
1833 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
1835 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
1836 (setq fields
(org-split-string (match-string 1) " *| *"))
1837 (while (setq field
(pop fields
))
1838 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
1839 (push (cons (match-string 1 field
) (match-string 2 field
))
1840 org-table-local-parameters
))))
1842 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
1843 (setq c
(match-string 1)
1844 fields
(org-split-string (match-string 2) " *| *"))
1846 (beginning-of-line (if (equal c
"_") 2 0))
1847 (setq line
(org-current-line) col
1)
1848 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
1849 (setq fields1
(org-split-string (match-string 1) " *| *"))))
1850 (while (and fields1
(setq field
(pop fields
)))
1851 (setq v
(pop fields1
) col
(1+ col
))
1852 (when (and (stringp field
) (stringp v
)
1853 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field
))
1854 (push (cons field v
) org-table-local-parameters
)
1855 (push (list field line col
) org-table-named-field-locations
))))
1856 ;; Analyse the line types
1858 (setq org-table-current-begin-line
(org-current-line)
1859 org-table-current-begin-pos
(point)
1860 l org-table-current-begin-line
)
1861 (while (looking-at "[ \t]*|\\(-\\)?")
1862 (push (if (match-end 1) 'hline
'dline
) types
)
1863 (if (match-end 1) (push l hlines
) (push l dlines
))
1864 (beginning-of-line 2)
1866 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
1867 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
1868 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
)))))))
1870 (defun org-table-maybe-eval-formula ()
1871 "Check if the current field starts with \"=\" or \":=\".
1872 If yes, store the formula and apply it."
1873 ;; We already know we are in a table. Get field will only return a formula
1874 ;; when appropriate. It might return a separator line, but no problem.
1875 (when org-table-formula-evaluate-inline
1876 (let* ((field (org-trim (or (org-table-get-field) "")))
1878 (when (string-match "^:?=\\(.*\\)" field
)
1879 (setq named
(equal (string-to-char field
) ?
:)
1880 eq
(match-string 1 field
))
1881 (if (or (fboundp 'calc-eval
)
1882 (equal (substring eq
0 (min 2 (length eq
))) "'("))
1883 (org-table-eval-formula (if named
'(4) nil
)
1884 (org-table-formula-from-user eq
))
1885 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
1887 (defvar org-recalc-commands nil
1888 "List of commands triggering the recalculation of a line.
1889 Will be filled automatically during use.")
1891 (defvar org-recalc-marks
1892 '((" " .
"Unmarked: no special line, no automatic recalculation")
1893 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
1894 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
1895 ("!" .
"Column name definition line. Reference in formula as $name.")
1896 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
1897 ("_" .
"Names for values in row below this one.")
1898 ("^" .
"Names for values in row above this one.")))
1900 (defun org-table-rotate-recalc-marks (&optional newchar
)
1901 "Rotate the recalculation mark in the first column.
1902 If in any row, the first field is not consistent with a mark,
1903 insert a new column for the markers.
1904 When there is an active region, change all the lines in the region,
1905 after prompting for the marking character.
1906 After each change, a message will be displayed indicating the meaning
1909 (unless (org-at-table-p) (error "Not at a table"))
1910 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
1911 (beg (org-table-begin))
1912 (end (org-table-end))
1913 (l (org-current-line))
1914 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
1915 (l2 (if (org-region-active-p) (org-current-line (region-end))))
1919 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
1920 (col (org-table-current-column))
1921 (forcenew (car (assoc newchar org-recalc-marks
)))
1924 (message "Change region to what mark? Type # * ! $ or SPC: ")
1925 (setq newchar
(char-to-string (read-char-exclusive))
1926 forcenew
(car (assoc newchar org-recalc-marks
))))
1927 (if (and newchar
(not forcenew
))
1928 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
1930 (if l1
(goto-line l1
))
1932 (beginning-of-line 1)
1933 (unless (looking-at org-table-dataline-regexp
)
1934 (error "Not at a table data line")))
1936 (org-table-goto-column 1)
1937 (org-table-insert-column)
1938 (org-table-goto-column (1+ col
)))
1939 (setq epos
(point-at-eol))
1941 (beginning-of-line 1)
1942 (org-table-get-field
1943 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
1945 (setq new
(or forcenew
1946 (cadr (member (match-string 1) marks
))))
1952 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
1953 (and (looking-at org-table-dataline-regexp
)
1954 (org-table-get-field 1 (concat " " new
" "))))
1956 (if (not (= epos
(point-at-eol))) (org-table-align))
1958 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks
))))))
1960 (defun org-table-maybe-recalculate-line ()
1961 "Recompute the current line if marked for it, and if we haven't just done it."
1963 (and org-table-allow-automatic-line-recalculation
1964 (not (and (memq last-command org-recalc-commands
)
1965 (equal org-last-recalc-line
(org-current-line))))
1966 (save-excursion (beginning-of-line 1)
1967 (looking-at org-table-auto-recalculate-regexp
))
1968 (org-table-recalculate) t
))
1971 (defsubst org-set-calc-mode
(var &optional value
)
1973 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
1974 ("R" calc-angle-mode rad
)
1975 ("F" calc-prefer-frac t
)
1976 ("S" calc-symbolic-mode t
)))
1977 value
(nth 2 var
) var
(nth 1 var
)))
1978 (if (memq var modes
)
1979 (setcar (cdr (memq var modes
)) value
)
1980 (cons var
(cons value modes
)))
1983 (defun org-table-eval-formula (&optional arg equation
1984 suppress-align suppress-const
1985 suppress-store suppress-analysis
)
1986 "Replace the table field value at the cursor by the result of a calculation.
1988 This function makes use of Dave Gillespie's Calc package, in my view the
1989 most exciting program ever written for GNU Emacs. So you need to have Calc
1990 installed in order to use this function.
1992 In a table, this command replaces the value in the current field with the
1993 result of a formula. It also installs the formula as the \"current\" column
1994 formula, by storing it in a special line below the table. When called
1995 with a `C-u' prefix, the current field must ba a named field, and the
1996 formula is installed as valid in only this specific field.
1998 When called with two `C-u' prefixes, insert the active equation
1999 for the field back into the current field, so that it can be
2000 edited there. This is useful in order to use \\[org-table-show-reference]
2001 to check the referenced fields.
2003 When called, the command first prompts for a formula, which is read in
2004 the minibuffer. Previously entered formulas are available through the
2005 history list, and the last used formula is offered as a default.
2006 These stored formulas are adapted correctly when moving, inserting, or
2007 deleting columns with the corresponding commands.
2009 The formula can be any algebraic expression understood by the Calc package.
2010 For details, see the Org-mode manual.
2012 This function can also be called from Lisp programs and offers
2013 additional arguments: EQUATION can be the formula to apply. If this
2014 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2015 used to speed-up recursive calls by by-passing unnecessary aligns.
2016 SUPPRESS-CONST suppresses the interpretation of constants in the
2017 formula, assuming that this has been done already outside the function.
2018 SUPPRESS-STORE means the formula should not be stored, either because
2019 it is already stored, or because it is a modified equation that should
2020 not overwrite the stored one."
2022 (org-table-check-inside-data-field)
2023 (or suppress-analysis
(org-table-get-specials))
2024 (if (equal arg
'(16))
2025 (let ((eq (org-table-current-field-formula)))
2026 (or eq
(error "No equation active for current field"))
2027 (org-table-get-field nil eq
)
2029 (setq org-table-may-need-update t
))
2031 (ndown (if (integerp arg
) arg
1))
2032 (org-table-automatic-realign nil
)
2033 (case-fold-search nil
)
2035 (formula (if (and equation suppress-store
)
2037 (org-table-get-formula equation
(equal arg
'(4)))))
2038 (n0 (org-table-current-column))
2039 (modes (copy-sequence org-calc-default-modes
))
2040 (numbers nil
) ; was a variable, now fixed default
2042 n form form0 bw fmt x ev orig c lispp literal
)
2043 ;; Parse the format string. Since we have a lot of modes, this is
2044 ;; a lot of work. However, I think calc still uses most of the time.
2045 (if (string-match ";" formula
)
2046 (let ((tmp (org-split-string formula
";")))
2047 (setq formula
(car tmp
)
2048 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2050 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2051 (setq c
(string-to-char (match-string 1 fmt
))
2052 n
(string-to-number (match-string 2 fmt
)))
2054 (setq modes
(org-set-calc-mode 'calc-internal-prec n
))
2055 (setq modes
(org-set-calc-mode
2057 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2058 (?s . sci
) (?e . eng
))))
2060 (setq fmt
(replace-match "" t t fmt
)))
2061 (if (string-match "[NT]" fmt
)
2062 (setq numbers
(equal (match-string 0 fmt
) "N")
2063 fmt
(replace-match "" t t fmt
)))
2064 (if (string-match "L" fmt
)
2066 fmt
(replace-match "" t t fmt
)))
2067 (if (string-match "E" fmt
)
2069 fmt
(replace-match "" t t fmt
)))
2070 (while (string-match "[DRFS]" fmt
)
2071 (setq modes
(org-set-calc-mode (match-string 0 fmt
)))
2072 (setq fmt
(replace-match "" t t fmt
)))
2073 (unless (string-match "\\S-" fmt
)
2075 (if (and (not suppress-const
) org-table-formula-use-constants
)
2076 (setq formula
(org-table-formula-substitute-names formula
)))
2077 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2079 (setq fields
(org-split-string
2081 (buffer-substring (point-at-bol) (point-at-eol)))
2084 (setq fields
(mapcar
2085 (lambda (x) (number-to-string (string-to-number x
)))
2087 (setq ndown
(1- ndown
))
2088 (setq form
(copy-sequence formula
)
2089 lispp
(and (> (length form
) 2)(equal (substring form
0 2) "'(")))
2090 (if (and lispp literal
) (setq lispp
'literal
))
2091 ;; Check for old vertical references
2092 (setq form
(org-rewrite-old-row-references form
))
2093 ;; Insert complex ranges
2094 (while (string-match org-table-range-regexp form
)
2098 (org-table-make-reference
2099 (org-table-get-range (match-string 0 form
) nil n0
)
2100 keep-empty numbers lispp
))
2102 ;; Insert simple ranges
2103 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2107 (org-table-make-reference
2109 fields
(string-to-number (match-string 1 form
))
2110 (string-to-number (match-string 2 form
)))
2111 keep-empty numbers lispp
))
2114 ;; Insert the references to fields in same row
2115 (while (string-match "\\$\\([0-9]+\\)" form
)
2116 (setq n
(string-to-number (match-string 1 form
))
2117 x
(nth (1- (if (= n
0) n0 n
)) fields
))
2118 (unless x
(error "Invalid field specifier \"%s\""
2119 (match-string 0 form
)))
2120 (setq form
(replace-match
2122 (org-table-make-reference x nil numbers lispp
))
2126 (setq ev
(condition-case nil
2127 (eval (eval (read form
)))
2129 ev
(if (numberp ev
) (number-to-string ev
) ev
))
2130 (or (fboundp 'calc-eval
)
2131 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2132 (setq ev
(calc-eval (cons form modes
)
2133 (if numbers
'num
))))
2135 (when org-table-formula-debug
2136 (with-output-to-temp-buffer "*Substitution History*"
2137 (princ (format "Substitution history of formula
2141 $1-> %s\n" orig formula form0 form
))
2143 (princ (format " %s^\nError: %s"
2144 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2145 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2147 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2148 (setq bw
(get-buffer-window "*Substitution History*"))
2149 (shrink-window-if-larger-than-buffer bw
)
2150 (unless (and (interactive-p) (not ndown
))
2151 (unless (let (inhibit-redisplay)
2152 (y-or-n-p "Debugging Formula. Continue to next? "))
2157 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2158 (org-table-justify-field-maybe
2159 (if fmt
(format fmt
(string-to-number ev
)) ev
))
2160 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2161 (call-interactively 'org-return
)
2163 (and down
(org-table-maybe-recalculate-line))
2164 (or suppress-align
(and org-table-may-need-update
2165 (org-table-align))))))
2167 (defun org-table-put-field-property (prop value
)
2169 (put-text-property (progn (skip-chars-backward "^|") (point))
2170 (progn (skip-chars-forward "^|") (point))
2173 (defun org-table-get-range (desc &optional tbeg col highlight
)
2174 "Get a calc vector from a column, accorting to descriptor DESC.
2175 Optional arguments TBEG and COL can give the beginning of the table and
2176 the current column, to avoid unnecessary parsing.
2177 HIGHLIGHT means, just highlight the range."
2178 (if (not (equal (string-to-char desc
) ?
@))
2179 (setq desc
(concat "@" desc
)))
2181 (or tbeg
(setq tbeg
(org-table-begin)))
2182 (or col
(setq col
(org-table-current-column)))
2183 (let ((thisline (org-current-line))
2184 beg end c1 c2 r1 r2 rangep tmp
)
2185 (unless (string-match org-table-range-regexp desc
)
2186 (error "Invalid table range specifier `%s'" desc
))
2187 (setq rangep
(match-end 3)
2188 r1
(and (match-end 1) (match-string 1 desc
))
2189 r2
(and (match-end 4) (match-string 4 desc
))
2190 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2191 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2193 (and c1
(setq c1
(+ (string-to-number c1
)
2194 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2195 (and c2
(setq c2
(+ (string-to-number c2
)
2196 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2197 (if (equal r1
"") (setq r1 nil
))
2198 (if (equal r2
"") (setq r2 nil
))
2199 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2200 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2201 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2202 (if (not r1
) (setq r1 thisline
))
2203 (if (not r2
) (setq r2 thisline
))
2204 (if (not c1
) (setq c1 col
))
2205 (if (not c2
) (setq c2 col
))
2206 (if (or (not rangep
) (and (= r1 r2
) (= c1 c2
)))
2210 (while (not (looking-at org-table-dataline-regexp
))
2211 (beginning-of-line 2))
2212 (prog1 (org-trim (org-table-get-field c1
))
2213 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2214 ;; A range, return a vector
2215 ;; First sort the numbers to get a regular ractangle
2216 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2217 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2219 (while (not (looking-at org-table-dataline-regexp
))
2220 (beginning-of-line 2))
2221 (org-table-goto-column c1
)
2224 (while (not (looking-at org-table-dataline-regexp
))
2225 (beginning-of-line 0))
2226 (org-table-goto-column c2
)
2229 (org-table-highlight-rectangle
2230 beg
(progn (skip-chars-forward "^|\n") (point))))
2231 ;; return string representation of calc vector
2233 (apply 'append
(org-table-copy-region beg end
)))))))
2235 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2236 "Analyze descriptor DESC and retrieve the corresponding line number.
2237 The cursor is currently in line CLINE, the table begins in line BLINE,
2238 and TABLE is a vector with line types."
2239 (if (string-match "^[0-9]+$" desc
)
2240 (aref org-table-dlines
(string-to-number desc
))
2241 (setq cline
(or cline
(org-current-line))
2242 bline
(or bline org-table-current-begin-line
)
2243 table
(or table org-table-current-line-types
))
2245 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2247 (and (not (match-end 3)) (not (match-end 6)))
2248 (and (match-end 3) (match-end 6) (not (match-end 5))))
2249 (error "invalid row descriptor `%s'" desc
))
2250 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2251 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2252 (odir (and (match-end 5) (match-string 5 desc
)))
2253 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2255 (rel (and (match-end 6)
2256 (or (and (match-end 1) (not (match-end 3)))
2258 (if (and hn
(not hdir
))
2261 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2262 (if (and (not hn
) on
(not odir
))
2263 (error "should never happen");;(aref org-table-dlines on)
2264 (if (and hn
(> hn
0))
2265 (setq i
(org-find-row-type table i
'hline
(equal hdir
"-") nil hn
)))
2267 (setq i
(org-find-row-type table i
'dline
(equal odir
"-") rel on
)))
2270 (defun org-find-row-type (table i type backwards relative n
)
2271 (let ((l (length table
)))
2273 (while (and (setq i
(+ i
(if backwards -
1 1)))
2275 (not (eq (aref table i
) type
))
2276 (if (and relative
(eq (aref table i
) 'hline
))
2277 (progn (setq i
(- i
(if backwards -
1 1)) n
1) nil
)
2280 (if (or (< i
0) (>= i l
))
2281 (error "Row descriptor leads outside table")
2284 (defun org-rewrite-old-row-references (s)
2285 (if (string-match "&[-+0-9I]" s
)
2286 (error "Formula contains old &row reference, please rewrite using @-syntax")
2289 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2290 "Convert list ELEMENTS to something appropriate to insert into formula.
2291 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2292 NUMBERS indicates that everything should be converted to numbers.
2293 LISPP means to return something appropriate for a Lisp list."
2294 (if (stringp elements
) ; just a single val
2296 (if (eq lispp
'literal
)
2298 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2299 (if (equal elements
"") (setq elements
"0"))
2300 (if numbers
(setq elements
(number-to-string (string-to-number elements
))))
2301 (concat "(" elements
")"))
2305 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2307 (setq elements
(or elements
'("0")))
2311 (if (eq lispp
'literal
)
2313 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2315 (concat "[" (mapconcat
2317 (if numbers
(number-to-string (string-to-number x
)) x
))
2321 (defun org-table-recalculate (&optional all noalign
)
2322 "Recalculate the current table line by applying all stored formulas.
2323 With prefix arg ALL, do this for all lines in the table."
2325 (or (memq this-command org-recalc-commands
)
2326 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2327 (unless (org-at-table-p) (error "Not at a table"))
2328 (if (equal all
'(16))
2330 (org-table-get-specials)
2331 (let* ((eqlist (sort (org-table-get-stored-formulas)
2332 (lambda (a b
) (string< (car a
) (car b
)))))
2333 (inhibit-redisplay (not debug-on-error
))
2334 (line-re org-table-dataline-regexp
)
2335 (thisline (org-current-line))
2336 (thiscol (org-table-current-column))
2337 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name
)
2338 ;; Insert constants in all formulas
2341 (setcdr x
(org-table-formula-substitute-names (cdr x
)))
2344 ;; Split the equation list
2345 (while (setq eq
(pop eqlist
))
2346 (if (<= (string-to-char (car eq
)) ?
9)
2349 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
2352 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
2353 (goto-char (setq beg
(org-table-begin)))
2354 (if (re-search-forward org-table-calculate-mark-regexp end t
)
2355 ;; This is a table with marked lines, compute selected lines
2356 (setq line-re org-table-recalculate-regexp
)
2357 ;; Move forward to the first non-header line
2358 (if (and (re-search-forward org-table-dataline-regexp end t
)
2359 (re-search-forward org-table-hline-regexp end t
)
2360 (re-search-forward org-table-dataline-regexp end t
))
2361 (setq beg
(match-beginning 0))
2362 nil
))) ;; just leave beg where it is
2363 (setq beg
(point-at-bol)
2364 end
(move-marker (make-marker) (1+ (point-at-eol)))))
2366 (and all
(message "Re-applying formulas to full table..."))
2368 ;; First find the named fields, and mark them untouchanble
2369 (remove-text-properties beg end
'(org-untouchable t
))
2370 (while (setq eq
(pop eqlname
))
2372 a
(assoc name org-table-named-field-locations
))
2374 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
2376 (aref org-table-dlines
2377 (string-to-number (match-string 1 name
)))
2378 (string-to-number (match-string 2 name
)))))
2379 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
2380 (message "Re-applying formula to field: %s" name
)
2381 (goto-line (nth 1 a
))
2382 (org-table-goto-column (nth 2 a
))
2383 (push (append a
(list (cdr eq
))) eqlname1
)
2384 (org-table-put-field-property :org-untouchable t
)))
2386 ;; Now evauluate the column formulas, but skip fields covered by
2389 (while (re-search-forward line-re end t
)
2390 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2391 ;; Unprotected line, recalculate
2392 (and all
(message "Re-applying formulas to full table...(line %d)"
2393 (setq cnt
(1+ cnt
))))
2394 (setq org-last-recalc-line
(org-current-line))
2396 (while (setq entry
(pop eql
))
2397 (goto-line org-last-recalc-line
)
2398 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
2399 (unless (get-text-property (point) :org-untouchable
)
2400 (org-table-eval-formula nil
(cdr entry
)
2401 'noalign
'nocst
'nostore
'noanalysis
)))))
2403 ;; Now evaluate the field formulas
2404 (while (setq eq
(pop eqlname1
))
2405 (message "Re-applying formula to field: %s" (car eq
))
2406 (goto-line (nth 1 eq
))
2407 (org-table-goto-column (nth 2 eq
))
2408 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
2409 'nostore
'noanalysis
))
2411 (goto-line thisline
)
2412 (org-table-goto-column thiscol
)
2413 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
2414 (or noalign
(and org-table-may-need-update
(org-table-align))
2415 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
2417 ;; back to initial position
2418 (message "Re-applying formulas...done")
2419 (goto-line thisline
)
2420 (org-table-goto-column thiscol
)
2421 (or noalign
(and org-table-may-need-update
(org-table-align))
2422 (and all
(message "Re-applying formulas...done"))))))
2424 (defun org-table-iterate (&optional arg
)
2425 "Recalculate the table until it does not change anymore."
2427 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
2429 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2434 (org-table-recalculate 'all
)
2435 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
2436 (if (not (string= lasttbl thistbl
))
2437 (setq lasttbl thistbl
)
2439 (message "Convergence after %d iterations" i
)
2440 (message "Table was already stable"))
2442 (error "No convergence after %d iterations" i
))))
2444 (defun org-table-formula-substitute-names (f)
2445 "Replace $const with values in string F."
2446 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
2447 ;; First, check for column names
2448 (while (setq start
(string-match org-table-column-name-regexp f start
))
2449 (setq start
(1+ start
))
2450 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
2451 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
2452 ;; Parameters and constants
2454 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start
))
2455 (setq start
(1+ start
))
2456 (if (setq a
(save-match-data
2457 (org-table-get-constant (match-string 1 f
))))
2458 (setq f
(replace-match
2459 (concat (if pp
"(") a
(if pp
")")) t t f
))))
2460 (if org-table-formula-debug
2461 (put-text-property 0 (length f
) :orig-formula f1 f
))
2464 (defun org-table-get-constant (const)
2465 "Find the value for a parameter or constant in a formula.
2466 Parameters get priority."
2467 (or (cdr (assoc const org-table-local-parameters
))
2468 (cdr (assoc const org-table-formula-constants-local
))
2469 (cdr (assoc const org-table-formula-constants
))
2470 (and (fboundp 'constants-get
) (constants-get const
))
2471 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
2472 (org-entry-get nil
(substring const
5) 'inherit
))
2475 (defvar org-table-fedit-map
2476 (let ((map (make-sparse-keymap)))
2477 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
2478 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
2479 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
2480 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
2481 (org-defkey map
"\C-c?" 'org-table-show-reference
)
2482 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
2483 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
2484 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
2485 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
2486 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
2487 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
2488 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
2489 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
2490 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
2491 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
2492 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
2493 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
2494 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
2495 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
2498 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
2500 ["Finish and Install" org-table-fedit-finish t
]
2501 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
2502 ["Abort" org-table-fedit-abort t
]
2504 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
2505 ["Complete Lisp Symbol" lisp-complete-symbol t
]
2507 "Shift Reference at Point"
2508 ["Up" org-table-fedit-ref-up t
]
2509 ["Down" org-table-fedit-ref-down t
]
2510 ["Left" org-table-fedit-ref-left t
]
2511 ["Right" org-table-fedit-ref-right t
]
2513 "Change Test Row for Column Formulas"
2514 ["Up" org-table-fedit-line-up t
]
2515 ["Down" org-table-fedit-line-down t
]
2517 ["Scroll Table Window" org-table-fedit-scroll t
]
2518 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
2519 ["Show Table Grid" org-table-fedit-toggle-coordinates
2520 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
2521 org-table-overlay-coordinates
)]
2523 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
2524 :style toggle
:selected org-table-buffer-is-an
]))
2528 (defun org-table-edit-formulas ()
2529 "Edit the formulas of the current table in a separate buffer."
2531 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
2532 (beginning-of-line 0))
2533 (unless (org-at-table-p) (error "Not at a table"))
2534 (org-table-get-specials)
2535 (let ((key (org-table-current-field-formula 'key
'noerror
))
2536 (eql (sort (org-table-get-stored-formulas 'noerror
)
2537 'org-table-formula-less-p
))
2538 (pos (move-marker (make-marker) (point)))
2540 (wc (current-window-configuration))
2541 (titles '((column .
"# Column Formulas\n")
2542 (field .
"# Field Formulas\n")
2543 (named .
"# Named Field Formulas\n")))
2545 (org-switch-to-buffer-other-window "*Edit Formulas*")
2547 ;; Keep global-font-lock-mode from turning on font-lock-mode
2548 (let ((font-lock-global-modes '(not fundamental-mode
)))
2550 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
2551 (org-set-local 'org-pos pos
)
2552 (org-set-local 'org-window-configuration wc
)
2553 (use-local-map org-table-fedit-map
)
2554 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
2555 (easy-menu-add org-table-fedit-menu
)
2556 (setq startline
(org-current-line))
2557 (while (setq entry
(pop eql
))
2559 ((equal (string-to-char (car entry
)) ?
@) 'field
)
2560 ((string-match "^[0-9]" (car entry
)) 'column
)
2562 (when (setq title
(assq type titles
))
2563 (or (bobp) (insert "\n"))
2564 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
2565 (setq titles
(delq title titles
)))
2566 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
2567 (setq s
(concat (if (equal (string-to-char (car entry
)) ?
@) "" "$")
2568 (car entry
) " = " (cdr entry
) "\n"))
2569 (remove-text-properties 0 (length s
) '(face nil
) s
)
2571 (if (eq org-table-use-standard-references t
)
2572 (org-table-fedit-toggle-ref-type))
2573 (goto-line startline
)
2574 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
2576 (defun org-table-fedit-post-command ()
2577 (when (not (memq this-command
'(lisp-complete-symbol)))
2578 (let ((win (selected-window)))
2581 (org-table-show-reference)
2583 (select-window win
)))))
2585 (defun org-table-formula-to-user (s)
2586 "Convert a formula from internal to user representation."
2587 (if (eq org-table-use-standard-references t
)
2588 (org-table-convert-refs-to-an s
)
2591 (defun org-table-formula-from-user (s)
2592 "Convert a formula from user to internal representation."
2593 (if org-table-use-standard-references
2594 (org-table-convert-refs-to-rc s
)
2597 (defun org-table-convert-refs-to-rc (s)
2598 "Convert spreadsheet references from AB7 to @7$28.
2599 Works for single references, but also for entire formulas and even the
2602 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start
)
2605 ;; format match, just advance
2606 (setq start
(match-end 0)))
2607 ((and (> (match-beginning 0) 0)
2608 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
2609 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
2610 ;; 3.e5 or something like this.
2611 (setq start
(match-end 0)))
2613 (setq start
(match-beginning 0)
2615 (if (equal (match-string 2 s
) "&")
2616 (format "$%d" (org-letters-to-number (match-string 1 s
)))
2618 (string-to-number (match-string 2 s
))
2619 (org-letters-to-number (match-string 1 s
))))
2623 (defun org-table-convert-refs-to-an (s)
2624 "Convert spreadsheet references from to @7$28 to AB7.
2625 Works for single references, but also for entire formulas and even the
2627 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
2628 (setq s
(replace-match
2630 (org-number-to-letters
2631 (string-to-number (match-string 2 s
)))
2632 (string-to-number (match-string 1 s
)))
2634 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
2635 (setq s
(replace-match (concat "\\1"
2636 (org-number-to-letters
2637 (string-to-number (match-string 2 s
))) "&")
2641 (defun org-letters-to-number (s)
2642 "Convert a base 26 number represented by letters into an integer.
2643 For example: AB -> 28."
2646 (while (> (length s
) 0)
2647 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
2651 (defun org-number-to-letters (n)
2652 "Convert an integer into a base 26 number represented by letters.
2653 For example: 28 -> AB."
2656 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
2660 (defun org-table-fedit-convert-buffer (function)
2661 "Convert all references in this buffer, using FUNTION."
2662 (let ((line (org-current-line)))
2663 (goto-char (point-min))
2665 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
2666 (delete-region (point) (point-at-eol))
2667 (or (eobp) (forward-char 1)))
2670 (defun org-table-fedit-toggle-ref-type ()
2671 "Convert all references in the buffer from B3 to @3$2 and back."
2673 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
2674 (org-table-fedit-convert-buffer
2675 (if org-table-buffer-is-an
2676 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
2677 (message "Reference type switched to %s"
2678 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
2680 (defun org-table-fedit-ref-up ()
2681 "Shift the reference at point one row/hline up."
2683 (org-table-fedit-shift-reference 'up
))
2684 (defun org-table-fedit-ref-down ()
2685 "Shift the reference at point one row/hline down."
2687 (org-table-fedit-shift-reference 'down
))
2688 (defun org-table-fedit-ref-left ()
2689 "Shift the reference at point one field to the left."
2691 (org-table-fedit-shift-reference 'left
))
2692 (defun org-table-fedit-ref-right ()
2693 "Shift the reference at point one field to the right."
2695 (org-table-fedit-shift-reference 'right
))
2697 (defun org-table-fedit-shift-reference (dir)
2699 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
2700 (if (memq dir
'(left right
))
2701 (org-rematch-and-replace 1 (eq dir
'left
))
2702 (error "Cannot shift reference in this direction")))
2703 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
2704 ;; A B3-like reference
2705 (if (memq dir
'(up down
))
2706 (org-rematch-and-replace 2 (eq dir
'up
))
2707 (org-rematch-and-replace 1 (eq dir
'left
))))
2709 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
2710 ;; An internal reference
2711 (if (memq dir
'(up down
))
2712 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
2713 (org-rematch-and-replace 5 (eq dir
'left
))))))
2715 (defun org-rematch-and-replace (n &optional decr hline
)
2716 "Re-match the group N, and replace it with the shifted refrence."
2717 (or (match-end n
) (error "Cannot shift reference in this direction"))
2718 (goto-char (match-beginning n
))
2719 (and (looking-at (regexp-quote (match-string n
)))
2720 (replace-match (org-shift-refpart (match-string 0) decr hline
)
2723 (defun org-shift-refpart (ref &optional decr hline
)
2724 "Shift a refrence part REF.
2725 If DECR is set, decrease the references row/column, else increase.
2726 If HLINE is set, this may be a hline reference, it certainly is not
2727 a translation reference."
2729 (let* ((sign (string-match "^[-+]" ref
)) n
)
2731 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
2733 ((and hline
(string-match "^I+" ref
))
2734 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
2735 (setq n
(+ n
(if decr -
1 1)))
2736 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
2738 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
2740 (concat sign
(make-string n ?I
)))
2742 ((string-match "^[0-9]+" ref
)
2743 (setq n
(string-to-number (concat sign ref
)))
2744 (setq n
(+ n
(if decr -
1 1)))
2746 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
2747 (number-to-string (max 1 n
))))
2749 ((string-match "^[a-zA-Z]+" ref
)
2750 (org-number-to-letters
2751 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
2753 (t (error "Cannot shift reference"))))))
2755 (defun org-table-fedit-toggle-coordinates ()
2756 "Toggle the display of coordinates in the refrenced table."
2758 (let ((pos (marker-position org-pos
)))
2759 (with-current-buffer (marker-buffer org-pos
)
2762 (org-table-toggle-coordinate-overlays)))))
2764 (defun org-table-fedit-finish (&optional arg
)
2765 "Parse the buffer for formula definitions and install them.
2766 With prefix ARG, apply the new formulas to the table."
2768 (org-table-remove-rectangle-highlight)
2769 (if org-table-use-standard-references
2771 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
2772 (setq org-table-buffer-is-an nil
)))
2773 (let ((pos org-pos
) eql var form
)
2774 (goto-char (point-min))
2775 (while (re-search-forward
2776 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
2778 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
2779 form
(match-string 3))
2780 (setq form
(org-trim form
))
2781 (when (not (equal form
""))
2782 (while (string-match "[ \t]*\n[ \t]*" form
)
2783 (setq form
(replace-match " " t t form
)))
2784 (when (assoc var eql
)
2785 (error "Double formulas for %s" var
))
2786 (push (cons var form
) eql
)))
2788 (set-window-configuration org-window-configuration
)
2789 (select-window (get-buffer-window (marker-buffer pos
)))
2791 (unless (org-at-table-p)
2792 (error "Lost table position - cannot install formulae"))
2793 (org-table-store-formulas eql
)
2794 (move-marker pos nil
)
2795 (kill-buffer "*Edit Formulas*")
2797 (org-table-recalculate 'all
)
2798 (message "New formulas installed - press C-u C-c C-c to apply."))))
2800 (defun org-table-fedit-abort ()
2801 "Abort editing formulas, without installing the changes."
2803 (org-table-remove-rectangle-highlight)
2804 (let ((pos org-pos
))
2805 (set-window-configuration org-window-configuration
)
2806 (select-window (get-buffer-window (marker-buffer pos
)))
2808 (move-marker pos nil
)
2809 (message "Formula editing aborted without installing changes")))
2811 (defun org-table-fedit-lisp-indent ()
2812 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
2814 (let ((pos (point)) beg end ind
)
2815 (beginning-of-line 1)
2817 ((looking-at "[ \t]")
2819 (call-interactively 'lisp-indent-line
))
2820 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
2821 ((not (fboundp 'pp-buffer
))
2822 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
2823 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
2824 (goto-char (- (match-end 0) 2))
2826 (setq ind
(make-string (current-column) ?\
))
2827 (condition-case nil
(forward-sexp 1)
2829 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
2832 (narrow-to-region beg end
)
2833 (if (eq last-command this-command
)
2835 (goto-char (point-min))
2836 (setq this-command nil
)
2837 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
2838 (replace-match " ")))
2840 (untabify (point-min) (point-max))
2841 (goto-char (1+ (point-min)))
2842 (while (re-search-forward "^." nil t
)
2843 (beginning-of-line 1)
2845 (goto-char (point-max))
2846 (backward-delete-char 1)))
2850 (defvar org-show-positions nil
)
2852 (defun org-table-show-reference (&optional local
)
2853 "Show the location/value of the $ expression at point."
2855 (org-table-remove-rectangle-highlight)
2857 (let ((pos (if local
(point) org-pos
))
2859 (org-inhibit-highlight-removal t
)
2860 (win (selected-window))
2861 (org-show-positions nil
)
2862 var name e what match dest
)
2863 (if local
(org-table-get-specials))
2865 ((or (org-at-regexp-p org-table-range-regexp2
)
2866 (org-at-regexp-p org-table-translate-regexp
)
2867 (org-at-regexp-p org-table-range-regexp
))
2870 (org-table-convert-refs-to-rc (match-string 0))))
2872 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
2873 ((org-at-regexp-p "\\$[0-9]+") 'column
)
2875 (t (error "No reference at point")))
2876 match
(and what
(or match
(match-string 0))))
2877 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
2878 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
2879 'secondary-selection
))
2880 (org-add-hook 'before-change-functions
2881 'org-table-remove-rectangle-highlight
)
2882 (if (eq what
'name
) (setq var
(substring match
1)))
2883 (when (eq what
'range
)
2884 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
2885 (setq match
(org-table-formula-substitute-names match
)))
2889 (re-search-backward "^\\S-" nil t
)
2890 (beginning-of-line 1)
2891 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
2894 (org-table-convert-refs-to-rc (match-string 1))))
2895 (org-table-add-rectangle-overlay
2896 (match-beginning 1) (match-end 1) face2
))))
2897 (if (and (markerp pos
) (marker-buffer pos
))
2898 (if (get-buffer-window (marker-buffer pos
))
2899 (select-window (get-buffer-window (marker-buffer pos
)))
2900 (org-switch-to-buffer-other-window (get-buffer-window
2901 (marker-buffer pos
)))))
2903 (org-table-force-dataline)
2905 (setq name
(substring dest
1))
2907 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
2908 (setq e
(assoc name org-table-named-field-locations
))
2909 (goto-line (nth 1 e
))
2910 (org-table-goto-column (nth 2 e
)))
2911 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
2912 (let ((l (string-to-number (match-string 1 dest
)))
2913 (c (string-to-number (match-string 2 dest
))))
2914 (goto-line (aref org-table-dlines l
))
2915 (org-table-goto-column c
)))
2916 (t (org-table-goto-column (string-to-number name
))))
2917 (move-marker pos
(point))
2918 (org-table-highlight-rectangle nil nil face2
))
2920 ((equal dest match
))
2925 (org-table-get-range match nil nil
'highlight
))
2927 ((setq e
(assoc var org-table-named-field-locations
))
2928 (goto-line (nth 1 e
))
2929 (org-table-goto-column (nth 2 e
))
2930 (org-table-highlight-rectangle (point) (point))
2931 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
2932 ((setq e
(assoc var org-table-column-names
))
2933 (org-table-goto-column (string-to-number (cdr e
)))
2934 (org-table-highlight-rectangle (point) (point))
2935 (goto-char (org-table-begin))
2936 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
2939 (goto-char (match-beginning 1))
2940 (org-table-highlight-rectangle)
2941 (message "Named column (column %s)" (cdr e
)))
2942 (error "Column name not found")))
2945 (org-table-goto-column (string-to-number (substring match
1)))
2946 (org-table-highlight-rectangle (point) (point))
2947 (message "Column %s" (substring match
1)))
2948 ((setq e
(assoc var org-table-local-parameters
))
2949 (goto-char (org-table-begin))
2950 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
2952 (goto-char (match-beginning 1))
2953 (org-table-highlight-rectangle)
2954 (message "Local parameter."))
2955 (error "Parameter not found")))
2958 ((not var
) (error "No reference at point"))
2959 ((setq e
(assoc var org-table-formula-constants-local
))
2960 (message "Local Constant: $%s=%s in #+CONSTANTS line."
2962 ((setq e
(assoc var org-table-formula-constants
))
2963 (message "Constant: $%s=%s in `org-table-formula-constants'."
2965 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
2966 (message "Constant: $%s=%s, from `constants.el'%s."
2967 var e
(format " (%s units)" constants-unit-system
)))
2968 (t (error "Undefined name $%s" var
)))))
2970 (when (and org-show-positions
2971 (not (memq this-command
'(org-table-fedit-scroll
2972 org-table-fedit-scroll-down
))))
2973 (push pos org-show-positions
)
2974 (push org-table-current-begin-pos org-show-positions
)
2975 (let ((min (apply 'min org-show-positions
))
2976 (max (apply 'max org-show-positions
)))
2977 (goto-char min
) (recenter 0)
2979 (or (pos-visible-in-window-p max
) (recenter -
1))))
2980 (select-window win
))))
2982 (defun org-table-force-dataline ()
2983 "Make sure the cursor is in a dataline in a table."
2984 (unless (save-excursion
2985 (beginning-of-line 1)
2986 (looking-at org-table-dataline-regexp
))
2987 (let* ((re org-table-dataline-regexp
)
2988 (p1 (save-excursion (re-search-forward re nil
'move
)))
2989 (p2 (save-excursion (re-search-backward re nil
'move
))))
2991 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
2993 ((or p1 p2
) (goto-char (or p1 p2
)))
2994 (t (error "No table dataline around here"))))))
2996 (defun org-table-fedit-line-up ()
2997 "Move cursor one line up in the window showing the table."
2999 (org-table-fedit-move 'previous-line
))
3001 (defun org-table-fedit-line-down ()
3002 "Move cursor one line down in the window showing the table."
3004 (org-table-fedit-move 'next-line
))
3006 (defun org-table-fedit-move (command)
3007 "Move the cursor in the window shoinw the table.
3008 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3009 (let ((org-table-allow-automatic-line-recalculation nil
)
3010 (pos org-pos
) (win (selected-window)) p
)
3011 (select-window (get-buffer-window (marker-buffer org-pos
)))
3013 (call-interactively command
)
3014 (while (and (org-at-table-p)
3015 (org-at-table-hline-p))
3016 (call-interactively command
))
3017 (or (org-at-table-p) (goto-char p
))
3018 (move-marker pos
(point))
3019 (select-window win
)))
3021 (defun org-table-fedit-scroll (N)
3023 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3024 (scroll-other-window N
)))
3026 (defun org-table-fedit-scroll-down (N)
3028 (org-table-fedit-scroll (- N
)))
3030 (defvar org-table-rectangle-overlays nil
)
3032 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3033 "Add a new overlay."
3034 (let ((ov (org-make-overlay beg end
)))
3035 (org-overlay-put ov
'face
(or face
'secondary-selection
))
3036 (push ov org-table-rectangle-overlays
)))
3038 (defun org-table-highlight-rectangle (&optional beg end face
)
3039 "Highlight rectangular region in a table."
3040 (setq beg
(or beg
(point)) end
(or end
(point)))
3041 (let ((b (min beg end
))
3044 (and (boundp 'org-show-positions
)
3045 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3046 (goto-char (min beg end
))
3047 (setq l1
(org-current-line)
3048 c1
(org-table-current-column))
3049 (goto-char (max beg end
))
3050 (setq l2
(org-current-line)
3051 c2
(org-table-current-column))
3052 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3054 (beginning-of-line 1)
3055 (loop for line from l1 to l2 do
3056 (when (looking-at org-table-dataline-regexp
)
3057 (org-table-goto-column c1
)
3058 (skip-chars-backward "^|\n") (setq beg
(point))
3059 (org-table-goto-column c2
)
3060 (skip-chars-forward "^|\n") (setq end
(point))
3061 (org-table-add-rectangle-overlay beg end face
))
3062 (beginning-of-line 2))
3064 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3066 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3067 "Remove the rectangle overlays."
3068 (unless org-inhibit-highlight-removal
3069 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3070 (mapc 'org-delete-overlay org-table-rectangle-overlays
)
3071 (setq org-table-rectangle-overlays nil
)))
3073 (defvar org-table-coordinate-overlays nil
3074 "Collects the cooordinate grid overlays, so that they can be removed.")
3075 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3077 (defun org-table-overlay-coordinates ()
3078 "Add overlays to the table at point, to show row/column coordinates."
3080 (mapc 'org-delete-overlay org-table-coordinate-overlays
)
3081 (setq org-table-coordinate-overlays nil
)
3083 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3084 (goto-char (org-table-begin))
3085 (while (org-at-table-p)
3086 (setq eol
(point-at-eol))
3087 (setq ov
(org-make-overlay (point-at-bol) (1+ (point-at-bol))))
3088 (push ov org-table-coordinate-overlays
)
3089 (setq hline
(looking-at org-table-hline-regexp
))
3090 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3091 (format "%4d" (setq id
(1+ id
)))))
3092 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3095 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3096 (setq beg
(1+ (match-beginning 0))
3098 s1
(concat "$" (int-to-string ic
))
3099 s2
(org-number-to-letters ic
)
3100 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3101 (setq ov
(org-make-overlay beg
(+ beg
(length str
))))
3102 (push ov org-table-coordinate-overlays
)
3103 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3104 (beginning-of-line 2)))))
3106 (defun org-table-toggle-coordinate-overlays ()
3107 "Toggle the display of Row/Column numbers in tables."
3109 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3110 (message "Row/Column number display turned %s"
3111 (if org-table-overlay-coordinates
"on" "off"))
3112 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3114 (unless org-table-overlay-coordinates
3115 (mapc 'org-delete-overlay org-table-coordinate-overlays
)
3116 (setq org-table-coordinate-overlays nil
)))
3118 (defun org-table-toggle-formula-debugger ()
3119 "Toggle the formula debugger in tables."
3121 (setq org-table-formula-debug
(not org-table-formula-debug
))
3122 (message "Formula debugging has been turned %s"
3123 (if org-table-formula-debug
"on" "off")))
3125 ;;; The orgtbl minor mode
3127 ;; Define a minor mode which can be used in other modes in order to
3128 ;; integrate the org-mode table editor.
3130 ;; This is really a hack, because the org-mode table editor uses several
3131 ;; keys which normally belong to the major mode, for example the TAB and
3132 ;; RET keys. Here is how it works: The minor mode defines all the keys
3133 ;; necessary to operate the table editor, but wraps the commands into a
3134 ;; function which tests if the cursor is currently inside a table. If that
3135 ;; is the case, the table editor command is executed. However, when any of
3136 ;; those keys is used outside a table, the function uses `key-binding' to
3137 ;; look up if the key has an associated command in another currently active
3138 ;; keymap (minor modes, major mode, global), and executes that command.
3139 ;; There might be problems if any of the keys used by the table editor is
3140 ;; otherwise used as a prefix key.
3142 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3143 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3144 ;; addresses this by checking explicitly for both bindings.
3146 ;; The optimized version (see variable `orgtbl-optimized') takes over
3147 ;; all keys which are bound to `self-insert-command' in the *global map*.
3148 ;; Some modes bind other commands to simple characters, for example
3149 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3150 ;; active, this binding is ignored inside tables and replaced with a
3151 ;; modified self-insert.
3153 (defvar orgtbl-mode nil
3154 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
3155 table editor in arbitrary modes.")
3156 (make-variable-buffer-local 'orgtbl-mode
)
3158 (defvar orgtbl-mode-map
(make-keymap)
3159 "Keymap for `orgtbl-mode'.")
3162 (defun turn-on-orgtbl ()
3163 "Unconditionally turn on `orgtbl-mode'."
3166 (defvar org-old-auto-fill-inhibit-regexp nil
3167 "Local variable used by `orgtbl-mode'")
3169 (defconst orgtbl-line-start-regexp
"[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
3170 "Matches a line belonging to an orgtbl.")
3172 (defconst orgtbl-extra-font-lock-keywords
3173 (list (list (concat "^" orgtbl-line-start-regexp
".*")
3174 0 (quote 'org-table
) 'prepend
))
3175 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
3178 (defun orgtbl-mode (&optional arg
)
3179 "The `org-mode' table editor as a minor mode for use in other modes."
3181 (org-load-modules-maybe)
3183 ;; Exit without error, in case some hook functions calls this
3184 ;; by accident in org-mode.
3185 (message "Orgtbl-mode is not useful in org-mode, command ignored")
3187 (if arg
(> (prefix-numeric-value arg
) 0) (not orgtbl-mode
)))
3190 (and (orgtbl-setup) (defun orgtbl-setup () nil
))
3191 ;; Make sure we are first in minor-mode-map-alist
3192 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
3193 (and c
(setq minor-mode-map-alist
3194 (cons c
(delq c minor-mode-map-alist
)))))
3195 (org-set-local (quote org-table-may-need-update
) t
)
3196 (org-add-hook 'before-change-functions
'org-before-change-function
3198 (org-set-local 'org-old-auto-fill-inhibit-regexp
3199 auto-fill-inhibit-regexp
)
3200 (org-set-local 'auto-fill-inhibit-regexp
3201 (if auto-fill-inhibit-regexp
3202 (concat orgtbl-line-start-regexp
"\\|"
3203 auto-fill-inhibit-regexp
)
3204 orgtbl-line-start-regexp
))
3205 (org-add-to-invisibility-spec '(org-cwidth))
3206 (when (fboundp 'font-lock-add-keywords
)
3207 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
3208 (org-restart-font-lock))
3209 (easy-menu-add orgtbl-mode-menu
)
3210 (run-hooks 'orgtbl-mode-hook
))
3211 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
3212 (org-cleanup-narrow-column-properties)
3213 (org-remove-from-invisibility-spec '(org-cwidth))
3214 (remove-hook 'before-change-functions
'org-before-change-function t
)
3215 (when (fboundp 'font-lock-remove-keywords
)
3216 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
3217 (org-restart-font-lock))
3218 (easy-menu-remove orgtbl-mode-menu
)
3219 (force-mode-line-update 'all
))))
3221 (defun org-cleanup-narrow-column-properties ()
3222 "Remove all properties related to narrow-column invisibility."
3224 (while (setq s
(text-property-any s
(point-max)
3225 'display org-narrow-column-arrow
))
3226 (remove-text-properties s
(1+ s
) '(display t
)))
3228 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
3229 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
3231 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
3232 (remove-text-properties s
(1+ s
) '(invisible t
)))))
3234 ;; Install it as a minor mode.
3235 (put 'orgtbl-mode
:included t
)
3236 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
3237 (add-minor-mode 'orgtbl-mode
" OrgTbl" orgtbl-mode-map
)
3239 (defun orgtbl-make-binding (fun n
&rest keys
)
3240 "Create a function for binding in the table minor mode.
3241 FUN is the command to call inside a table. N is used to create a unique
3242 command name. KEYS are keys that should be checked in for a command
3243 to execute outside of tables."
3246 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
3248 (concat "In tables, run `" (symbol-name fun
) "'.\n"
3249 "Outside of tables, run the binding of `"
3250 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
3255 (list 'call-interactively
(list 'quote fun
))
3256 (list 'let
'(orgtbl-mode)
3257 (list 'call-interactively
3260 (list 'key-binding k
))
3262 '('orgtbl-error
))))))))
3264 (defun orgtbl-error ()
3265 "Error when there is no default binding for a table key."
3267 (error "This key has no function outside tables"))
3269 (defun orgtbl-setup ()
3270 "Setup orgtbl keymaps."
3274 '([(meta shift left
)] org-table-delete-column
)
3275 '([(meta left
)] org-table-move-column-left
)
3276 '([(meta right
)] org-table-move-column-right
)
3277 '([(meta shift right
)] org-table-insert-column
)
3278 '([(meta shift up
)] org-table-kill-row
)
3279 '([(meta shift down
)] org-table-insert-row
)
3280 '([(meta up
)] org-table-move-row-up
)
3281 '([(meta down
)] org-table-move-row-down
)
3282 '("\C-c\C-w" org-table-cut-region
)
3283 '("\C-c\M-w" org-table-copy-region
)
3284 '("\C-c\C-y" org-table-paste-rectangle
)
3285 '("\C-c-" org-table-insert-hline
)
3286 '("\C-c}" org-table-toggle-coordinate-overlays
)
3287 '("\C-c{" org-table-toggle-formula-debugger
)
3288 '("\C-m" org-table-next-row
)
3289 '([(shift return
)] org-table-copy-down
)
3290 '("\C-c\C-q" org-table-wrap-region
)
3291 '("\C-c?" org-table-field-info
)
3292 '("\C-c " org-table-blank-field
)
3293 '("\C-c+" org-table-sum
)
3294 '("\C-c=" org-table-eval-formula
)
3295 '("\C-c'" org-table-edit-formulas
)
3296 '("\C-c`" org-table-edit-field
)
3297 '("\C-c*" org-table-recalculate
)
3298 '("\C-c|" org-table-create-or-convert-from-region
)
3299 '("\C-c^" org-table-sort-lines
)
3300 '([(control ?
#)] org-table-rotate-recalc-marks
)))
3302 (while (setq elt
(pop bindings
))
3303 (setq nfunc
(1+ nfunc
))
3304 (setq key
(org-key (car elt
))
3306 cmd
(orgtbl-make-binding fun nfunc key
))
3307 (org-defkey orgtbl-mode-map key cmd
))
3309 ;; Special treatment needed for TAB and RET
3310 (org-defkey orgtbl-mode-map
[(return)]
3311 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
3312 (org-defkey orgtbl-mode-map
"\C-m"
3313 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
3315 (org-defkey orgtbl-mode-map
[(tab)]
3316 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
3317 (org-defkey orgtbl-mode-map
"\C-i"
3318 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
3320 (org-defkey orgtbl-mode-map
[(shift tab
)]
3321 (orgtbl-make-binding 'org-table-previous-field
104
3322 [(shift tab
)] [(tab)] "\C-i"))
3324 (org-defkey orgtbl-mode-map
"\M-\C-m"
3325 (orgtbl-make-binding 'org-table-wrap-region
105
3326 "\M-\C-m" [(meta return
)]))
3327 (org-defkey orgtbl-mode-map
[(meta return
)]
3328 (orgtbl-make-binding 'org-table-wrap-region
106
3329 [(meta return
)] "\M-\C-m"))
3331 (org-defkey orgtbl-mode-map
"\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c
)
3332 (when orgtbl-optimized
3333 ;; If the user wants maximum table support, we need to hijack
3334 ;; some standard editing functions
3335 (org-remap orgtbl-mode-map
3336 'self-insert-command
'orgtbl-self-insert-command
3337 'delete-char
'org-delete-char
3338 'delete-backward-char
'org-delete-backward-char
)
3339 (org-defkey orgtbl-mode-map
"|" 'org-force-self-insert
))
3340 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map
"OrgTbl menu"
3342 ["Align" org-ctrl-c-ctrl-c
:active
(org-at-table-p) :keys
"C-c C-c"]
3343 ["Next Field" org-cycle
:active
(org-at-table-p) :keys
"TAB"]
3344 ["Previous Field" org-shifttab
:active
(org-at-table-p) :keys
"S-TAB"]
3345 ["Next Row" org-return
:active
(org-at-table-p) :keys
"RET"]
3347 ["Blank Field" org-table-blank-field
:active
(org-at-table-p) :keys
"C-c SPC"]
3348 ["Edit Field" org-table-edit-field
:active
(org-at-table-p) :keys
"C-c ` "]
3349 ["Copy Field from Above"
3350 org-table-copy-down
:active
(org-at-table-p) :keys
"S-RET"]
3353 ["Move Column Left" org-metaleft
:active
(org-at-table-p) :keys
"M-<left>"]
3354 ["Move Column Right" org-metaright
:active
(org-at-table-p) :keys
"M-<right>"]
3355 ["Delete Column" org-shiftmetaleft
:active
(org-at-table-p) :keys
"M-S-<left>"]
3356 ["Insert Column" org-shiftmetaright
:active
(org-at-table-p) :keys
"M-S-<right>"])
3358 ["Move Row Up" org-metaup
:active
(org-at-table-p) :keys
"M-<up>"]
3359 ["Move Row Down" org-metadown
:active
(org-at-table-p) :keys
"M-<down>"]
3360 ["Delete Row" org-shiftmetaup
:active
(org-at-table-p) :keys
"M-S-<up>"]
3361 ["Insert Row" org-shiftmetadown
:active
(org-at-table-p) :keys
"M-S-<down>"]
3362 ["Sort lines in region" org-table-sort-lines
:active
(org-at-table-p) :keys
"C-c ^"]
3364 ["Insert Hline" org-table-insert-hline
:active
(org-at-table-p) :keys
"C-c -"])
3366 ["Copy Rectangle" org-copy-special
:active
(org-at-table-p)]
3367 ["Cut Rectangle" org-cut-special
:active
(org-at-table-p)]
3368 ["Paste Rectangle" org-paste-special
:active
(org-at-table-p)]
3369 ["Fill Rectangle" org-table-wrap-region
:active
(org-at-table-p)])
3372 ["Insert table template" orgtbl-insert-radio-table
3373 (assq major-mode orgtbl-radio-table-templates
)]
3374 ["Comment/uncomment table" orgtbl-toggle-comment t
])
3376 ["Set Column Formula" org-table-eval-formula
:active
(org-at-table-p) :keys
"C-c ="]
3377 ["Set Field Formula" (org-table-eval-formula '(4)) :active
(org-at-table-p) :keys
"C-u C-c ="]
3378 ["Edit Formulas" org-table-edit-formulas
:active
(org-at-table-p) :keys
"C-c '"]
3379 ["Recalculate line" org-table-recalculate
:active
(org-at-table-p) :keys
"C-c *"]
3380 ["Recalculate all" (org-table-recalculate '(4)) :active
(org-at-table-p) :keys
"C-u C-c *"]
3381 ["Iterate all" (org-table-recalculate '(16)) :active
(org-at-table-p) :keys
"C-u C-u C-c *"]
3382 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks
:active
(org-at-table-p) :keys
"C-c #"]
3383 ["Sum Column/Rectangle" org-table-sum
3384 :active
(or (org-at-table-p) (org-region-active-p)) :keys
"C-c +"]
3385 ["Which Column?" org-table-current-column
:active
(org-at-table-p) :keys
"C-c ?"]
3387 org-table-toggle-formula-debugger
:active
(org-at-table-p)
3389 :style toggle
:selected org-table-formula-debug
]
3390 ["Show Col/Row Numbers"
3391 org-table-toggle-coordinate-overlays
:active
(org-at-table-p)
3393 :style toggle
:selected org-table-overlay-coordinates
]
3397 (defun orgtbl-ctrl-c-ctrl-c (arg)
3398 "If the cursor is inside a table, realign the table.
3399 It it is a table to be sent away to a receiver, do it.
3400 With prefix arg, also recompute table."
3402 (let ((pos (point)) action
)
3404 (beginning-of-line 1)
3405 (setq action
(cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
3406 ((looking-at "[ \t]*|") pos
)
3407 ((looking-at "#\\+TBLFM:") 'recalc
))))
3411 (org-table-maybe-eval-formula)
3413 (call-interactively 'org-table-recalculate
)
3414 (org-table-maybe-recalculate-line))
3415 (call-interactively 'org-table-align
)
3416 (orgtbl-send-table 'maybe
))
3417 ((eq action
'recalc
)
3419 (beginning-of-line 1)
3420 (skip-chars-backward " \r\n\t")
3421 (if (org-at-table-p)
3422 (org-call-with-arg 'org-table-recalculate t
))))
3423 (t (let (orgtbl-mode)
3424 (call-interactively (key-binding "\C-c\C-c")))))))
3426 (defun orgtbl-tab (arg)
3427 "Justification and field motion for `orgtbl-mode'."
3429 (if arg
(org-table-edit-field t
)
3430 (org-table-justify-field-maybe)
3431 (org-table-next-field)))
3433 (defun orgtbl-ret ()
3434 "Justification and field motion for `orgtbl-mode'."
3436 (org-table-justify-field-maybe)
3437 (org-table-next-row))
3439 (defun orgtbl-self-insert-command (N)
3440 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
3441 If the cursor is in a table looking at whitespace, the whitespace is
3442 overwritten, and the table is not marked as requiring realignment."
3444 (if (and (org-at-table-p)
3446 (and org-table-auto-blank-field
3447 (member last-command
3448 '(orgtbl-hijacker-command-100
3449 orgtbl-hijacker-command-101
3450 orgtbl-hijacker-command-102
3451 orgtbl-hijacker-command-103
3452 orgtbl-hijacker-command-104
3453 orgtbl-hijacker-command-105
))
3454 (org-table-blank-field))
3457 (looking-at "[^|\n]* +|"))
3458 (let (org-table-may-need-update)
3459 (goto-char (1- (match-end 0)))
3460 (delete-backward-char 1)
3461 (goto-char (match-beginning 0))
3462 (self-insert-command N
))
3463 (setq org-table-may-need-update t
)
3465 (call-interactively (key-binding (vector last-input-event
))))))
3467 (defvar orgtbl-exp-regexp
"^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
3468 "Regular expression matching exponentials as produced by calc.")
3470 (defun orgtbl-export (table target
)
3472 (let ((func (intern (concat "orgtbl-to-" (symbol-name target
))))
3473 (lines (org-split-string table
"[ \t]*\n[ \t]*"))
3474 org-table-last-alignment org-table-last-column-widths
3476 (if (not (fboundp func
))
3477 (error "Cannot export orgtbl table to %s" target
))
3478 (setq lines
(org-table-clean-before-export lines
))
3482 (if (string-match org-table-hline-regexp x
)
3484 (org-split-string (org-trim x
) "\\s-*|\\s-*")))
3486 (setq maxcol
(apply 'max
(mapcar (lambda (x) (if (listp x
) (length x
) 0))
3488 (loop for i from
(1- maxcol
) downto
0 do
3489 (setq column
(mapcar (lambda (x) (if (listp x
) (nth i x
) nil
)) table
))
3490 (setq column
(delq nil column
))
3491 (push (apply 'max
(mapcar 'string-width column
)) org-table-last-column-widths
)
3492 (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
))
3493 (funcall func table nil
)))
3495 (defun orgtbl-gather-send-defs ()
3496 "Gathers a plist of :name, :transform, :params for each destination before
3499 (goto-char (org-table-begin))
3501 (beginning-of-line 0)
3502 (while (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
3503 (let ((name (org-no-properties (match-string 1)))
3504 (transform (intern (match-string 2)))
3505 (params (if (match-end 3)
3506 (read (concat "(" (match-string 3) ")")))))
3507 (push (list :name name
:transform transform
:params params
)
3509 (beginning-of-line 0)))
3512 (defun orgtbl-send-replace-tbl (name txt
)
3513 "Find and replace table NAME with TXT."
3515 (goto-char (point-min))
3516 (unless (re-search-forward
3517 (concat "BEGIN RECEIVE ORGTBL +" name
"\\([ \t]\\|$\\)") nil t
)
3518 (error "Don't know where to insert translated table"))
3519 (goto-char (match-beginning 0))
3520 (beginning-of-line 2)
3522 (let ((beg (point)))
3523 (unless (re-search-forward
3524 (concat "END RECEIVE ORGTBL +" name
) nil t
)
3525 (error "Cannot find end of insertion region"))
3526 (beginning-of-line 1)
3527 (delete-region beg
(point))))
3530 (defun orgtbl-send-table (&optional maybe
)
3531 "Send a tranformed version of this table to the receiver position.
3532 With argument MAYBE, fail quietly if no transformation is defined for
3536 (unless (org-at-table-p) (error "Not at a table"))
3537 ;; when non-interactive, we assume align has just happened.
3538 (when (interactive-p) (org-table-align))
3539 (let ((dests (orgtbl-gather-send-defs))
3540 (txt (buffer-substring-no-properties (org-table-begin)
3543 (unless dests
(if maybe
(throw 'exit nil
)
3544 (error "Don't know how to transform this table.")))
3545 (dolist (dest dests
)
3546 (let* ((name (plist-get dest
:name
))
3547 (transform (plist-get dest
:transform
))
3548 (params (plist-get dest
:params
))
3549 (skip (plist-get params
:skip
))
3550 (skipcols (plist-get params
:skipcols
))
3552 (lines (org-table-clean-before-export
3554 (org-split-string txt
"[ \t]*\n[ \t]*"))))
3555 (i0 (if org-table-clean-did-remove-column
2 1))
3558 (if (string-match org-table-hline-regexp x
)
3560 (org-remove-by-index
3561 (org-split-string (org-trim x
) "\\s-*|\\s-*")
3564 (fun (if (= i0
2) 'cdr
'identity
))
3565 (org-table-last-alignment
3566 (org-remove-by-index (funcall fun org-table-last-alignment
)
3568 (org-table-last-column-widths
3569 (org-remove-by-index (funcall fun org-table-last-column-widths
)
3571 (txt (if (fboundp transform
)
3572 (funcall transform table params
)
3573 (error "No such transformation function %s" transform
))))
3574 (orgtbl-send-replace-tbl name txt
))
3575 (setq ntbl
(1+ ntbl
)))
3576 (message "Table converted and installed at %d receiver location%s"
3577 ntbl
(if (> ntbl
1) "s" "")))))
3579 (defun org-remove-by-index (list indices
&optional i0
)
3580 "Remove the elements in LIST with indices in INDICES.
3581 First element has index 0, or I0 if given."
3584 (if (integerp indices
) (setq indices
(list indices
)))
3585 (setq i0
(1- (or i0
0)))
3586 (delq :rm
(mapcar (lambda (x)
3588 (if (memq i0 indices
) :rm x
))
3591 (defun orgtbl-toggle-comment ()
3592 "Comment or uncomment the orgtbl at point."
3594 (let* ((re1 (concat "^" (regexp-quote comment-start
) orgtbl-line-start-regexp
))
3595 (re2 (concat "^" orgtbl-line-start-regexp
))
3596 (commented (save-excursion (beginning-of-line 1)
3597 (cond ((looking-at re1
) t
)
3598 ((looking-at re2
) nil
)
3599 (t (error "Not at an org table")))))
3600 (re (if commented re1 re2
))
3603 (beginning-of-line 1)
3604 (while (looking-at re
) (beginning-of-line 0))
3605 (beginning-of-line 2)
3607 (while (looking-at re
) (beginning-of-line 2))
3609 (comment-region beg end
(if commented
'(4) nil
))))
3611 (defun orgtbl-insert-radio-table ()
3612 "Insert a radio table template appropriate for this major mode."
3614 (let* ((e (assq major-mode orgtbl-radio-table-templates
))
3617 (unless e
(error "No radio table setup defined for %s" major-mode
))
3618 (setq name
(read-string "Table name: "))
3619 (while (string-match "%n" txt
)
3620 (setq txt
(replace-match name t t txt
)))
3621 (or (bolp) (insert "\n"))
3626 ;; Dynamically bound input and output for table formatting.
3627 (defvar *orgtbl-table
* nil
3628 "Carries the current table through formatting routines.")
3629 (defvar *orgtbl-rtn
* nil
3630 "Formatting routines push the output lines here.")
3631 ;; Formatting parameters for the current table section.
3632 (defvar *orgtbl-hline
* nil
"Text used for horizontal lines")
3633 (defvar *orgtbl-sep
* nil
"Text used as a column separator")
3634 (defvar *orgtbl-fmt
* nil
"Format for each entry")
3635 (defvar *orgtbl-efmt
* nil
"Format for numbers")
3636 (defvar *orgtbl-lfmt
* nil
"Format for an entire line, overrides fmt")
3637 (defvar *orgtbl-llfmt
* nil
"Specializes lfmt for the last row")
3638 (defvar *orgtbl-lstart
* nil
"Text starting a row")
3639 (defvar *orgtbl-llstart
* nil
"Specializes lstart for the last row")
3640 (defvar *orgtbl-lend
* nil
"Text ending a row")
3641 (defvar *orgtbl-llend
* nil
"Specializes lend for the last row")
3643 (defsubst orgtbl-get-fmt
(fmt i
)
3644 "Retrieve the format from FMT corresponding to the Ith column."
3645 (if (and (not (functionp fmt
)) (consp fmt
))
3649 (defsubst orgtbl-apply-fmt
(fmt &rest args
)
3650 "Apply format FMT to the arguments. NIL FMTs return the first argument."
3651 (cond ((functionp fmt
) (apply fmt args
))
3652 (fmt (apply 'format fmt args
))
3656 (defsubst orgtbl-eval-str
(str)
3657 "If STR is a function, evaluate it with no arguments."
3662 (defun orgtbl-format-line (line)
3663 "Format LINE as a table row."
3664 (if (eq line
'hline
) (if *orgtbl-hline
* (push *orgtbl-hline
* *orgtbl-rtn
*))
3670 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt
* i
))
3671 (f (if (and efmt
(string-match orgtbl-exp-regexp f
))
3672 (orgtbl-apply-fmt efmt
(match-string 1 f
)
3675 (orgtbl-apply-fmt (orgtbl-get-fmt *orgtbl-fmt
* i
) f
)))
3677 (push (if *orgtbl-lfmt
*
3678 (orgtbl-apply-fmt *orgtbl-lfmt
* line
)
3679 (concat (orgtbl-eval-str *orgtbl-lstart
*)
3680 (mapconcat 'identity line
*orgtbl-sep
*)
3681 (orgtbl-eval-str *orgtbl-lend
*)))
3684 (defun orgtbl-format-section (section-stopper)
3685 "Format lines until the first occurrence of SECTION-STOPPER."
3688 (while (not (eq (car *orgtbl-table
*) section-stopper
))
3689 (if prevline
(orgtbl-format-line prevline
))
3690 (setq prevline
(pop *orgtbl-table
*)))
3691 (if prevline
(let ((*orgtbl-lstart
* *orgtbl-llstart
*)
3692 (*orgtbl-lend
* *orgtbl-llend
*)
3693 (*orgtbl-lfmt
* *orgtbl-llfmt
*))
3694 (orgtbl-format-line prevline
))))))
3696 (defun orgtbl-to-generic (table params
)
3697 "Convert the orgtbl-mode TABLE to some other format.
3698 This generic routine can be used for many standard cases.
3699 TABLE is a list, each entry either the symbol `hline' for a horizontal
3700 separator line, or a list of fields for that line.
3701 PARAMS is a property list of parameters that can influence the conversion.
3702 For the generic converter, some parameters are obligatory: You need to
3703 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
3704 :splice, you must have :tstart and :tend.
3706 Valid parameters are
3708 :splice When set to t, return only table body lines, don't wrap
3709 them into :tstart and :tend. Default is nil.
3711 :hline String to be inserted on horizontal separation lines.
3712 May be nil to ignore hlines.
3714 :sep Separator between two fields
3715 :remove-nil-lines Do not include lines that evaluate to nil.
3718 Each in the following group may be either a string or a function
3719 of no arguments returning a string:
3720 :tstart String to start the table. Ignored when :splice is t.
3721 :tend String to end the table. Ignored when :splice is t.
3722 :lstart String to start a new table line.
3723 :llstart String to start the last table line, defaults to :lstart.
3724 :lend String to end a table line
3725 :llend String to end the last table line, defaults to :lend.
3727 Each in the following group may be a string, a function of one
3728 argument (the field or line) returning a string, or a plist
3729 mapping columns to either of the above:
3730 :lfmt Format for entire line, with enough %s to capture all fields.
3731 If this is present, :lstart, :lend, and :sep are ignored.
3732 :llfmt Format for the entire last line, defaults to :lfmt.
3733 :fmt A format to be used to wrap the field, should contain
3734 %s for the original field value. For example, to wrap
3735 everything in dollars, you could use :fmt \"$%s$\".
3736 This may also be a property list with column numbers and
3737 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
3739 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
3740 Same as above, specific for the header lines in the table.
3741 All lines before the first hline are treated as header.
3742 If any of these is not present, the data line value is used.
3744 This may be either a string or a function of two arguments:
3745 :efmt Use this format to print numbers with exponentials.
3746 The format should have %s twice for inserting mantissa
3747 and exponent, for example \"%s\\\\times10^{%s}\". This
3748 may also be a property list with column numbers and
3749 formats. :fmt will still be applied after :efmt.
3751 In addition to this, the parameters :skip and :skipcols are always handled
3752 directly by `orgtbl-send-table'. See manual."
3755 (let* ((splicep (plist-get params
:splice
))
3756 (hline (plist-get params
:hline
))
3757 (remove-nil-linesp (plist-get params
:remove-nil-lines
))
3758 (*orgtbl-hline
* hline
)
3759 (*orgtbl-table
* table
)
3760 (*orgtbl-sep
* (plist-get params
:sep
))
3761 (*orgtbl-efmt
* (plist-get params
:efmt
))
3762 (*orgtbl-lstart
* (plist-get params
:lstart
))
3763 (*orgtbl-llstart
* (or (plist-get params
:llstart
) *orgtbl-lstart
*))
3764 (*orgtbl-lend
* (plist-get params
:lend
))
3765 (*orgtbl-llend
* (or (plist-get params
:llend
) *orgtbl-lend
*))
3766 (*orgtbl-lfmt
* (plist-get params
:lfmt
))
3767 (*orgtbl-llfmt
* (or (plist-get params
:llfmt
) *orgtbl-lfmt
*))
3768 (*orgtbl-fmt
* (plist-get params
:fmt
))
3773 (push (or (orgtbl-eval-str (plist-get params
:tstart
))
3774 "ERROR: no :tstart") *orgtbl-rtn
*))
3776 ;; Do we have a heading section? If so, format it and handle the
3778 (if (and (not splicep
) (listp (car *orgtbl-table
*))
3779 (memq 'hline
*orgtbl-table
*))
3781 (let* ((*orgtbl-lstart
* (or (plist-get params
:hlstart
)
3783 (*orgtbl-llstart
* (or (plist-get params
:hllstart
)
3785 (*orgtbl-lend
* (or (plist-get params
:hlend
) *orgtbl-lend
*))
3786 (*orgtbl-llend
* (or (plist-get params
:hllend
)
3787 (plist-get params
:hlend
) *orgtbl-llend
*))
3788 (*orgtbl-lfmt
* (or (plist-get params
:hlfmt
) *orgtbl-lfmt
*))
3789 (*orgtbl-llfmt
* (or (plist-get params
:hllfmt
)
3790 (plist-get params
:hlfmt
) *orgtbl-llfmt
*))
3791 (*orgtbl-sep
* (or (plist-get params
:hlsep
) *orgtbl-sep
*))
3792 (*orgtbl-fmt
* (or (plist-get params
:hfmt
) *orgtbl-fmt
*)))
3793 (orgtbl-format-section 'hline
))
3794 (if hline
(push hline
*orgtbl-rtn
*))
3795 (pop *orgtbl-table
*)))
3797 ;; Now format the main section.
3798 (orgtbl-format-section nil
)
3801 (push (or (orgtbl-eval-str (plist-get params
:tend
))
3802 "ERROR: no :tend") *orgtbl-rtn
*))
3804 (mapconcat 'identity
(nreverse (if remove-nil-linesp
3805 (remq nil
*orgtbl-rtn
*)
3806 *orgtbl-rtn
*)) "\n")))
3808 (defun orgtbl-to-latex (table params
)
3809 "Convert the orgtbl-mode TABLE to LaTeX.
3810 TABLE is a list, each entry either the symbol `hline' for a horizontal
3811 separator line, or a list of fields for that line.
3812 PARAMS is a property list of parameters that can influence the conversion.
3813 Supports all parameters from `orgtbl-to-generic'. Most important for
3816 :splice When set to t, return only table body lines, don't wrap
3817 them into a tabular environment. Default is nil.
3819 :fmt A format to be used to wrap the field, should contain %s for the
3820 original field value. For example, to wrap everything in dollars,
3821 use :fmt \"$%s$\". This may also be a property list with column
3822 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
3823 The format may also be a function that formats its one argument.
3825 :efmt Format for transforming numbers with exponentials. The format
3826 should have %s twice for inserting mantissa and exponent, for
3827 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
3828 This may also be a property list with column numbers and formats.
3829 The format may also be a function that formats its two arguments.
3831 :llend If you find too much space below the last line of a table,
3832 pass a value of \"\" for :llend to suppress the final \\\\.
3834 The general parameters :skip and :skipcols have already been applied when
3835 this function is called."
3836 (let* ((alignment (mapconcat (lambda (x) (if x
"r" "l"))
3837 org-table-last-alignment
""))
3840 :tstart
(concat "\\begin{tabular}{" alignment
"}")
3841 :tend
"\\end{tabular}"
3842 :lstart
"" :lend
" \\\\" :sep
" & "
3843 :efmt
"%s\\,(%s)" :hline
"\\hline")))
3844 (orgtbl-to-generic table
(org-combine-plists params2 params
))))
3846 (defun orgtbl-to-html (table params
)
3847 "Convert the orgtbl-mode TABLE to LaTeX.
3848 TABLE is a list, each entry either the symbol `hline' for a horizontal
3849 separator line, or a list of fields for that line.
3850 PARAMS is a property list of parameters that can influence the conversion.
3851 Currently this function recognizes the following parameters:
3853 :splice When set to t, return only table body lines, don't wrap
3854 them into a <table> environment. Default is nil.
3856 The general parameters :skip and :skipcols have already been applied when
3857 this function is called. The function does *not* use `orgtbl-to-generic',
3858 so you cannot specify parameters for it."
3859 (let* ((splicep (plist-get params
:splice
))
3861 ;; Just call the formatter we already have
3862 ;; We need to make text lines for it, so put the fields back together.
3863 (setq html
(org-format-org-table-html
3868 (concat "| " (mapconcat 'identity x
" | ") " |")))
3871 (if (string-match "\n+\\'" html
)
3872 (setq html
(replace-match "" t t html
)))
3875 (defun orgtbl-to-texinfo (table params
)
3876 "Convert the orgtbl-mode TABLE to TeXInfo.
3877 TABLE is a list, each entry either the symbol `hline' for a horizontal
3878 separator line, or a list of fields for that line.
3879 PARAMS is a property list of parameters that can influence the conversion.
3880 Supports all parameters from `orgtbl-to-generic'. Most important for
3883 :splice nil/t When set to t, return only table body lines, don't wrap
3884 them into a multitable environment. Default is nil.
3886 :fmt fmt A format to be used to wrap the field, should contain
3887 %s for the original field value. For example, to wrap
3888 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
3889 This may also be a property list with column numbers and
3890 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
3891 Each format also may be a function that formats its one
3894 :cf \"f1 f2..\" The column fractions for the table. By default these
3895 are computed automatically from the width of the columns
3898 The general parameters :skip and :skipcols have already been applied when
3899 this function is called."
3900 (let* ((total (float (apply '+ org-table-last-column-widths
)))
3901 (colfrac (or (plist-get params
:cf
)
3903 (lambda (x) (format "%.3f" (/ (float x
) total
)))
3904 org-table-last-column-widths
" ")))
3907 :tstart
(concat "@multitable @columnfractions " colfrac
)
3908 :tend
"@end multitable"
3909 :lstart
"@item " :lend
"" :sep
" @tab "
3910 :hlstart
"@headitem ")))
3911 (orgtbl-to-generic table
(org-combine-plists params2 params
))))
3913 (provide 'org-table
)
3915 ;;; org-table.el ends here