1 ;;; org-table.el --- The table editor for Org-mode
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
29 ;; This file contains the table editor and spreadsheet for Org-mode.
31 ;; Watch out: Here we are talking about two different kind of tables.
32 ;; Most of the code is for the tables created with the Org-mode table editor.
33 ;; Sometimes, we talk about tables created and edited with the table.el
34 ;; Emacs package. We call the former org-type tables, and the latter
35 ;; table.el-type tables.
43 (declare-function org-table-clean-before-export
"org-exp"
44 (lines &optional maybe-quoted
))
45 (declare-function org-format-org-table-html
"org-html" (lines &optional splice
))
46 (defvar orgtbl-mode
) ; defined below
47 (defvar orgtbl-mode-menu
) ; defined when orgtbl mode get initialized
48 (defvar org-export-html-table-tag
) ; defined in org-exp.el
49 (defvar constants-unit-system
)
51 (defvar orgtbl-after-send-table-hook nil
52 "Hook for functions attaching to `C-c C-c', if the table is sent.
53 This can be used to add additional functionality after the table is sent
54 to the receiver position, othewise, if table is not sent, the functions
57 (defcustom orgtbl-optimized
(eq org-enable-table-editor
'optimized
)
58 "Non-nil means use the optimized table editor version for `orgtbl-mode'.
59 In the optimized version, the table editor takes over all simple keys that
60 normally just insert a character. In tables, the characters are inserted
61 in a way to minimize disturbing the table structure (i.e. in overwrite mode
62 for empty fields). Outside tables, the correct binding of the keys is
65 The default for this option is t if the optimized version is also used in
66 Org-mode. See the variable `org-enable-table-editor' for details. Changing
67 this variable requires a restart of Emacs to become effective."
71 (defcustom orgtbl-radio-table-templates
72 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
73 % END RECEIVE ORGTBL %n
75 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
78 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
79 @c END RECEIVE ORGTBL %n
81 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
84 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
85 <!-- END RECEIVE ORGTBL %n -->
87 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
90 "Templates for radio tables in different major modes.
91 All occurrences of %n in a template will be replaced with the name of the
92 table, obtained by prompting the user."
95 (list (symbol :tag
"Major mode")
96 (string :tag
"Format"))))
98 (defgroup org-table-settings nil
99 "Settings for tables in Org-mode."
100 :tag
"Org Table Settings"
103 (defcustom org-table-default-size
"5x2"
104 "The default size for newly created tables, Columns x Rows."
105 :group
'org-table-settings
108 (defcustom org-table-number-regexp
109 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
110 "Regular expression for recognizing numbers in table columns.
111 If a table column contains mostly numbers, it will be aligned to the
112 right. If not, it will be aligned to the left.
114 The default value of this option is a regular expression which allows
115 anything which looks remotely like a number as used in scientific
116 context. For example, all of the following will be considered a
118 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
120 Other options offered by the customize interface are more restrictive."
121 :group
'org-table-settings
123 (const :tag
"Positive Integers"
125 (const :tag
"Integers"
127 (const :tag
"Floating Point Numbers"
128 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
129 (const :tag
"Floating Point Number or Integer"
130 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
131 (const :tag
"Exponential, Floating point, Integer"
132 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
133 (const :tag
"Very General Number-Like, including hex"
134 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
135 (string :tag
"Regexp:")))
137 (defcustom org-table-number-fraction
0.5
138 "Fraction of numbers in a column required to make the column align right.
139 In a column all non-white fields are considered. If at least this
140 fraction of fields is matched by `org-table-number-fraction',
141 alignment to the right border applies."
142 :group
'org-table-settings
145 (defgroup org-table-editing nil
146 "Behavior of tables during editing in Org-mode."
147 :tag
"Org Table Editing"
150 (defcustom org-table-automatic-realign t
151 "Non-nil means automatically re-align table when pressing TAB or RETURN.
152 When nil, aligning is only done with \\[org-table-align], or after column
154 :group
'org-table-editing
157 (defcustom org-table-auto-blank-field t
158 "Non-nil means automatically blank table field when starting to type into it.
159 This only happens when typing immediately after a field motion
160 command (TAB, S-TAB or RET).
161 Only relevant when `org-enable-table-editor' is equal to `optimized'."
162 :group
'org-table-editing
165 (defcustom org-table-fix-formulas-confirm nil
166 "Whether the user should confirm when Org fixes formulas."
167 :group
'org-table-editing
169 (const :tag
"with yes-or-no" yes-or-no-p
)
170 (const :tag
"with y-or-n" y-or-n-p
)
171 (const :tag
"no confirmation" nil
)))
172 (put 'org-table-fix-formulas-confirm
174 '(lambda (x) (member x
'(yes-or-no-p y-or-n-p
))))
176 (defcustom org-table-tab-jumps-over-hlines t
177 "Non-nil means tab in the last column of a table with jump over a hline.
178 If a horizontal separator line is following the current line,
179 `org-table-next-field' can either create a new row before that line, or jump
180 over the line. When this option is nil, a new line will be created before
182 :group
'org-table-editing
185 (defgroup org-table-calculation nil
186 "Options concerning tables in Org-mode."
187 :tag
"Org Table Calculation"
190 (defcustom org-table-use-standard-references
'from
191 "Should org-mode work with table references like B3 instead of @3$2?
194 from accept as input, do not present for editing
195 t accept as input and present for editing"
196 :group
'org-table-calculation
198 (const :tag
"Never, don't even check user input for them" nil
)
199 (const :tag
"Always, both as user input, and when editing" t
)
200 (const :tag
"Convert user input, don't offer during editing" from
)))
202 (defcustom org-table-copy-increment t
203 "Non-nil means increment when copying current field with \\[org-table-copy-down]."
204 :group
'org-table-calculation
207 (defcustom org-calc-default-modes
208 '(calc-internal-prec 12
209 calc-float-format
(float 8)
212 calc-symbolic-mode nil
213 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " hh
":" mm
))
214 calc-display-working-message t
216 "List with Calc mode settings for use in `calc-eval' for table formulas.
217 The list must contain alternating symbols (Calc modes variables and values).
218 Don't remove any of the default settings, just change the values. Org-mode
219 relies on the variables to be present in the list."
220 :group
'org-table-calculation
223 (defcustom org-table-formula-evaluate-inline t
224 "Non-nil means TAB and RET evaluate a formula in current table field.
225 If the current field starts with an equal sign, it is assumed to be a formula
226 which should be evaluated as described in the manual and in the documentation
227 string of the command `org-table-eval-formula'. This feature requires the
229 When this variable is nil, formula calculation is only available through
230 the command \\[org-table-eval-formula]."
231 :group
'org-table-calculation
234 (defcustom org-table-formula-use-constants t
235 "Non-nil means interpret constants in formulas in tables.
236 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
237 by the value given in `org-table-formula-constants', or by a value obtained
238 from the `constants.el' package."
239 :group
'org-table-calculation
242 (defcustom org-table-formula-constants nil
243 "Alist with constant names and values, for use in table formulas.
244 The car of each element is a name of a constant, without the `$' before it.
245 The cdr is the value as a string. For example, if you'd like to use the
246 speed of light in a formula, you would configure
248 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
250 and then use it in an equation like `$1*$c'.
252 Constants can also be defined on a per-file basis using a line like
254 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
255 :group
'org-table-calculation
257 (cons (string :tag
"name")
258 (string :tag
"value"))))
260 (defcustom org-table-allow-automatic-line-recalculation t
261 "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
262 Automatically means when TAB or RET or C-c C-c are pressed in the line."
263 :group
'org-table-calculation
266 (defcustom org-table-error-on-row-ref-crossing-hline t
267 "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
271 (defcustom org-table-relative-ref-may-cross-hline t
272 "Non-nil means relative formula references may cross hlines.
273 Here are the allowed values:
275 nil Relative references may not cross hlines. They will reference the
276 field next to the hline instead. Coming from below, the reference
277 will be to the field below the hline. Coming from above, it will be
279 t Relative references may cross hlines.
280 error An attempt to cross a hline will throw an error.
282 It is probably good to never set this variable to nil, for the sake of
283 portability of tables."
284 :group
'org-table-calculation
286 (const :tag
"Allow to cross" t
)
287 (const :tag
"Stick to hline" nil
)
288 (const :tag
"Error on attempt to cross" error
)))
290 (defgroup org-table-import-export nil
291 "Options concerning table import and export in Org-mode."
292 :tag
"Org Table Import Export"
295 (defcustom org-table-export-default-format
"orgtbl-to-tsv"
296 "Default export parameters for `org-table-export'.
297 These can be overridden for a specific table by setting the
298 TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
299 radio tables for the different export transformations and
300 available parameters."
301 :group
'org-table-import-export
304 (defconst org-table-auto-recalculate-regexp
"^[ \t]*| *# *\\(|\\|$\\)"
305 "Detects a table line marked for automatic recalculation.")
306 (defconst org-table-recalculate-regexp
"^[ \t]*| *[#*] *\\(|\\|$\\)"
307 "Detects a table line marked for automatic recalculation.")
308 (defconst org-table-calculate-mark-regexp
"^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
309 "Detects a table line marked for automatic recalculation.")
310 (defconst org-table-border-regexp
"^[ \t]*[^| \t]"
311 "Searching from within a table (any type) this finds the first line outside the table.")
312 (defvar org-table-last-highlighted-reference nil
)
313 (defvar org-table-formula-history nil
)
315 (defvar org-table-column-names nil
316 "Alist with column names, derived from the `!' line.")
317 (defvar org-table-column-name-regexp nil
318 "Regular expression matching the current column names.")
319 (defvar org-table-local-parameters nil
320 "Alist with parameter names, derived from the `$' line.")
321 (defvar org-table-named-field-locations nil
322 "Alist with locations of named fields.")
324 (defvar org-table-current-line-types nil
325 "Table row types, non-nil only for the duration of a command.")
326 (defvar org-table-current-begin-line nil
327 "Table begin line, non-nil only for the duration of a command.")
328 (defvar org-table-current-begin-pos nil
329 "Table begin position, non-nil only for the duration of a command.")
330 (defvar org-table-current-ncol nil
331 "Number of columns in table, non-nil only for the duration of a command.")
332 (defvar org-table-dlines nil
333 "Vector of data line line numbers in the current table.")
334 (defvar org-table-hlines nil
335 "Vector of hline line numbers in the current table.")
337 (defconst org-table-range-regexp
338 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
340 "Regular expression for matching ranges in formulas.")
342 (defconst org-table-range-regexp2
344 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
346 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
347 "Match a range for reference display.")
349 (defun org-table-colgroup-line-p (line)
350 "Is this a table line colgroup information?"
352 (and (string-match "[<>]\\|&[lg]t;" line
)
353 (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
359 (not (member s
'("" "<" ">" "<>" "<" ">" "<>"))))
360 (org-split-string (match-string 1 line
) "[ \t]*|[ \t]*")))))))
362 (defun org-table-cookie-line-p (line)
363 "Is this a table line with only alignment/width cookies?"
365 (and (string-match "[<>]\\|&[lg]t;" line
)
367 "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line
)
368 (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line
))
369 (not (delq nil
(mapcar
371 (not (or (equal s
"")
373 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s
)
375 "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'"
377 (org-split-string (match-string 1 line
)
378 "[ \t]*|[ \t]*")))))))
380 (defconst org-table-translate-regexp
381 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
382 "Match a reference that needs translation, for reference display.")
384 (defun org-table-create-with-table.el
()
385 "Use the table.el package to insert a new table.
386 If there is already a table at point, convert between Org-mode tables
387 and table.el tables."
392 (if (y-or-n-p "Convert table to Org-mode table? ")
393 (org-table-convert)))
395 (when (y-or-n-p "Convert table to table.el table? ")
397 (org-table-convert)))
398 (t (call-interactively 'table-insert
))))
400 (defun org-table-create-or-convert-from-region (arg)
401 "Convert region to table, or create an empty table.
402 If there is an active region, convert it to a table, using the function
403 `org-table-convert-region'. See the documentation of that function
404 to learn how the prefix argument is interpreted to determine the field
406 If there is no such region, create an empty table with `org-table-create'."
408 (if (org-region-active-p)
409 (org-table-convert-region (region-beginning) (region-end) arg
)
410 (org-table-create arg
)))
412 (defun org-table-create (&optional size
)
413 "Query for a size and insert a table skeleton.
414 SIZE is a string Columns x Rows like for example \"3x2\"."
417 (setq size
(read-string
418 (concat "Table size Columns x Rows [e.g. "
419 org-table-default-size
"]: ")
420 "" nil org-table-default-size
)))
423 (indent (make-string (current-column) ?\
))
424 (split (org-split-string size
" *x *"))
425 (rows (string-to-number (nth 1 split
)))
426 (columns (string-to-number (car split
)))
427 (line (concat (apply 'concat indent
"|" (make-list columns
" |"))
429 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
430 (point-at-bol) (point)))
431 (beginning-of-line 1)
433 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
434 (dotimes (i rows
) (insert line
))
437 ;; Insert a hline after the first row.
444 (defun org-table-convert-region (beg0 end0
&optional separator
)
445 "Convert region to a table.
446 The region goes from BEG0 to END0, but these borders will be moved
447 slightly, to make sure a beginning of line in the first line is included.
449 SEPARATOR specifies the field separator in the lines. It can have the
452 '(4) Use the comma as a field separator
453 '(16) Use a TAB as field separator
454 integer When a number, use that many spaces as field separator
455 nil When nil, the command tries to be smart and figure out the
456 separator in the following way:
457 - when each line contains a TAB, assume TAB-separated material
458 - when each line contains a comma, assume CSV material
459 - else, assume one or more SPACE characters as separator."
461 (let* ((beg (min beg0 end0
))
462 (end (max beg0 end0
))
465 (beginning-of-line 1)
466 (setq beg
(move-marker (make-marker) (point)))
468 (if (bolp) (backward-char 1) (end-of-line 1))
469 (setq end
(move-marker (make-marker) (point)))
470 ;; Get the right field separator
475 ((not (re-search-forward "^[^\n\t]+$" end t
)) '(16))
476 ((not (re-search-forward "^[^\n,]+$" end t
)) '(4))
479 (if (equal separator
'(4))
480 (while (< (point) end
)
481 ;; parse the csv stuff
483 ((looking-at "^") (insert "| "))
484 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
485 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
486 (replace-match "\\1")
487 (if (looking-at "\"") (insert "\"")))
488 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
489 ((looking-at "[ \t]*,") (replace-match " | "))
490 (t (beginning-of-line 2))))
492 ((equal separator
'(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
493 ((equal separator
'(16)) "^\\|\t")
494 ((integerp separator
)
496 (error "Number of spaces in separator must be >= 1")
497 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
)))
498 (t (error "This should not happen"))))
499 (while (re-search-forward re end t
)
500 (replace-match "| " t t
)))
504 (defun org-table-import (file arg
)
505 "Import FILE as a table.
506 The file is assumed to be tab-separated. Such files can be produced by most
507 spreadsheet and database applications. If no tabs (at least one per line)
508 are found, lines will be split on whitespace into fields."
510 (or (bolp) (newline))
513 (insert-file-contents file
)
514 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
517 (defvar org-table-last-alignment
)
518 (defvar org-table-last-column-widths
)
519 (defun org-table-export (&optional file format
)
520 "Export table to a file, with configurable format.
521 Such a file can be imported into a spreadsheet program like Excel.
522 FILE can be the output file name. If not given, it will be taken from
523 a TABLE_EXPORT_FILE property in the current entry or higher up in the
524 hierarchy, or the user will be prompted for a file name.
525 FORMAT can be an export format, of the same kind as it used when
526 `orgtbl-mode' sends a table in a different format. The default format can
527 be found in the variable `org-table-export-default-format', but the function
528 first checks if there is an export format specified in a TABLE_EXPORT_FORMAT
529 property, locally or anywhere up in the hierarchy."
531 (unless (org-at-table-p)
532 (error "No table at point"))
534 (org-table-align) ;; make sure we have everything we need
535 (let* ((beg (org-table-begin))
536 (end (org-table-end))
537 (txt (buffer-substring-no-properties beg end
))
538 (file (or file
(org-entry-get beg
"TABLE_EXPORT_FILE" t
)))
540 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)))
543 (setq file
(read-file-name "Export table to: "))
544 (unless (or (not (file-exists-p file
))
545 (y-or-n-p (format "Overwrite file %s? " file
)))
547 (if (file-directory-p file
)
548 (error "This is a directory path, not a file"))
549 (if (and (buffer-file-name)
550 (equal (file-truename file
)
551 (file-truename (buffer-file-name))))
552 (error "Please specify a file name that is different from current"))
554 (setq deffmt-readable org-table-export-default-format
)
555 (while (string-match "\t" deffmt-readable
)
556 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
557 (while (string-match "\n" deffmt-readable
)
558 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
559 (setq format
(org-completing-read
561 '("orgtbl-to-tsv" "orgtbl-to-csv"
562 "orgtbl-to-latex" "orgtbl-to-html"
563 "orgtbl-to-generic" "orgtbl-to-texinfo"
564 "orgtbl-to-orgtbl") nil nil
566 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
567 (let* ((transform (intern (match-string 1 format
)))
568 (params (if (match-end 2)
569 (read (concat "(" (match-string 2 format
) ")"))))
570 (skip (plist-get params
:skip
))
571 (skipcols (plist-get params
:skipcols
))
572 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
573 (lines (org-table-clean-before-export lines
))
574 (i0 (if org-table-clean-did-remove-column
2 1))
577 (if (string-match org-table-hline-regexp x
)
580 (org-split-string (org-trim x
) "\\s-*|\\s-*")
583 (fun (if (= i0
2) 'cdr
'identity
))
584 (org-table-last-alignment
585 (org-remove-by-index (funcall fun org-table-last-alignment
)
587 (org-table-last-column-widths
588 (org-remove-by-index (funcall fun org-table-last-column-widths
)
591 (unless (fboundp transform
)
592 (error "No such transformation function %s" transform
))
593 (setq txt
(funcall transform table params
))
595 (with-current-buffer (find-file-noselect file
)
596 (setq buf
(current-buffer))
602 (message "Export done."))
603 (error "TABLE_EXPORT_FORMAT invalid"))))
605 (defvar org-table-aligned-begin-marker
(make-marker)
606 "Marker at the beginning of the table last aligned.
607 Used to check if cursor still is in that table, to minimize realignment.")
608 (defvar org-table-aligned-end-marker
(make-marker)
609 "Marker at the end of the table last aligned.
610 Used to check if cursor still is in that table, to minimize realignment.")
611 (defvar org-table-last-alignment nil
612 "List of flags for flushright alignment, from the last re-alignment.
613 This is being used to correctly align a single field after TAB or RET.")
614 (defvar org-table-last-column-widths nil
615 "List of max width of fields in each column.
616 This is being used to correctly align a single field after TAB or RET.")
617 (defvar org-table-formula-debug nil
618 "Non-nil means debug table formulas.
619 When nil, simply write \"#ERROR\" in corrupted fields.")
620 (make-variable-buffer-local 'org-table-formula-debug
)
621 (defvar org-table-overlay-coordinates nil
622 "Overlay coordinates after each align of a table.")
623 (make-variable-buffer-local 'org-table-overlay-coordinates
)
625 (defvar org-last-recalc-line nil
)
626 (defvar org-table-do-narrow t
) ; for dynamic scoping
627 (defconst org-narrow-column-arrow
"=>"
628 "Used as display property in narrowed table columns.")
630 (defun org-table-align ()
631 "Align the table at point by aligning all vertical bars."
635 (beg (org-table-begin))
636 (end (org-table-end))
637 ;; Current cursor position
638 (linepos (org-current-line))
639 (colpos (org-table-current-column))
640 (winstart (window-start))
641 (winstartline (org-current-line (min winstart
(1- (point-max)))))
642 lines
(new "") lengths l typenums ty fields maxfields i
650 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
652 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
653 emptystrings links dates emph raise narrow
654 falign falign1 fmax f1 len c e space
)
656 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
657 ;; Check if we have links or dates
659 (setq links
(re-search-forward org-bracket-link-regexp end t
))
661 (setq emph
(and org-hide-emphasis-markers
662 (re-search-forward org-emph-re end t
)))
664 (setq raise
(and org-use-sub-superscripts
665 (re-search-forward org-match-substring-regexp end t
)))
667 (setq dates
(and org-display-custom-times
668 (re-search-forward org-ts-regexp-both end t
)))
669 ;; Make sure the link properties are right
670 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
671 ;; Make sure the date properties are right
672 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
673 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
674 (when raise
(goto-char beg
) (while (org-raise-scripts end
)))
676 ;; Check if we are narrowing any columns
678 (setq narrow
(and org-table-do-narrow
679 org-format-transports-properties-p
680 (re-search-forward "<[lrc]?[0-9]+>" end t
)))
682 (setq falign
(re-search-forward "<[lrc][0-9]*>" end t
))
685 (setq lines
(org-split-string
686 (buffer-substring beg end
) "\n"))
687 ;; Store the indentation of the first line
688 (if (string-match "^ *" (car lines
))
689 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
690 ;; Mark the hlines by setting the corresponding element to nil
691 ;; At the same time, we remove trailing space.
692 (setq lines
(mapcar (lambda (l)
693 (if (string-match "^ *|-" l
)
695 (if (string-match "[ \t]+$" l
)
696 (substring l
0 (match-beginning 0))
699 ;; Get the data fields by splitting the lines.
702 (org-split-string l
" *| *"))
703 (delq nil
(copy-sequence lines
))))
704 ;; How many fields in the longest line?
706 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
708 (kill-region beg end
)
709 (org-table-create org-table-default-size
)
710 (error "Empty table - created default table")))
711 ;; A list of empty strings to fill any short rows on output
712 (setq emptystrings
(make-list maxfields
""))
713 ;; Check for special formatting.
715 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
716 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
717 ;; Check if there is an explicit width specified
719 (when (or narrow falign
)
720 (setq c column fmax nil falign1 nil
)
723 (when (and (stringp e
) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e
))
724 (if (match-end 1) (setq falign1
(match-string 1 e
)))
725 (if (and org-table-do-narrow
(match-end 2))
726 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
727 ;; Find fields that are wider than fmax, and shorten them
729 (loop for xx in column do
730 (when (and (stringp xx
)
731 (> (org-string-width xx
) fmax
))
732 (org-add-props xx nil
734 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
735 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
737 (error "Cannot narrow field starting with wide link \"%s\""
738 (match-string 0 xx
)))
739 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
740 (add-text-properties (- f1
2) f1
741 (list 'display org-narrow-column-arrow
)
743 ;; Get the maximum width for each column
744 (push (apply 'max
(or fmax
1) 1 (mapcar 'org-string-width column
))
746 ;; Get the fraction of numbers, to decide about alignment of the column
748 (push (equal (downcase falign1
) "r") typenums
)
749 (setq cnt
0 frac
0.0)
750 (loop for x in column do
753 (setq frac
( / (+ (* frac cnt
)
754 (if (string-match org-table-number-regexp x
) 1 0))
755 (setq cnt
(1+ cnt
))))))
756 (push (>= frac org-table-number-fraction
) typenums
)))
757 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
759 ;; Store the alignment of this table, for later editing of single fields
760 (setq org-table-last-alignment typenums
761 org-table-last-column-widths lengths
)
763 ;; With invisible characters, `format' does not get the field width right
764 ;; So we need to make these fields wide by hand.
765 (when (or links emph raise
)
766 (loop for i from
0 upto
(1- maxfields
) do
767 (setq len
(nth i lengths
))
768 (loop for j from
0 upto
(1- (length fields
)) do
769 (setq c
(nthcdr i
(car (nthcdr j fields
))))
770 (if (and (stringp (car c
))
771 (or (text-property-any 0 (length (car c
))
772 'invisible
'org-link
(car c
))
773 (text-property-any 0 (length (car c
))
774 'org-dwidth t
(car c
)))
775 (< (org-string-width (car c
)) len
))
777 (setq space
(make-string (- len
(org-string-width (car c
))) ?\
))
778 (setcar c
(if (nth i typenums
)
779 (concat space
(car c
))
780 (concat (car c
) space
))))))))
782 ;; Compute the formats needed for output of the table
783 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
784 (while (setq l
(pop lengths
))
785 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
786 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
787 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
788 (setq rfmt
(concat rfmt
"\n")
789 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
793 (if l
(apply 'format rfmt
794 (append (pop fields
) emptystrings
))
797 (if (equal (char-before) ?
\n)
798 ;; This hack is for org-indent, to force redisplay of the
799 ;; line prefix of the first line. Apparently the redisplay
800 ;; is tied to the newline, which is, I think, a bug.
801 ;; To force this redisplay, we remove and re-insert the
802 ;; newline, so that the redisplay engine thinks it belongs
803 ;; to the changed text.
805 (backward-delete-char 1)
807 (move-marker org-table-aligned-begin-marker
(point))
809 ;; Replace the old one
810 (delete-region (point) end
)
811 (move-marker end nil
)
812 (move-marker org-table-aligned-end-marker
(point))
813 (when (and orgtbl-mode
(not (org-mode-p)))
814 (goto-char org-table-aligned-begin-marker
)
815 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
816 ;; Try to move to the old location
817 (org-goto-line winstartline
)
818 (setq winstart
(point-at-bol))
819 (org-goto-line linepos
)
820 (set-window-start (selected-window) winstart
'noforce
)
821 (org-table-goto-column colpos
)
822 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
823 (setq org-table-may-need-update nil
)
826 (defun org-table-begin (&optional table-type
)
827 "Find the beginning of the table and return its position.
828 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
830 (if (not (re-search-backward
831 (if table-type org-table-any-border-regexp
832 org-table-border-regexp
)
834 (progn (goto-char (point-min)) (point))
835 (goto-char (match-beginning 0))
836 (beginning-of-line 2)
839 (defun org-table-end (&optional table-type
)
840 "Find the end of the table and return its position.
841 With argument TABLE-TYPE, go to the end of a table.el-type table."
843 (if (not (re-search-forward
844 (if table-type org-table-any-border-regexp
845 org-table-border-regexp
)
847 (goto-char (point-max))
848 (goto-char (match-beginning 0)))
851 (defun org-table-justify-field-maybe (&optional new
)
852 "Justify the current field, text to left, number to right.
853 Optional argument NEW may specify text to replace the current field content."
855 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
856 ((org-at-table-hline-p))
858 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
860 (< (point) org-table-aligned-begin-marker
)
861 (>= (point) org-table-aligned-end-marker
)))
862 ;; This is not the same table, force a full re-align
863 (setq org-table-may-need-update t
))
864 (t ;; realign the current field, based on previous full realign
865 (let* ((pos (point)) s
866 (col (org-table-current-column))
867 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
870 (skip-chars-backward "^|\n")
871 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
873 (setq s
(match-string 1)
875 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
876 e
(not (= (match-beginning 2) (match-end 2))))
877 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
878 l
(if e
"|" (setq org-table-may-need-update t
) ""))
881 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
882 (setq n
(format f new
))
883 (setq n
(concat new
"|") org-table-may-need-update t
)))
884 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
886 (let (org-table-may-need-update)
887 (replace-match n t t
))))
888 (setq org-table-may-need-update t
))
891 (defun org-table-next-field ()
892 "Go to the next field in the current table, creating new lines as needed.
893 Before doing so, re-align the table if necessary."
895 (org-table-maybe-eval-formula)
896 (org-table-maybe-recalculate-line)
897 (if (and org-table-automatic-realign
898 org-table-may-need-update
)
900 (let ((end (org-table-end)))
901 (if (org-at-table-hline-p)
905 (re-search-forward "|" end
)
906 (if (looking-at "[ \t]*$")
907 (re-search-forward "|" end
))
908 (if (and (looking-at "-")
909 org-table-tab-jumps-over-hlines
910 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
911 (goto-char (match-beginning 1)))
914 (beginning-of-line 0)
915 (org-table-insert-row 'below
))
916 (if (looking-at " ") (forward-char 1))))
918 (org-table-insert-row 'below
)))))
920 (defun org-table-previous-field ()
921 "Go to the previous field in the table.
922 Before doing so, re-align the table if necessary."
924 (org-table-justify-field-maybe)
925 (org-table-maybe-recalculate-line)
926 (if (and org-table-automatic-realign
927 org-table-may-need-update
)
929 (if (org-at-table-hline-p)
933 (re-search-backward "|" (org-table-begin))
934 (re-search-backward "|" (org-table-begin)))
935 (error (error "Cannot move to previous table field")))
936 (while (looking-at "|\\(-\\|[ \t]*$\\)")
937 (re-search-backward "|" (org-table-begin)))
938 (if (looking-at "| ?")
939 (goto-char (match-end 0))))
941 (defun org-table-beginning-of-field (&optional n
)
942 "Move to the end of the current table field.
943 If already at or after the end, move to the end of the next table field.
944 With numeric argument N, move N-1 fields forward first."
949 (org-table-previous-field))
950 (if (not (re-search-backward "|" (point-at-bol 0) t
))
951 (error "No more table fields before the current")
952 (goto-char (match-end 0))
953 (and (looking-at " ") (forward-char 1)))
954 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
956 (defun org-table-end-of-field (&optional n
)
957 "Move to the beginning of the current table field.
958 If already at or before the beginning, move to the beginning of the
960 With numeric argument N, move N-1 fields backward first."
965 (org-table-next-field))
966 (when (re-search-forward "|" (point-at-eol 1) t
)
968 (skip-chars-backward " ")
969 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
971 (if (<= (point) pos
) (org-table-end-of-field 2))))
973 (defun org-table-next-row ()
974 "Go to the next row (same column) in the current table.
975 Before doing so, re-align the table if necessary."
977 (org-table-maybe-eval-formula)
978 (org-table-maybe-recalculate-line)
979 (if (or (looking-at "[ \t]*$")
980 (save-excursion (skip-chars-backward " \t") (bolp)))
982 (if (and org-table-automatic-realign
983 org-table-may-need-update
)
985 (let ((col (org-table-current-column)))
986 (beginning-of-line 2)
987 (if (or (not (org-at-table-p))
988 (org-at-table-hline-p))
990 (beginning-of-line 0)
991 (org-table-insert-row 'below
)))
992 (org-table-goto-column col
)
993 (skip-chars-backward "^|\n\r")
994 (if (looking-at " ") (forward-char 1)))))
996 (defun org-table-copy-down (n)
997 "Copy a field down in the current column.
998 If the field at the cursor is empty, copy into it the content of
999 the nearest non-empty field above. With argument N, use the Nth
1000 non-empty field. If the current field is not empty, it is copied
1001 down to the next row, and the cursor is moved with it.
1002 Therefore, repeating this command causes the column to be filled
1004 If the variable `org-table-copy-increment' is non-nil and the
1005 field is an integer or a timestamp, it will be incremented while
1006 copying. In the case of a timestamp, increment by one day."
1008 (let* ((colpos (org-table-current-column))
1009 (col (current-column))
1010 (field (org-table-get-field))
1011 (non-empty (string-match "[^ \t]" field
))
1012 (beg (org-table-begin))
1015 (org-table-check-inside-data-field)
1018 (setq txt
(org-trim field
))
1019 (org-table-next-row)
1020 (org-table-blank-field))
1024 (while (progn (beginning-of-line 1)
1025 (re-search-backward org-table-dataline-regexp
1027 (org-table-goto-column colpos t
)
1028 (if (and (looking-at
1029 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1030 (<= (setq n
(1- n
)) 0))
1031 (throw 'exit
(match-string 1))))))))
1034 (if (and org-table-copy-increment
1035 (not (equal orig-n
0))
1036 (string-match "^[0-9]+$" txt
)
1037 (< (string-to-number txt
) 100000000))
1038 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
1040 (org-move-to-column col
)
1041 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1042 (org-timestamp-up-day)
1043 (org-table-maybe-recalculate-line))
1045 (org-move-to-column col
))
1046 (error "No non-empty field found"))))
1048 (defun org-table-check-inside-data-field ()
1049 "Is point inside a table data field?
1050 I.e. not on a hline or before the first or after the last column?
1051 This actually throws an error, so it aborts the current command."
1052 (if (or (not (org-at-table-p))
1053 (= (org-table-current-column) 0)
1054 (org-at-table-hline-p)
1055 (looking-at "[ \t]*$"))
1056 (error "Not in table data field")))
1058 (defvar org-table-clip nil
1059 "Clipboard for table regions.")
1061 (defun org-table-get (line column
)
1062 "Get the field in table line LINE, column COLUMN.
1063 If LINE is larger than the number of data lines in the table, the function
1064 returns nil. However, if COLUMN is too large, we will simply return an
1066 If LINE is nil, use the current line.
1067 If column is nil, use the current column."
1068 (setq column
(or column
(org-table-current-column)))
1070 (and (or (not line
) (org-table-goto-line line
))
1071 (org-trim (org-table-get-field column
)))))
1073 (defun org-table-put (line column value
&optional align
)
1074 "Put VALUE into line LINE, column COLUMN.
1075 When ALIGN is set, also realign the table."
1076 (setq column
(or column
(org-table-current-column)))
1077 (prog1 (save-excursion
1078 (and (or (not line
) (org-table-goto-line line
))
1079 (progn (org-table-goto-column column nil
'force
) t
)
1080 (org-table-get-field column value
)))
1081 (and align
(org-table-align))))
1083 (defun org-table-current-line ()
1084 "Return the index of the current data line."
1085 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1087 (goto-char (org-table-begin))
1088 (while (and (re-search-forward org-table-dataline-regexp end t
)
1090 (< (point-at-eol) pos
))))
1093 (defun org-table-goto-line (N)
1094 "Go to the Nth data line in the current table.
1095 Return t when the line exists, nil if it does not exist."
1096 (goto-char (org-table-begin))
1097 (let ((end (org-table-end)) (cnt 0))
1098 (while (and (re-search-forward org-table-dataline-regexp end t
)
1099 (< (setq cnt
(1+ cnt
)) N
)))
1102 (defun org-table-blank-field ()
1103 "Blank the current table field or active region."
1105 (org-table-check-inside-data-field)
1106 (if (and (interactive-p) (org-region-active-p))
1107 (let (org-table-clip)
1108 (org-table-cut-region (region-beginning) (region-end)))
1109 (skip-chars-backward "^|")
1111 (if (looking-at "|[^|\n]+")
1112 (let* ((pos (match-beginning 0))
1113 (match (match-string 0))
1114 (len (org-string-width match
)))
1115 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1116 (goto-char (+ 2 pos
))
1117 (substring match
1)))))
1119 (defun org-table-get-field (&optional n replace
)
1120 "Return the value of the field in column N of current row.
1121 N defaults to current field.
1122 If REPLACE is a string, replace field with this value. The return value
1123 is always the old value."
1124 (and n
(org-table-goto-column n
))
1125 (skip-chars-backward "^|\n")
1127 (if (looking-at "|[^|\r\n]*")
1128 (let* ((pos (match-beginning 0))
1129 (val (buffer-substring (1+ pos
) (match-end 0))))
1131 (replace-match (concat "|" replace
) t t
))
1132 (goto-char (min (point-at-eol) (+ 2 pos
)))
1134 (forward-char 1) ""))
1136 (defun org-table-field-info (arg)
1137 "Show info about the current field, and highlight any reference at point."
1139 (org-table-get-specials)
1141 (let* ((pos (point))
1142 (col (org-table-current-column))
1143 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1144 (name (car (rassoc (list (org-current-line) col
)
1145 org-table-named-field-locations
)))
1146 (eql (org-table-expand-lhs-ranges
1149 (cons (org-table-formula-handle-first/last-rc
1151 (org-table-get-stored-formulas))))
1152 (dline (org-table-current-dline))
1153 (ref (format "@%d$%d" dline col
))
1154 (ref1 (org-table-convert-refs-to-an ref
))
1155 (fequation (or (assoc name eql
) (assoc ref eql
)))
1156 (cequation (assoc (int-to-string col
) eql
))
1157 (eqn (or fequation cequation
)))
1158 (if (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))
1159 (setq eqn
(get-text-property 0 :orig-eqn
(car eqn
))))
1162 (org-table-show-reference 'local
)
1164 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1166 (if cname
(concat " or $" cname
) "")
1168 (if name
(concat " or $" name
) "")
1169 ;; FIXME: formula info not correct if special table line
1171 (concat ", formula: "
1172 (org-table-formula-to-user
1174 (if (string-match "^[$@]"(car eqn
)) "" "$")
1175 (car eqn
) "=" (cdr eqn
))))
1178 (defun org-table-current-column ()
1179 "Find out which column we are in."
1181 (if (interactive-p) (org-table-check-inside-data-field))
1183 (let ((cnt 0) (pos (point)))
1184 (beginning-of-line 1)
1185 (while (search-forward "|" pos t
)
1186 (setq cnt
(1+ cnt
)))
1187 (if (interactive-p) (message "In table column %d" cnt
))
1190 (defun org-table-current-dline ()
1191 "Find out what table data line we are in.
1192 Only data lines count for this."
1194 (if (interactive-p) (org-table-check-inside-data-field))
1196 (let ((cnt 0) (pos (point)))
1197 (goto-char (org-table-begin))
1198 (while (<= (point) pos
)
1199 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1200 (beginning-of-line 2))
1201 (if (interactive-p) (message "This is table line %d" cnt
))
1204 (defun org-table-goto-column (n &optional on-delim force
)
1205 "Move the cursor to the Nth column in the current table line.
1206 With optional argument ON-DELIM, stop with point before the left delimiter
1208 If there are less than N fields, just go to after the last delimiter.
1209 However, when FORCE is non-nil, create new columns if necessary."
1211 (beginning-of-line 1)
1213 (while (and (> (setq n
(1- n
)) -
1)
1214 (or (search-forward "|" (point-at-eol) t
)
1216 (progn (end-of-line 1)
1217 (skip-chars-backward "^|")
1220 (when (and force
(not (looking-at ".*|")))
1221 (save-excursion (end-of-line 1) (insert " | ")))
1224 (if (looking-at " ") (forward-char 1)))))
1226 (defun org-table-insert-column ()
1227 "Insert a new column into the table."
1229 (if (not (org-at-table-p))
1230 (error "Not at a table"))
1231 (org-table-find-dataline)
1232 (let* ((col (max 1 (org-table-current-column)))
1233 (beg (org-table-begin))
1234 (end (org-table-end))
1235 ;; Current cursor position
1236 (linepos (org-current-line))
1239 (while (< (point) end
)
1240 (if (org-at-table-hline-p)
1242 (org-table-goto-column col t
)
1244 (beginning-of-line 2))
1245 (move-marker end nil
)
1246 (org-goto-line linepos
)
1247 (org-table-goto-column colpos
)
1249 (when (or (not org-table-fix-formulas-confirm
)
1250 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1251 (org-table-fix-formulas "$" nil
(1- col
) 1)
1252 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1254 (defun org-table-find-dataline ()
1255 "Find a data line in the current table, which is needed for column commands."
1256 (if (and (org-at-table-p)
1257 (not (org-at-table-hline-p)))
1259 (let ((col (current-column))
1260 (end (org-table-end)))
1261 (org-move-to-column col
)
1262 (while (and (< (point) end
)
1263 (or (not (= (current-column) col
))
1264 (org-at-table-hline-p)))
1265 (beginning-of-line 2)
1266 (org-move-to-column col
))
1267 (if (and (org-at-table-p)
1268 (not (org-at-table-hline-p)))
1271 "Please position cursor in a data line for column operations")))))
1273 (defun org-table-line-to-dline (line &optional above
)
1274 "Turn a buffer line number into a data line number.
1275 If there is no data line in this line, return nil.
1276 If there is no matchin dline (most likely te refrence was a hline), the
1277 first dline below it is used. When ABOVE is non-nil, the one above is used."
1279 (let ((ll (length org-table-dlines
))
1285 (if (<= (aref org-table-dlines i
) line
)
1290 (if (>= (aref org-table-dlines i
) line
)
1295 (defun org-table-delete-column ()
1296 "Delete a column from the table."
1298 (if (not (org-at-table-p))
1299 (error "Not at a table"))
1300 (org-table-find-dataline)
1301 (org-table-check-inside-data-field)
1302 (let* ((col (org-table-current-column))
1303 (beg (org-table-begin))
1304 (end (org-table-end))
1305 ;; Current cursor position
1306 (linepos (org-current-line))
1309 (while (< (point) end
)
1310 (if (org-at-table-hline-p)
1312 (org-table-goto-column col t
)
1313 (and (looking-at "|[^|\n]+|")
1314 (replace-match "|")))
1315 (beginning-of-line 2))
1316 (move-marker end nil
)
1317 (org-goto-line linepos
)
1318 (org-table-goto-column colpos
)
1320 (when (or (not org-table-fix-formulas-confirm
)
1321 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1322 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1324 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1327 (defun org-table-move-column-right ()
1328 "Move column to the right."
1330 (org-table-move-column nil
))
1331 (defun org-table-move-column-left ()
1332 "Move column to the left."
1334 (org-table-move-column 'left
))
1336 (defun org-table-move-column (&optional left
)
1337 "Move the current column to the right. With arg LEFT, move to the left."
1339 (if (not (org-at-table-p))
1340 (error "Not at a table"))
1341 (org-table-find-dataline)
1342 (org-table-check-inside-data-field)
1343 (let* ((col (org-table-current-column))
1344 (col1 (if left
(1- col
) col
))
1345 (beg (org-table-begin))
1346 (end (org-table-end))
1347 ;; Current cursor position
1348 (linepos (org-current-line))
1349 (colpos (if left
(1- col
) (1+ col
))))
1350 (if (and left
(= col
1))
1351 (error "Cannot move column further left"))
1352 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1353 (error "Cannot move column further right"))
1355 (while (< (point) end
)
1356 (if (org-at-table-hline-p)
1358 (org-table-goto-column col1 t
)
1359 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1360 (replace-match "|\\2|\\1|")))
1361 (beginning-of-line 2))
1362 (move-marker end nil
)
1363 (org-goto-line linepos
)
1364 (org-table-goto-column colpos
)
1366 (when (or (not org-table-fix-formulas-confirm
)
1367 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1368 (org-table-fix-formulas
1369 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1370 (cons (number-to-string colpos
) (number-to-string col
))))
1371 (org-table-fix-formulas
1372 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1373 (cons (number-to-string colpos
) (number-to-string col
)))))))
1375 (defun org-table-move-row-down ()
1376 "Move table row down."
1378 (org-table-move-row nil
))
1379 (defun org-table-move-row-up ()
1380 "Move table row up."
1382 (org-table-move-row 'up
))
1384 (defun org-table-move-row (&optional up
)
1385 "Move the current table line down. With arg UP, move it up."
1387 (let* ((col (current-column))
1389 (hline1p (save-excursion (beginning-of-line 1)
1390 (looking-at org-table-hline-regexp
)))
1391 (dline1 (org-table-current-dline))
1392 (dline2 (+ dline1
(if up -
1 1)))
1395 (beginning-of-line tonew
)
1396 (unless (org-at-table-p)
1398 (error "Cannot move row further"))
1399 (setq hline2p
(looking-at org-table-hline-regexp
))
1401 (beginning-of-line 1)
1403 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1404 (delete-region (point) (1+ (point-at-eol)))
1405 (beginning-of-line tonew
)
1407 (beginning-of-line 0)
1408 (org-move-to-column col
)
1409 (unless (or hline1p hline2p
1410 (not (or (not org-table-fix-formulas-confirm
)
1411 (funcall org-table-fix-formulas-confirm
1412 "Fix formulas? "))))
1413 (org-table-fix-formulas
1414 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1415 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1417 (defun org-table-insert-row (&optional arg
)
1418 "Insert a new row above the current line into the table.
1419 With prefix ARG, insert below the current line."
1421 (if (not (org-at-table-p))
1422 (error "Not at a table"))
1423 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1424 (new (org-table-clean-line line
)))
1425 ;; Fix the first field if necessary
1426 (if (string-match "^[ \t]*| *[#$] *|" line
)
1427 (setq new
(replace-match (match-string 0 line
) t t new
)))
1428 (beginning-of-line (if arg
2 1))
1429 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1430 (beginning-of-line 0)
1431 (re-search-forward "| ?" (point-at-eol) t
)
1432 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1434 (when (or (not org-table-fix-formulas-confirm
)
1435 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1436 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1438 (defun org-table-insert-hline (&optional above
)
1439 "Insert a horizontal-line below the current line into the table.
1440 With prefix ABOVE, insert above the current line."
1442 (if (not (org-at-table-p))
1443 (error "Not at a table"))
1444 (when (eobp) (insert "\n") (backward-char 1))
1445 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1447 (let ((line (org-table-clean-line
1448 (buffer-substring (point-at-bol) (point-at-eol))))
1449 (col (current-column)))
1450 (while (string-match "|\\( +\\)|" line
)
1451 (setq line
(replace-match
1452 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1453 ?-
) "|") t t line
)))
1454 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1455 (beginning-of-line (if above
1 2))
1457 (beginning-of-line (if above
1 -
1))
1458 (org-move-to-column col
)
1459 (and org-table-overlay-coordinates
(org-table-align))))
1461 (defun org-table-hline-and-move (&optional same-column
)
1462 "Insert a hline and move to the row below that line."
1464 (let ((col (org-table-current-column)))
1465 (org-table-maybe-eval-formula)
1466 (org-table-maybe-recalculate-line)
1467 (org-table-insert-hline)
1469 (if (looking-at "\n[ \t]*|-")
1470 (progn (insert "\n|") (org-table-align))
1471 (org-table-next-field))
1472 (if same-column
(org-table-goto-column col
))))
1474 (defun org-table-clean-line (s)
1475 "Convert a table line S into a string with only \"|\" and space.
1476 In particular, this does handle wide and invisible characters."
1477 (if (string-match "^[ \t]*|-" s
)
1478 ;; It's a hline, just map the characters
1479 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1480 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1481 (setq s
(replace-match
1482 (concat "|" (make-string (org-string-width (match-string 1 s
))
1487 (defun org-table-kill-row ()
1488 "Delete the current row or horizontal line from the table."
1490 (if (not (org-at-table-p))
1491 (error "Not at a table"))
1492 (let ((col (current-column))
1493 (dline (org-table-current-dline)))
1494 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1495 (if (not (org-at-table-p)) (beginning-of-line 0))
1496 (org-move-to-column col
)
1497 (when (or (not org-table-fix-formulas-confirm
)
1498 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1499 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1502 (defun org-table-sort-lines (with-case &optional sorting-type
)
1503 "Sort table lines according to the column at point.
1505 The position of point indicates the column to be used for
1506 sorting, and the range of lines is the range between the nearest
1507 horizontal separator lines, or the entire table of no such lines
1508 exist. If point is before the first column, you will be prompted
1509 for the sorting column. If there is an active region, the mark
1510 specifies the first line and the sorting column, while point
1511 should be in the last line to be included into the sorting.
1513 The command then prompts for the sorting type which can be
1514 alphabetically, numerically, or by time (as given in a time stamp
1515 in the field). Sorting in reverse order is also possible.
1517 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1519 If SORTING-TYPE is specified when this function is called from a Lisp
1520 program, no prompting will take place. SORTING-TYPE must be a character,
1521 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1522 should be done in reverse order."
1524 (let* ((thisline (org-current-line))
1525 (thiscol (org-table-current-column))
1526 beg end bcol ecol tend tbeg column lns pos
)
1527 (when (equal thiscol
0)
1531 (read-string "Use column N for sorting: ")))
1533 (org-table-goto-column thiscol
))
1534 (org-table-check-inside-data-field)
1535 (if (org-region-active-p)
1537 (setq beg
(region-beginning) end
(region-end))
1539 (setq column
(org-table-current-column)
1542 (setq end
(point-at-bol 2)))
1543 (setq column
(org-table-current-column)
1545 tbeg
(org-table-begin)
1546 tend
(org-table-end))
1547 (if (re-search-backward org-table-hline-regexp tbeg t
)
1548 (setq beg
(point-at-bol 2))
1550 (setq beg
(point-at-bol 1)))
1552 (if (re-search-forward org-table-hline-regexp tend t
)
1553 (setq end
(point-at-bol 1))
1555 (setq end
(point-at-bol))))
1556 (setq beg
(move-marker (make-marker) beg
)
1557 end
(move-marker (make-marker) end
))
1560 (org-table-goto-column column
)
1561 (skip-chars-backward "^|")
1562 (setq bcol
(current-column))
1563 (org-table-goto-column (1+ column
))
1564 (skip-chars-backward "^|")
1565 (setq ecol
(1- (current-column)))
1566 (org-table-goto-column column
)
1567 (setq lns
(mapcar (lambda(x) (cons
1568 (org-sort-remove-invisible
1570 (org-split-string x
"[ \t]*|[ \t]*")))
1572 (org-split-string (buffer-substring beg end
) "\n")))
1573 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1574 (delete-region beg end
)
1575 (move-marker beg nil
)
1576 (move-marker end nil
)
1577 (insert (mapconcat 'cdr lns
"\n") "\n")
1578 (org-goto-line thisline
)
1579 (org-table-goto-column thiscol
)
1580 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1583 (defun org-table-cut-region (beg end
)
1584 "Copy region in table to the clipboard and blank all relevant fields.
1585 If there is no active region, use just the field at point."
1587 (if (org-region-active-p) (region-beginning) (point))
1588 (if (org-region-active-p) (region-end) (point))))
1589 (org-table-copy-region beg end
'cut
))
1591 (defun org-table-copy-region (beg end
&optional cut
)
1592 "Copy rectangular region in table to clipboard.
1593 A special clipboard is used which can only be accessed
1594 with `org-table-paste-rectangle'."
1596 (if (org-region-active-p) (region-beginning) (point))
1597 (if (org-region-active-p) (region-end) (point))
1598 current-prefix-arg
))
1599 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1601 (rpl (if cut
" " nil
)))
1603 (org-table-check-inside-data-field)
1604 (setq l01
(org-current-line)
1605 c01
(org-table-current-column))
1607 (org-table-check-inside-data-field)
1608 (setq l02
(org-current-line)
1609 c02
(org-table-current-column))
1610 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1611 c1
(min c01 c02
) c2
(max c01 c02
))
1615 (if (> l1 l2
) (throw 'exit t
))
1617 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1618 (setq cols nil ic1 c1 ic2 c2
)
1619 (while (< ic1
(1+ ic2
))
1620 (push (org-table-get-field ic1 rpl
) cols
)
1621 (setq ic1
(1+ ic1
)))
1622 (push (nreverse cols
) region
)
1623 (setq l1
(1+ l1
)))))
1624 (setq org-table-clip
(nreverse region
))
1625 (if cut
(org-table-align))
1628 (defun org-table-paste-rectangle ()
1629 "Paste a rectangular region into a table.
1630 The upper right corner ends up in the current field. All involved fields
1631 will be overwritten. If the rectangle does not fit into the present table,
1632 the table is enlarged as needed. The process ignores horizontal separator
1635 (unless (and org-table-clip
(listp org-table-clip
))
1636 (error "First cut/copy a region to paste!"))
1637 (org-table-check-inside-data-field)
1638 (let* ((clip org-table-clip
)
1639 (line (org-current-line))
1640 (col (org-table-current-column))
1641 (org-enable-table-editor t
)
1642 (org-table-automatic-realign nil
)
1644 (while (setq cols
(pop clip
))
1645 (while (org-at-table-hline-p) (beginning-of-line 2))
1646 (if (not (org-at-table-p))
1647 (progn (end-of-line 0) (org-table-next-field)))
1649 (while (setq field
(pop cols
))
1650 (org-table-goto-column c nil
'force
)
1651 (org-table-get-field nil field
)
1653 (beginning-of-line 2))
1654 (org-goto-line line
)
1655 (org-table-goto-column col
)
1658 (defun org-table-convert ()
1659 "Convert from `org-mode' table to table.el and back.
1660 Obviously, this only works within limits. When an Org-mode table is
1661 converted to table.el, all horizontal separator lines get lost, because
1662 table.el uses these as cell boundaries and has no notion of horizontal lines.
1663 A table.el table can be converted to an Org-mode table only if it does not
1664 do row or column spanning. Multiline cells will become multiple cells.
1665 Beware, Org-mode does not test if the table can be successfully converted - it
1666 blindly applies a recipe that works for simple tables."
1669 (if (org-at-table.el-p
)
1670 ;; convert to Org-mode table
1671 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1672 (end (move-marker (make-marker) (org-table-end t
))))
1673 (table-unrecognize-region beg end
)
1675 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1678 (if (org-at-table-p)
1679 ;; convert to table.el table
1680 (let ((beg (move-marker (make-marker) (org-table-begin)))
1681 (end (move-marker (make-marker) (org-table-end))))
1682 ;; first, get rid of all horizontal lines
1684 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1686 ;; insert a hline before first
1688 (org-table-insert-hline 'above
)
1689 (beginning-of-line -
1)
1690 ;; insert a hline after each line
1691 (while (progn (beginning-of-line 3) (< (point) end
))
1692 (org-table-insert-hline))
1694 (setq end
(move-marker end
(org-table-end)))
1695 ;; replace "+" at beginning and ending of hlines
1696 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1697 (replace-match "\\1+-"))
1699 (while (re-search-forward "-|[ \t]*$" end t
)
1700 (replace-match "-+"))
1703 (defun org-table-wrap-region (arg)
1704 "Wrap several fields in a column like a paragraph.
1705 This is useful if you'd like to spread the contents of a field over several
1706 lines, in order to keep the table compact.
1708 If there is an active region, and both point and mark are in the same column,
1709 the text in the column is wrapped to minimum width for the given number of
1710 lines. Generally, this makes the table more compact. A prefix ARG may be
1711 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1712 formats the selected text to two lines. If the region was longer than two
1713 lines, the remaining lines remain empty. A negative prefix argument reduces
1714 the current number of lines by that amount. The wrapped text is pasted back
1715 into the table. If you formatted it to more lines than it was before, fields
1716 further down in the table get overwritten - so you might need to make space in
1719 If there is no region, the current field is split at the cursor position and
1720 the text fragment to the right of the cursor is prepended to the field one
1723 If there is no region, but you specify a prefix ARG, the current field gets
1724 blank, and the content is appended to the field above."
1726 (org-table-check-inside-data-field)
1727 (if (org-region-active-p)
1728 ;; There is a region: fill as a paragraph
1729 (let* ((beg (region-beginning))
1730 (cline (save-excursion (goto-char beg
) (org-current-line)))
1731 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1733 (org-table-cut-region (region-beginning) (region-end))
1734 (if (> (length (car org-table-clip
)) 1)
1735 (error "Region must be limited to single column"))
1736 (setq nlines
(if arg
1738 (+ (length org-table-clip
) arg
)
1740 (length org-table-clip
)))
1741 (setq org-table-clip
1742 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1744 (org-goto-line cline
)
1745 (org-table-goto-column ccol
)
1746 (org-table-paste-rectangle))
1747 ;; No region, split the current field at point
1748 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1749 (skip-chars-forward "^\r\n|"))
1751 ;; combine with field above
1752 (let ((s (org-table-blank-field))
1753 (col (org-table-current-column)))
1754 (beginning-of-line 0)
1755 (while (org-at-table-hline-p) (beginning-of-line 0))
1756 (org-table-goto-column col
)
1757 (skip-chars-forward "^|")
1758 (skip-chars-backward " ")
1759 (insert " " (org-trim s
))
1762 (if (looking-at "\\([^|]+\\)+|")
1763 (let ((s (match-string 1)))
1764 (replace-match " |")
1765 (goto-char (match-beginning 0))
1766 (org-table-next-row)
1767 (insert (org-trim s
) " ")
1769 (org-table-next-row)))))
1771 (defvar org-field-marker nil
)
1773 (defun org-table-edit-field (arg)
1774 "Edit table field in a different window.
1775 This is mainly useful for fields that contain hidden parts.
1776 When called with a \\[universal-argument] prefix, just make the full field visible so that
1777 it can be edited in place."
1780 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1781 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1782 (remove-text-properties b e
'(org-cwidth t invisible t
1783 display t intangible t
))
1784 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1785 (font-lock-fontify-block)))
1786 (let ((pos (move-marker (make-marker) (point)))
1787 (field (org-table-get-field))
1788 (cw (current-window-configuration))
1790 (org-switch-to-buffer-other-window "*Org tmp*")
1792 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
1793 (let ((org-inhibit-startup t
)) (org-mode))
1794 (goto-char (setq p
(point-max)))
1795 (insert (org-trim field
))
1796 (remove-text-properties p
(point-max)
1797 '(invisible t org-cwidth t display t
1800 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1801 (org-set-local 'org-window-configuration cw
)
1802 (org-set-local 'org-field-marker pos
)
1803 (message "Edit and finish with C-c C-c"))))
1805 (defun org-table-finish-edit-field ()
1806 "Finish editing a table data field.
1807 Remove all newline characters, insert the result into the table, realign
1808 the table and kill the editing buffer."
1809 (let ((pos org-field-marker
)
1810 (cw org-window-configuration
)
1811 (cb (current-buffer))
1813 (goto-char (point-min))
1814 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1815 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1816 (replace-match " "))
1817 (setq text
(org-trim (buffer-string)))
1818 (set-window-configuration cw
)
1820 (select-window (get-buffer-window (marker-buffer pos
)))
1822 (move-marker pos nil
)
1823 (org-table-check-inside-data-field)
1824 (org-table-get-field nil text
)
1826 (message "New field value inserted")))
1828 (defvar org-timecnt
) ; dynamically scoped parameter
1830 (defun org-table-sum (&optional beg end nlast
)
1831 "Sum numbers in region of current table column.
1832 The result will be displayed in the echo area, and will be available
1833 as kill to be inserted with \\[yank].
1835 If there is an active region, it is interpreted as a rectangle and all
1836 numbers in that rectangle will be summed. If there is no active
1837 region and point is located in a table column, sum all numbers in that
1840 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1841 numbers are assumed to be times as well (in decimal hours) and the
1842 numbers are added as such.
1844 If NLAST is a number, only the NLAST fields will actually be summed."
1847 (let (col (org-timecnt 0) diff h m s org-table-clip
)
1849 ((and beg end
)) ; beg and end given explicitly
1850 ((org-region-active-p)
1851 (setq beg
(region-beginning) end
(region-end)))
1853 (setq col
(org-table-current-column))
1854 (goto-char (org-table-begin))
1855 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
1856 (error "No table data"))
1857 (org-table-goto-column col
)
1859 (goto-char (org-table-end))
1860 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
1861 (error "No table data"))
1862 (org-table-goto-column col
)
1863 (setq end
(point))))
1864 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
1865 (items1 (cond ((not nlast
) items
)
1866 ((>= nlast
(length items
)) items
)
1867 (t (setq items
(reverse items
))
1868 (setcdr (nthcdr (1- nlast
) items
) nil
)
1870 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
1872 (res (apply '+ numbers
))
1873 (sres (if (= org-timecnt
0)
1874 (number-to-string res
)
1875 (setq diff
(* 3600 res
)
1876 h
(floor (/ diff
3600)) diff
(mod diff
3600)
1877 m
(floor (/ diff
60)) diff
(mod diff
60)
1879 (format "%d:%02d:%02d" h m s
))))
1883 (substitute-command-keys
1884 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
1885 (length numbers
) sres
))))
1888 (defun org-table-get-number-for-summing (s)
1890 (if (string-match "^ *|? *" s
)
1891 (setq s
(replace-match "" nil nil s
)))
1892 (if (string-match " *|? *$" s
)
1893 (setq s
(replace-match "" nil nil s
)))
1894 (setq n
(string-to-number s
))
1896 ((and (string-match "0" s
)
1897 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
1898 ((string-match "\\`[ \t]+\\'" s
) nil
)
1899 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
1900 (let ((h (string-to-number (or (match-string 1 s
) "0")))
1901 (m (string-to-number (or (match-string 2 s
) "0")))
1902 (s (string-to-number (or (match-string 4 s
) "0"))))
1903 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
1904 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
1908 (defun org-table-current-field-formula (&optional key noerror
)
1909 "Return the formula active for the current field.
1910 Assumes that specials are in place.
1911 If KEY is given, return the key to this formula.
1912 Otherwise return the formula preceded with \"=\" or \":=\"."
1913 (let* ((name (car (rassoc (list (org-current-line)
1914 (org-table-current-column))
1915 org-table-named-field-locations
)))
1916 (col (org-table-current-column))
1917 (scol (int-to-string col
))
1918 (ref (format "@%d$%d" (org-table-current-dline) col
))
1919 (stored-list (org-table-get-stored-formulas noerror
))
1920 (ass (or (assoc name stored-list
)
1921 (assoc ref stored-list
)
1922 (assoc scol stored-list
))))
1925 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
1928 (defun org-table-get-formula (&optional equation named
)
1929 "Read a formula from the minibuffer, offer stored formula as default.
1930 When NAMED is non-nil, look for a named equation."
1931 (let* ((stored-list (org-table-get-stored-formulas))
1932 (name (car (rassoc (list (org-current-line)
1933 (org-table-current-column))
1934 org-table-named-field-locations
)))
1935 (ref (format "@%d$%d" (org-table-current-dline)
1936 (org-table-current-column)))
1937 (refass (assoc ref stored-list
))
1938 (nameass (assoc name stored-list
))
1940 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
1943 (int-to-string (org-table-current-column))))
1944 (dummy (and (or nameass refass
) (not named
)
1945 (not (y-or-n-p "Replace existing field formula with column formula? " ))
1947 (name (or name ref
))
1948 (org-table-may-need-update nil
)
1949 (stored (cdr (assoc scol stored-list
)))
1951 ((and stored equation
(string-match "^ *=? *$" equation
))
1955 (t (org-table-formula-from-user
1957 (org-table-formula-to-user
1958 (format "%s formula %s%s="
1959 (if named
"Field" "Column")
1960 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
1962 (if stored
(org-table-formula-to-user stored
) "")
1963 'org-table-formula-history
1966 (when (not (string-match "\\S-" eq
))
1968 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
1969 (org-table-store-formulas stored-list
)
1970 (error "Formula removed"))
1971 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
1972 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
1973 (if (and name
(not named
))
1974 ;; We set the column equation, delete the named one.
1975 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
1978 (setcdr (assoc scol stored-list
) eq
)
1979 (setq stored-list
(cons (cons scol eq
) stored-list
)))
1980 (if (or mustsave
(not (equal stored eq
)))
1981 (org-table-store-formulas stored-list
))
1984 (defun org-table-store-formulas (alist)
1985 "Store the list of formulas below the current table."
1986 (setq alist
(sort alist
'org-table-formula-less-p
))
1988 (goto-char (org-table-end))
1989 (if (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM:\\(.*\n?\\)")
1991 ;; don't overwrite TBLFM, we might use text properties to store stuff
1992 (goto-char (match-beginning 2))
1993 (delete-region (match-beginning 2) (match-end 0)))
1994 (org-indent-line-function)
1995 (insert "#+TBLFM:"))
1997 (mapconcat (lambda (x)
1999 (if (equal (string-to-char (car x
)) ?
@) "" "$")
2000 (car x
) "=" (cdr x
)))
2004 (defsubst org-table-formula-make-cmp-string
(a)
2005 (when (string-match "\\`$[<>]" a
)
2006 (let ((arrow (string-to-char (substring a
1))))
2007 ;; Fake a high number to make sure this is sorted at the end.
2008 (setq a
(org-table-formula-handle-first/last-rc a
))
2009 (setq a
(format "$%d" (+ 10000
2010 (if (= arrow ?
<) -
1000 0)
2011 (string-to-number (substring a
1)))))))
2013 "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
2017 (format "@%05d" (string-to-number (match-string 2 a
))) "")
2019 (format "$%05d" (string-to-number (match-string 4 a
))) "")
2021 (concat "@@" (match-string 5 a
))))))
2023 (defun org-table-formula-less-p (a b
)
2024 "Compare two formulas for sorting."
2025 (let ((as (org-table-formula-make-cmp-string (car a
)))
2026 (bs (org-table-formula-make-cmp-string (car b
))))
2027 (and as bs
(string< as bs
))))
2029 (defun org-table-get-stored-formulas (&optional noerror
)
2030 "Return an alist with the stored formulas directly after current table."
2032 (let (scol eq eq-alist strings string seen
)
2034 (goto-char (org-table-end))
2035 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
2036 (setq strings
(org-split-string (org-match-string-no-properties 2)
2038 (while (setq string
(pop strings
))
2039 (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string
)
2040 (setq scol
(if (match-end 2)
2041 (match-string 2 string
)
2042 (match-string 1 string
))
2043 scol
(if (member (string-to-char scol
) '(?
< ?
>))
2044 (concat "$" scol
) scol
)
2045 eq
(match-string 3 string
)
2046 eq-alist
(cons (cons scol eq
) eq-alist
))
2047 (if (member scol seen
)
2050 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2053 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2054 (push scol seen
))))))
2055 (nreverse eq-alist
)))
2057 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2058 "Modify the equations after the table structure has been edited.
2059 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2060 For all numbers larger than LIMIT, shift them by DELTA."
2062 (goto-char (org-table-end))
2063 (when (looking-at "[ \t]*#\\+TBLFM:")
2064 (let ((re (concat key
"\\([0-9]+\\)"))
2067 (if (or (equal key
"$") (equal key
"$LR"))
2068 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2069 (regexp-quote key
) remove
)
2070 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2073 (while (re-search-forward re2
(point-at-eol) t
)
2074 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2075 (replace-match ""))))
2076 (while (re-search-forward re
(point-at-eol) t
)
2077 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2078 (setq s
(match-string 1) n
(string-to-number s
))
2080 ((setq a
(assoc s replace
))
2081 (replace-match (concat key
(cdr a
)) t t
))
2082 ((and limit
(> n limit
))
2083 (replace-match (concat key
(int-to-string (+ n delta
)))
2086 (defun org-table-get-specials ()
2087 "Get the column names and local parameters for this table."
2089 (let ((beg (org-table-begin)) (end (org-table-end))
2090 names name fields fields1 field cnt
2091 c v l line col types dlines hlines last-dline
)
2092 (setq org-table-column-names nil
2093 org-table-local-parameters nil
2094 org-table-named-field-locations nil
2095 org-table-current-begin-line nil
2096 org-table-current-begin-pos nil
2097 org-table-current-line-types nil
2098 org-table-current-ncol
0)
2100 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2101 (setq names
(org-split-string (match-string 1) " *| *")
2103 (while (setq name
(pop names
))
2105 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name
)
2106 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2107 (setq org-table-column-names
(nreverse org-table-column-names
))
2108 (setq org-table-column-name-regexp
2109 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2111 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2112 (setq fields
(org-split-string (match-string 1) " *| *"))
2113 (while (setq field
(pop fields
))
2114 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2115 (push (cons (match-string 1 field
) (match-string 2 field
))
2116 org-table-local-parameters
))))
2118 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2119 (setq c
(match-string 1)
2120 fields
(org-split-string (match-string 2) " *| *"))
2122 (beginning-of-line (if (equal c
"_") 2 0))
2123 (setq line
(org-current-line) col
1)
2124 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2125 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2126 (while (and fields1
(setq field
(pop fields
)))
2127 (setq v
(pop fields1
) col
(1+ col
))
2128 (when (and (stringp field
) (stringp v
)
2129 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field
))
2130 (push (cons field v
) org-table-local-parameters
)
2131 (push (list field line col
) org-table-named-field-locations
))))
2132 ;; Analyse the line types
2134 (setq org-table-current-begin-line
(org-current-line)
2135 org-table-current-begin-pos
(point)
2136 l org-table-current-begin-line
)
2137 (while (looking-at "[ \t]*|\\(-\\)?")
2138 (push (if (match-end 1) 'hline
'dline
) types
)
2139 (if (match-end 1) (push l hlines
) (push l dlines
))
2140 (beginning-of-line 2)
2142 (push 'hline types
) ;; add an imaginary extra hline to the end
2143 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2144 last-dline
(car dlines
)
2145 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2146 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2147 (org-goto-line last-dline
)
2148 (let* ((l last-dline
)
2149 (fields (org-split-string
2150 (buffer-substring (point-at-bol) (point-at-eol))
2152 (nfields (length fields
))
2154 (setq org-table-current-ncol nfields
)
2155 (loop for i from
1 to nfields do
2156 (push (list (format "LR%d" i
) l i
) al
)
2157 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2158 (setq org-table-named-field-locations
2159 (append org-table-named-field-locations al
))
2160 (setq org-table-local-parameters
2161 (append org-table-local-parameters al2
))))))
2163 (defun org-table-maybe-eval-formula ()
2164 "Check if the current field starts with \"=\" or \":=\".
2165 If yes, store the formula and apply it."
2166 ;; We already know we are in a table. Get field will only return a formula
2167 ;; when appropriate. It might return a separator line, but no problem.
2168 (when org-table-formula-evaluate-inline
2169 (let* ((field (org-trim (or (org-table-get-field) "")))
2171 (when (string-match "^:?=\\(.*\\)" field
)
2172 (setq named
(equal (string-to-char field
) ?
:)
2173 eq
(match-string 1 field
))
2174 (if (or (fboundp 'calc-eval
)
2175 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2176 (org-table-eval-formula (if named
'(4) nil
)
2177 (org-table-formula-from-user eq
))
2178 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2180 (defvar org-recalc-commands nil
2181 "List of commands triggering the recalculation of a line.
2182 Will be filled automatically during use.")
2184 (defvar org-recalc-marks
2185 '((" " .
"Unmarked: no special line, no automatic recalculation")
2186 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2187 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2188 ("!" .
"Column name definition line. Reference in formula as $name.")
2189 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2190 ("_" .
"Names for values in row below this one.")
2191 ("^" .
"Names for values in row above this one.")))
2193 (defun org-table-rotate-recalc-marks (&optional newchar
)
2194 "Rotate the recalculation mark in the first column.
2195 If in any row, the first field is not consistent with a mark,
2196 insert a new column for the markers.
2197 When there is an active region, change all the lines in the region,
2198 after prompting for the marking character.
2199 After each change, a message will be displayed indicating the meaning
2202 (unless (org-at-table-p) (error "Not at a table"))
2203 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2204 (beg (org-table-begin))
2205 (end (org-table-end))
2206 (l (org-current-line))
2207 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2208 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2212 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2213 (col (org-table-current-column))
2214 (forcenew (car (assoc newchar org-recalc-marks
)))
2217 (message "Change region to what mark? Type # * ! $ or SPC: ")
2218 (setq newchar
(char-to-string (read-char-exclusive))
2219 forcenew
(car (assoc newchar org-recalc-marks
))))
2220 (if (and newchar
(not forcenew
))
2221 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2223 (if l1
(org-goto-line l1
))
2225 (beginning-of-line 1)
2226 (unless (looking-at org-table-dataline-regexp
)
2227 (error "Not at a table data line")))
2229 (org-table-goto-column 1)
2230 (org-table-insert-column)
2231 (org-table-goto-column (1+ col
)))
2232 (setq epos
(point-at-eol))
2234 (beginning-of-line 1)
2235 (org-table-get-field
2236 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2238 (setq new
(or forcenew
2239 (cadr (member (match-string 1) marks
))))
2245 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2246 (and (looking-at org-table-dataline-regexp
)
2247 (org-table-get-field 1 (concat " " new
" "))))
2248 (org-goto-line l1
)))
2249 (if (not (= epos
(point-at-eol))) (org-table-align))
2251 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks
))))))
2253 (defun org-table-maybe-recalculate-line ()
2254 "Recompute the current line if marked for it, and if we haven't just done it."
2256 (and org-table-allow-automatic-line-recalculation
2257 (not (and (memq last-command org-recalc-commands
)
2258 (equal org-last-recalc-line
(org-current-line))))
2259 (save-excursion (beginning-of-line 1)
2260 (looking-at org-table-auto-recalculate-regexp
))
2261 (org-table-recalculate) t
))
2264 (defsubst org-set-calc-mode
(var &optional value
)
2266 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2267 ("R" calc-angle-mode rad
)
2268 ("F" calc-prefer-frac t
)
2269 ("S" calc-symbolic-mode t
)))
2270 value
(nth 2 var
) var
(nth 1 var
)))
2271 (if (memq var modes
)
2272 (setcar (cdr (memq var modes
)) value
)
2273 (cons var
(cons value modes
)))
2276 (defun org-table-eval-formula (&optional arg equation
2277 suppress-align suppress-const
2278 suppress-store suppress-analysis
)
2279 "Replace the table field value at the cursor by the result of a calculation.
2281 This function makes use of Dave Gillespie's Calc package, in my view the
2282 most exciting program ever written for GNU Emacs. So you need to have Calc
2283 installed in order to use this function.
2285 In a table, this command replaces the value in the current field with the
2286 result of a formula. It also installs the formula as the \"current\" column
2287 formula, by storing it in a special line below the table. When called
2288 with a `C-u' prefix, the current field must be a named field, and the
2289 formula is installed as valid in only this specific field.
2291 When called with two `C-u' prefixes, insert the active equation
2292 for the field back into the current field, so that it can be
2293 edited there. This is useful in order to use \\[org-table-show-reference]
2294 to check the referenced fields.
2296 When called, the command first prompts for a formula, which is read in
2297 the minibuffer. Previously entered formulas are available through the
2298 history list, and the last used formula is offered as a default.
2299 These stored formulas are adapted correctly when moving, inserting, or
2300 deleting columns with the corresponding commands.
2302 The formula can be any algebraic expression understood by the Calc package.
2303 For details, see the Org-mode manual.
2305 This function can also be called from Lisp programs and offers
2306 additional arguments: EQUATION can be the formula to apply. If this
2307 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2308 used to speed-up recursive calls by by-passing unnecessary aligns.
2309 SUPPRESS-CONST suppresses the interpretation of constants in the
2310 formula, assuming that this has been done already outside the function.
2311 SUPPRESS-STORE means the formula should not be stored, either because
2312 it is already stored, or because it is a modified equation that should
2313 not overwrite the stored one."
2315 (org-table-check-inside-data-field)
2316 (or suppress-analysis
(org-table-get-specials))
2317 (if (equal arg
'(16))
2318 (let ((eq (org-table-current-field-formula)))
2319 (or eq
(error "No equation active for current field"))
2320 (org-table-get-field nil eq
)
2322 (setq org-table-may-need-update t
))
2324 (ndown (if (integerp arg
) arg
1))
2325 (org-table-automatic-realign nil
)
2326 (case-fold-search nil
)
2328 (formula (if (and equation suppress-store
)
2330 (org-table-get-formula equation
(equal arg
'(4)))))
2331 (n0 (org-table-current-column))
2332 (modes (copy-sequence org-calc-default-modes
))
2333 (numbers nil
) ; was a variable, now fixed default
2335 n form form0 bw fmt x ev orig c lispp literal
)
2336 ;; Parse the format string. Since we have a lot of modes, this is
2337 ;; a lot of work. However, I think calc still uses most of the time.
2338 (if (string-match ";" formula
)
2339 (let ((tmp (org-split-string formula
";")))
2340 (setq formula
(car tmp
)
2341 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2343 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2344 (setq c
(string-to-char (match-string 1 fmt
))
2345 n
(string-to-number (match-string 2 fmt
)))
2347 (setq modes
(org-set-calc-mode 'calc-internal-prec n
))
2348 (setq modes
(org-set-calc-mode
2350 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2351 (?s . sci
) (?e . eng
))))
2353 (setq fmt
(replace-match "" t t fmt
)))
2354 (if (string-match "[NT]" fmt
)
2355 (setq numbers
(equal (match-string 0 fmt
) "N")
2356 fmt
(replace-match "" t t fmt
)))
2357 (if (string-match "L" fmt
)
2359 fmt
(replace-match "" t t fmt
)))
2360 (if (string-match "E" fmt
)
2362 fmt
(replace-match "" t t fmt
)))
2363 (while (string-match "[DRFS]" fmt
)
2364 (setq modes
(org-set-calc-mode (match-string 0 fmt
)))
2365 (setq fmt
(replace-match "" t t fmt
)))
2366 (unless (string-match "\\S-" fmt
)
2368 (if (and (not suppress-const
) org-table-formula-use-constants
)
2369 (setq formula
(org-table-formula-substitute-names formula
)))
2370 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2372 (setq fields
(org-split-string
2374 (buffer-substring (point-at-bol) (point-at-eol)))
2377 (setq fields
(mapcar
2378 (lambda (x) (number-to-string (string-to-number x
)))
2380 (setq ndown
(1- ndown
))
2381 (setq form
(copy-sequence formula
)
2382 lispp
(and (> (length form
) 2)(equal (substring form
0 2) "'(")))
2383 (if (and lispp literal
) (setq lispp
'literal
))
2385 ;; Insert row and column number of formula result field
2386 (while (string-match "[@$]#" form
)
2391 (if (equal (substring form
(match-beginning 0)
2392 (1+ (match-beginning 0)))
2394 (org-table-current-dline)
2395 (org-table-current-column))))
2398 ;; Check for old vertical references
2399 (setq form
(org-table-rewrite-old-row-references form
))
2400 ;; Insert remote references
2401 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2405 (org-table-make-reference
2406 (org-table-get-remote-range
2407 (match-string 1 form
) (match-string 2 form
))
2408 keep-empty numbers lispp
))
2410 ;; Insert complex ranges
2411 (while (and (string-match org-table-range-regexp form
)
2412 (> (length (match-string 0 form
)) 1))
2416 (org-table-make-reference
2417 (org-table-get-range (match-string 0 form
) nil n0
)
2418 keep-empty numbers lispp
))
2420 ;; Insert simple ranges
2421 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2425 (org-table-make-reference
2427 fields
(string-to-number (match-string 1 form
))
2428 (string-to-number (match-string 2 form
)))
2429 keep-empty numbers lispp
))
2432 ;; Insert the references to fields in same row
2433 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2434 (setq n
(+ (string-to-number (match-string 1 form
))
2435 (if (match-end 2) n0
0))
2436 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
))
2437 (unless x
(error "Invalid field specifier \"%s\""
2438 (match-string 0 form
)))
2439 (setq form
(replace-match
2441 (org-table-make-reference x nil numbers lispp
))
2445 (setq ev
(condition-case nil
2446 (eval (eval (read form
)))
2448 ev
(if (numberp ev
) (number-to-string ev
) ev
))
2449 (or (fboundp 'calc-eval
)
2450 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2451 (setq ev
(calc-eval (cons form modes
)
2452 (if numbers
'num
))))
2454 (when org-table-formula-debug
2455 (with-output-to-temp-buffer "*Substitution History*"
2456 (princ (format "Substitution history of formula
2460 $1-> %s\n" orig formula form0 form
))
2462 (princ (format " %s^\nError: %s"
2463 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2464 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2466 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2467 (setq bw
(get-buffer-window "*Substitution History*"))
2468 (org-fit-window-to-buffer bw
)
2469 (unless (and (interactive-p) (not ndown
))
2470 (unless (let (inhibit-redisplay)
2471 (y-or-n-p "Debugging Formula. Continue to next? "))
2476 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2477 (org-table-justify-field-maybe
2478 (if fmt
(format fmt
(string-to-number ev
)) ev
))
2479 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2480 (call-interactively 'org-return
)
2482 (and down
(org-table-maybe-recalculate-line))
2483 (or suppress-align
(and org-table-may-need-update
2484 (org-table-align))))))
2486 (defun org-table-put-field-property (prop value
)
2488 (put-text-property (progn (skip-chars-backward "^|") (point))
2489 (progn (skip-chars-forward "^|") (point))
2492 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2493 "Get a calc vector from a column, according to descriptor DESC.
2494 Optional arguments TBEG and COL can give the beginning of the table and
2495 the current column, to avoid unnecessary parsing.
2497 HIGHLIGHT means just highlight the range.
2499 When CORNERS-ONLY is set, only return the corners of the range as
2500 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2501 in the buffer and column1 and column2 are table column numbers."
2502 (if (not (equal (string-to-char desc
) ?
@))
2503 (setq desc
(concat "@" desc
)))
2505 (or tbeg
(setq tbeg
(org-table-begin)))
2506 (or col
(setq col
(org-table-current-column)))
2507 (let ((thisline (org-current-line))
2508 beg end c1 c2 r1 r2 rangep tmp
)
2509 (unless (string-match org-table-range-regexp desc
)
2510 (error "Invalid table range specifier `%s'" desc
))
2511 (setq rangep
(match-end 3)
2512 r1
(and (match-end 1) (match-string 1 desc
))
2513 r2
(and (match-end 4) (match-string 4 desc
))
2514 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2515 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2517 (and c1
(setq c1
(+ (string-to-number c1
)
2518 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2519 (and c2
(setq c2
(+ (string-to-number c2
)
2520 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2521 (if (equal r1
"") (setq r1 nil
))
2522 (if (equal r2
"") (setq r2 nil
))
2523 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2524 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2525 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2526 (if (not r1
) (setq r1 thisline
))
2527 (if (not r2
) (setq r2 thisline
))
2528 (if (not c1
) (setq c1 col
))
2529 (if (not c2
) (setq c2 col
))
2530 (if (and (not corners-only
)
2531 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2535 (while (not (looking-at org-table-dataline-regexp
))
2536 (beginning-of-line 2))
2537 (prog1 (org-trim (org-table-get-field c1
))
2538 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2539 ;; A range, return a vector
2540 ;; First sort the numbers to get a regular ractangle
2541 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2542 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2544 ;; Only return the corners of the range
2546 ;; Copy the range values into a list
2548 (while (not (looking-at org-table-dataline-regexp
))
2549 (beginning-of-line 2))
2550 (org-table-goto-column c1
)
2553 (while (not (looking-at org-table-dataline-regexp
))
2554 (beginning-of-line 0))
2555 (org-table-goto-column c2
)
2558 (org-table-highlight-rectangle
2559 beg
(progn (skip-chars-forward "^|\n") (point))))
2560 ;; return string representation of calc vector
2562 (apply 'append
(org-table-copy-region beg end
))))))))
2564 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2565 "Analyze descriptor DESC and retrieve the corresponding line number.
2566 The cursor is currently in line CLINE, the table begins in line BLINE,
2567 and TABLE is a vector with line types."
2568 (if (string-match "^[0-9]+$" desc
)
2569 (aref org-table-dlines
(string-to-number desc
))
2570 (setq cline
(or cline
(org-current-line))
2571 bline
(or bline org-table-current-begin-line
)
2572 table
(or table org-table-current-line-types
))
2574 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2576 (and (not (match-end 3)) (not (match-end 6)))
2577 (and (match-end 3) (match-end 6) (not (match-end 5))))
2578 (error "Invalid row descriptor `%s'" desc
))
2579 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2580 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2581 (odir (and (match-end 5) (match-string 5 desc
)))
2582 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2584 (rel (and (match-end 6)
2585 (or (and (match-end 1) (not (match-end 3)))
2587 (if (and hn
(not hdir
))
2590 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2591 (if (and (not hn
) on
(not odir
))
2592 (error "Should never happen");;(aref org-table-dlines on)
2593 (if (and hn
(> hn
0))
2594 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2595 nil hn cline desc
)))
2597 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2598 rel on cline desc
)))
2601 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2602 "FIXME: Needs more documentation."
2603 (let ((l (length table
)))
2605 (while (and (setq i
(+ i
(if backwards -
1 1)))
2607 (not (eq (aref table i
) type
))
2608 (if (and relative
(eq (aref table i
) 'hline
))
2610 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2611 ((eq org-table-relative-ref-may-cross-hline
'error
)
2612 (error "Row descriptor %s used in line %d crosses hline" desc cline
))
2613 (t (setq i
(- i
(if backwards -
1 1))
2618 (if (or (< i
0) (>= i l
))
2619 (error "Row descriptor %s used in line %d leads outside table"
2623 (defun org-table-rewrite-old-row-references (s)
2624 (if (string-match "&[-+0-9I]" s
)
2625 (error "Formula contains old &row reference, please rewrite using @-syntax")
2628 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2629 "Convert list ELEMENTS to something appropriate to insert into formula.
2630 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2631 NUMBERS indicates that everything should be converted to numbers.
2632 LISPP means to return something appropriate for a Lisp list."
2633 (if (stringp elements
) ; just a single val
2635 (if (eq lispp
'literal
)
2637 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2638 (if (equal elements
"") (setq elements
"0"))
2639 (if numbers
(setq elements
(number-to-string (string-to-number elements
))))
2640 (concat "(" elements
")"))
2644 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2646 (setq elements
(or elements
'("0")))
2650 (if (eq lispp
'literal
)
2652 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2654 (concat "[" (mapconcat
2656 (if numbers
(number-to-string (string-to-number x
)) x
))
2660 (defun org-table-recalculate (&optional all noalign
)
2661 "Recalculate the current table line by applying all stored formulas.
2662 With prefix arg ALL, do this for all lines in the table.
2663 With the prefix argument ALL is `(16)' \
2664 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2665 it is the symbol `iterate', recompute the table until it no longer changes.
2666 If NOALIGN is not nil, do not re-align the table after the computations
2667 are done. This is typically used internally to save time, if it is
2668 known that the table will be realigned a little later anyway."
2670 (or (memq this-command org-recalc-commands
)
2671 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2672 (unless (org-at-table-p) (error "Not at a table"))
2673 (if (or (eq all
'iterate
) (equal all
'(16)))
2675 (org-table-get-specials)
2676 (let* ((eqlist (sort (org-table-get-stored-formulas)
2677 (lambda (a b
) (string< (car a
) (car b
)))))
2678 (eqlist1 (copy-sequence eqlist
))
2679 (inhibit-redisplay (not debug-on-error
))
2680 (line-re org-table-dataline-regexp
)
2681 (thisline (org-current-line))
2682 (thiscol (org-table-current-column))
2684 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
2685 ;; Insert constants in all formulas
2688 (when (string-match "\\`$[<>]" (car x
))
2690 (setq x
(cons (substring
2691 (org-table-formula-handle-first/last-rc
2694 (if (assoc (car x
) eqlist1
)
2695 (error "\"%s=\" formula tries to overwrite existing formula for column %s"
2698 (org-table-formula-handle-first/last-rc
(car x
))
2699 (org-table-formula-substitute-names
2700 (org-table-formula-handle-first/last-rc
(cdr x
)))))
2702 ;; Split the equation list
2703 (while (setq eq
(pop eqlist
))
2704 (if (<= (string-to-char (car eq
)) ?
9)
2707 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
2708 ;; Expand ranges in lhs of formulas
2709 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
2711 ;; Get the correct line range to process
2714 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
2715 (goto-char (setq beg
(org-table-begin)))
2716 (if (re-search-forward org-table-calculate-mark-regexp end t
)
2717 ;; This is a table with marked lines, compute selected lines
2718 (setq line-re org-table-recalculate-regexp
)
2719 ;; Move forward to the first non-header line
2720 (if (and (re-search-forward org-table-dataline-regexp end t
)
2721 (re-search-forward org-table-hline-regexp end t
)
2722 (re-search-forward org-table-dataline-regexp end t
))
2723 (setq beg
(match-beginning 0))
2724 nil
))) ;; just leave beg where it is
2725 (setq beg
(point-at-bol)
2726 end
(move-marker (make-marker) (1+ (point-at-eol)))))
2728 (and all
(message "Re-applying formulas to full table..."))
2730 ;; First find the named fields, and mark them untouchable.
2731 ;; Also check if several field/range formulas try to set the same field.
2732 (remove-text-properties beg end
'(org-untouchable t
))
2733 (while (setq eq
(pop eqlname
))
2735 a
(assoc name org-table-named-field-locations
))
2737 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
2739 (when (member name1 seen-fields
)
2740 (error "Several field/range formulas try to set %s" name1
))
2741 (push name1 seen-fields
)
2744 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
2747 (aref org-table-dlines
2748 (string-to-number (match-string 1 name
)))
2749 (error (error "Invalid row number in %s"
2751 (string-to-number (match-string 2 name
)))))
2752 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
2753 (message "Re-applying formula to field: %s" name
)
2754 (org-goto-line (nth 1 a
))
2755 (org-table-goto-column (nth 2 a
))
2756 (push (append a
(list (cdr eq
))) eqlname1
)
2757 (org-table-put-field-property :org-untouchable t
)))
2758 (setq eqlname1
(nreverse eqlname1
))
2760 ;; Now evaluate the column formulas, but skip fields covered by
2763 (while (re-search-forward line-re end t
)
2764 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2765 ;; Unprotected line, recalculate
2766 (and all
(message "Re-applying formulas to full table...(line %d)"
2767 (setq cnt
(1+ cnt
))))
2768 (setq org-last-recalc-line
(org-current-line))
2770 (while (setq entry
(pop eql
))
2771 (org-goto-line org-last-recalc-line
)
2772 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
2773 (unless (get-text-property (point) :org-untouchable
)
2774 (org-table-eval-formula nil
(cdr entry
)
2775 'noalign
'nocst
'nostore
'noanalysis
)))))
2777 ;; Now evaluate the field formulas
2778 (while (setq eq
(pop eqlname1
))
2779 (message "Re-applying formula to field: %s" (car eq
))
2780 (org-goto-line (nth 1 eq
))
2781 (org-table-goto-column (nth 2 eq
))
2782 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
2783 'nostore
'noanalysis
))
2785 (org-goto-line thisline
)
2786 (org-table-goto-column thiscol
)
2787 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
2788 (or noalign
(and org-table-may-need-update
(org-table-align))
2789 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
2791 ;; back to initial position
2792 (message "Re-applying formulas...done")
2793 (org-goto-line thisline
)
2794 (org-table-goto-column thiscol
)
2795 (or noalign
(and org-table-may-need-update
(org-table-align))
2796 (and all
(message "Re-applying formulas...done"))))))
2798 (defun org-table-iterate (&optional arg
)
2799 "Recalculate the table until it does not change anymore.
2800 The maximun number of iterations is 10, but you can chose a different value
2801 with the prefix ARG."
2803 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
2805 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2810 (org-table-recalculate 'all
)
2811 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
2812 (if (not (string= lasttbl thistbl
))
2813 (setq lasttbl thistbl
)
2815 (message "Convergence after %d iterations" i
)
2816 (message "Table was already stable"))
2818 (error "No convergence after %d iterations" i
))))
2820 (defun org-table-recalculate-buffer-tables ()
2821 "Recalculate all tables in the current buffer."
2826 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
2828 (defun org-table-iterate-buffer-tables ()
2829 "Iterate all tables in the buffer, to converge inter-table dependencies."
2832 (checksum (md5 (buffer-string)))
2842 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
2843 (if (equal checksum
(setq c1
(md5 (buffer-string))))
2845 (message "Convergence after %d iterations" (- imax i
))
2847 (setq checksum c1
)))
2848 (error "No convergence after %d iterations" imax
))))))
2850 (defun org-table-expand-lhs-ranges (equations)
2851 "Expand list of formulas.
2852 If some of the RHS in the formulas are ranges or a row reference, expand
2853 them to individual field equations for each field."
2854 (let (e res lhs rhs range r1 r2 c1 c2
)
2855 (while (setq e
(pop equations
))
2856 (setq lhs
(car e
) rhs
(cdr e
))
2858 ((string-match "^@-?[-+I0-9]+\\$-?[0-9]+$" lhs
)
2859 ;; This just refers to one fixed field
2861 ((string-match "^[a-zA-Z][a-zA-Z0-9]*$" lhs
)
2862 ;; This just refers to one fixed named field
2864 ((string-match "^@[0-9]+$" lhs
)
2865 (loop for ic from
1 to org-table-current-ncol do
2866 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
2867 (put-text-property 0 (length (caar res
))
2868 :orig-eqn e
(caar res
))))
2870 (setq range
(org-table-get-range lhs org-table-current-begin-pos
2872 (setq r1
(nth 0 range
) c1
(nth 1 range
)
2873 r2
(nth 2 range
) c2
(nth 3 range
))
2874 (setq r1
(org-table-line-to-dline r1
))
2875 (setq r2
(org-table-line-to-dline r2
'above
))
2876 (loop for ir from r1 to r2 do
2877 (loop for ic from c1 to c2 do
2878 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
2879 (put-text-property 0 (length (caar res
))
2880 :orig-eqn e
(caar res
)))))))
2883 (defun org-table-formula-handle-first/last-rc
(s)
2884 "Replace @<, @>, $<, $> with first/last row/column of the table.
2885 So @< and $< will always be replaced with @1 and $1, respectively.
2886 The advantage of these special markers are that structure editing of
2887 the table will not change them, while @1 and $1 will be modified
2888 when a line/row is swaped out of that privileged position. So for
2889 formulas that use a range of rows or columns, it may often be better
2890 to anchor the formula with \"I\" row markers, or to offset from the
2891 borders of the table using the @< @> $< $> makers."
2892 (let (n nmax len char
)
2893 (while (string-match "\\([@$]\\)\\(<+\\|>+\\)" s
)
2894 (setq nmax
(if (equal (match-string 1 s
) "@")
2895 (1- (length org-table-dlines
))
2896 org-table-current-ncol
)
2897 len
(- (match-end 2) (match-beginning 2))
2898 char
(string-to-char (match-string 2 s
))
2902 (if (or (< n
1) (> n nmax
))
2903 (error "Reference \"%s\" in expression \"%s\" points outside table"
2904 (match-string 0 s
) s
))
2905 (setq s
(replace-match (format "%s%d" (match-string 1 s
) n
) t t s
))))
2908 (defun org-table-formula-substitute-names (f)
2909 "Replace $const with values in string F."
2910 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
2911 ;; First, check for column names
2912 (while (setq start
(string-match org-table-column-name-regexp f start
))
2913 (setq start
(1+ start
))
2914 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
2915 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
2916 ;; Parameters and constants
2918 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
2920 (setq start
(match-end 2))
2921 (setq start
(1+ start
))
2922 (if (setq a
(save-match-data
2923 (org-table-get-constant (match-string 1 f
))))
2924 (setq f
(replace-match
2925 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
2926 (if org-table-formula-debug
2927 (put-text-property 0 (length f
) :orig-formula f1 f
))
2930 (defun org-table-get-constant (const)
2931 "Find the value for a parameter or constant in a formula.
2932 Parameters get priority."
2933 (or (cdr (assoc const org-table-local-parameters
))
2934 (cdr (assoc const org-table-formula-constants-local
))
2935 (cdr (assoc const org-table-formula-constants
))
2936 (and (fboundp 'constants-get
) (constants-get const
))
2937 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
2938 (org-entry-get nil
(substring const
5) 'inherit
))
2941 (defvar org-table-fedit-map
2942 (let ((map (make-sparse-keymap)))
2943 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
2944 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
2945 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
2946 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
2947 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
2948 (org-defkey map
"\C-c?" 'org-table-show-reference
)
2949 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
2950 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
2951 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
2952 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
2953 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
2954 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
2955 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
2956 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
2957 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
2958 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
2959 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
2960 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
2961 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
2962 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
2965 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
2967 ["Finish and Install" org-table-fedit-finish t
]
2968 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
2969 ["Abort" org-table-fedit-abort t
]
2971 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
2972 ["Complete Lisp Symbol" lisp-complete-symbol t
]
2974 "Shift Reference at Point"
2975 ["Up" org-table-fedit-ref-up t
]
2976 ["Down" org-table-fedit-ref-down t
]
2977 ["Left" org-table-fedit-ref-left t
]
2978 ["Right" org-table-fedit-ref-right t
]
2980 "Change Test Row for Column Formulas"
2981 ["Up" org-table-fedit-line-up t
]
2982 ["Down" org-table-fedit-line-down t
]
2984 ["Scroll Table Window" org-table-fedit-scroll t
]
2985 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
2986 ["Show Table Grid" org-table-fedit-toggle-coordinates
2987 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
2988 org-table-overlay-coordinates
)]
2990 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
2991 :style toggle
:selected org-table-buffer-is-an
]))
2995 (defun org-table-edit-formulas ()
2996 "Edit the formulas of the current table in a separate buffer."
2998 (when (save-excursion (beginning-of-line 1) (looking-at "[ \t]*#\\+TBLFM"))
2999 (beginning-of-line 0))
3000 (unless (org-at-table-p) (error "Not at a table"))
3001 (org-table-get-specials)
3002 (let ((key (org-table-current-field-formula 'key
'noerror
))
3003 (eql (sort (org-table-get-stored-formulas 'noerror
)
3004 'org-table-formula-less-p
))
3005 (pos (move-marker (make-marker) (point)))
3007 (wc (current-window-configuration))
3008 (sel-win (selected-window))
3009 (titles '((column .
"# Column Formulas\n")
3010 (field .
"# Field and Range Formulas\n")
3011 (named .
"# Named Field Formulas\n")))
3013 (org-switch-to-buffer-other-window "*Edit Formulas*")
3015 ;; Keep global-font-lock-mode from turning on font-lock-mode
3016 (let ((font-lock-global-modes '(not fundamental-mode
)))
3018 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
3019 (org-set-local 'org-pos pos
)
3020 (org-set-local 'org-window-configuration wc
)
3021 (org-set-local 'org-selected-window sel-win
)
3022 (use-local-map org-table-fedit-map
)
3023 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3024 (easy-menu-add org-table-fedit-menu
)
3025 (setq startline
(org-current-line))
3026 (while (setq entry
(pop eql
))
3028 ((string-match "\\`$[<>]" (car entry
)) 'column
)
3029 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3030 ((string-match "^[0-9]" (car entry
)) 'column
)
3032 (when (setq title
(assq type titles
))
3033 (or (bobp) (insert "\n"))
3034 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3035 (setq titles
(remove title titles
)))
3036 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3037 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3038 (car entry
) " = " (cdr entry
) "\n"))
3039 (remove-text-properties 0 (length s
) '(face nil
) s
)
3041 (if (eq org-table-use-standard-references t
)
3042 (org-table-fedit-toggle-ref-type))
3043 (org-goto-line startline
)
3044 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3046 (defun org-table-fedit-post-command ()
3047 (when (not (memq this-command
'(lisp-complete-symbol)))
3048 (let ((win (selected-window)))
3051 (org-table-show-reference)
3053 (select-window win
)))))
3055 (defun org-table-formula-to-user (s)
3056 "Convert a formula from internal to user representation."
3057 (if (eq org-table-use-standard-references t
)
3058 (org-table-convert-refs-to-an s
)
3061 (defun org-table-formula-from-user (s)
3062 "Convert a formula from user to internal representation."
3063 (if org-table-use-standard-references
3064 (org-table-convert-refs-to-rc s
)
3067 (defun org-table-convert-refs-to-rc (s)
3068 "Convert spreadsheet references from A7 to @7$28.
3069 Works for single references, but also for entire formulas and even the
3072 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^)]*)\\)" s start
)
3075 ;; format match, just advance
3076 (setq start
(match-end 0)))
3077 ((and (> (match-beginning 0) 0)
3078 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3079 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3080 ;; 3.e5 or something like this.
3081 (setq start
(match-end 0)))
3082 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3083 ;; (member (match-string 1 s)
3084 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3086 ;; function name, just advance
3087 (setq start
(match-end 0)))
3089 (setq start
(match-beginning 0)
3091 (if (equal (match-string 2 s
) "&")
3092 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3094 (string-to-number (match-string 2 s
))
3095 (org-letters-to-number (match-string 1 s
))))
3099 (defun org-table-convert-refs-to-an (s)
3100 "Convert spreadsheet references from to @7$28 to AB7.
3101 Works for single references, but also for entire formulas and even the
3103 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3104 (setq s
(replace-match
3106 (org-number-to-letters
3107 (string-to-number (match-string 2 s
)))
3108 (string-to-number (match-string 1 s
)))
3110 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3111 (setq s
(replace-match (concat "\\1"
3112 (org-number-to-letters
3113 (string-to-number (match-string 2 s
))) "&")
3117 (defun org-letters-to-number (s)
3118 "Convert a base 26 number represented by letters into an integer.
3119 For example: AB -> 28."
3122 (while (> (length s
) 0)
3123 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3127 (defun org-number-to-letters (n)
3128 "Convert an integer into a base 26 number represented by letters.
3129 For example: 28 -> AB."
3132 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3136 (defun org-table-fedit-convert-buffer (function)
3137 "Convert all references in this buffer, using FUNCTION."
3138 (let ((line (org-current-line)))
3139 (goto-char (point-min))
3141 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3142 (delete-region (point) (point-at-eol))
3143 (or (eobp) (forward-char 1)))
3144 (org-goto-line line
)))
3146 (defun org-table-fedit-toggle-ref-type ()
3147 "Convert all references in the buffer from B3 to @3$2 and back."
3149 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3150 (org-table-fedit-convert-buffer
3151 (if org-table-buffer-is-an
3152 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3153 (message "Reference type switched to %s"
3154 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3156 (defun org-table-fedit-ref-up ()
3157 "Shift the reference at point one row/hline up."
3159 (org-table-fedit-shift-reference 'up
))
3160 (defun org-table-fedit-ref-down ()
3161 "Shift the reference at point one row/hline down."
3163 (org-table-fedit-shift-reference 'down
))
3164 (defun org-table-fedit-ref-left ()
3165 "Shift the reference at point one field to the left."
3167 (org-table-fedit-shift-reference 'left
))
3168 (defun org-table-fedit-ref-right ()
3169 "Shift the reference at point one field to the right."
3171 (org-table-fedit-shift-reference 'right
))
3173 (defun org-table-fedit-shift-reference (dir)
3175 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3176 (if (memq dir
'(left right
))
3177 (org-rematch-and-replace 1 (eq dir
'left
))
3178 (error "Cannot shift reference in this direction")))
3179 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3180 ;; A B3-like reference
3181 (if (memq dir
'(up down
))
3182 (org-rematch-and-replace 2 (eq dir
'up
))
3183 (org-rematch-and-replace 1 (eq dir
'left
))))
3185 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3186 ;; An internal reference
3187 (if (memq dir
'(up down
))
3188 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3189 (org-rematch-and-replace 5 (eq dir
'left
))))))
3191 (defun org-rematch-and-replace (n &optional decr hline
)
3192 "Re-match the group N, and replace it with the shifted reference."
3193 (or (match-end n
) (error "Cannot shift reference in this direction"))
3194 (goto-char (match-beginning n
))
3195 (and (looking-at (regexp-quote (match-string n
)))
3196 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3199 (defun org-table-shift-refpart (ref &optional decr hline
)
3200 "Shift a reference part REF.
3201 If DECR is set, decrease the references row/column, else increase.
3202 If HLINE is set, this may be a hline reference, it certainly is not
3203 a translation reference."
3205 (let* ((sign (string-match "^[-+]" ref
)) n
)
3207 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3209 ((and hline
(string-match "^I+" ref
))
3210 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3211 (setq n
(+ n
(if decr -
1 1)))
3212 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3214 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3216 (concat sign
(make-string n ?I
)))
3218 ((string-match "^[0-9]+" ref
)
3219 (setq n
(string-to-number (concat sign ref
)))
3220 (setq n
(+ n
(if decr -
1 1)))
3222 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3223 (number-to-string (max 1 n
))))
3225 ((string-match "^[a-zA-Z]+" ref
)
3226 (org-number-to-letters
3227 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3229 (t (error "Cannot shift reference"))))))
3231 (defun org-table-fedit-toggle-coordinates ()
3232 "Toggle the display of coordinates in the referenced table."
3234 (let ((pos (marker-position org-pos
)))
3235 (with-current-buffer (marker-buffer org-pos
)
3238 (org-table-toggle-coordinate-overlays)))))
3240 (defun org-table-fedit-finish (&optional arg
)
3241 "Parse the buffer for formula definitions and install them.
3242 With prefix ARG, apply the new formulas to the table."
3244 (org-table-remove-rectangle-highlight)
3245 (if org-table-use-standard-references
3247 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3248 (setq org-table-buffer-is-an nil
)))
3249 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3250 (goto-char (point-min))
3251 (while (re-search-forward
3252 "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3254 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3255 form
(match-string 3))
3256 (setq form
(org-trim form
))
3257 (when (not (equal form
""))
3258 (while (string-match "[ \t]*\n[ \t]*" form
)
3259 (setq form
(replace-match " " t t form
)))
3260 (when (assoc var eql
)
3261 (error "Double formulas for %s" var
))
3262 (push (cons var form
) eql
)))
3264 (set-window-configuration org-window-configuration
)
3265 (select-window sel-win
)
3267 (unless (org-at-table-p)
3268 (error "Lost table position - cannot install formulas"))
3269 (org-table-store-formulas eql
)
3270 (move-marker pos nil
)
3271 (kill-buffer "*Edit Formulas*")
3273 (org-table-recalculate 'all
)
3274 (message "New formulas installed - press C-u C-c C-c to apply."))))
3276 (defun org-table-fedit-abort ()
3277 "Abort editing formulas, without installing the changes."
3279 (org-table-remove-rectangle-highlight)
3280 (let ((pos org-pos
) (sel-win org-selected-window
))
3281 (set-window-configuration org-window-configuration
)
3282 (select-window sel-win
)
3284 (move-marker pos nil
)
3285 (message "Formula editing aborted without installing changes")))
3287 (defun org-table-fedit-lisp-indent ()
3288 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3290 (let ((pos (point)) beg end ind
)
3291 (beginning-of-line 1)
3293 ((looking-at "[ \t]")
3295 (call-interactively 'lisp-indent-line
))
3296 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3297 ((not (fboundp 'pp-buffer
))
3298 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3299 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3300 (goto-char (- (match-end 0) 2))
3302 (setq ind
(make-string (current-column) ?\
))
3303 (condition-case nil
(forward-sexp 1)
3305 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3308 (narrow-to-region beg end
)
3309 (if (eq last-command this-command
)
3311 (goto-char (point-min))
3312 (setq this-command nil
)
3313 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3314 (replace-match " ")))
3316 (untabify (point-min) (point-max))
3317 (goto-char (1+ (point-min)))
3318 (while (re-search-forward "^." nil t
)
3319 (beginning-of-line 1)
3321 (goto-char (point-max))
3322 (backward-delete-char 1)))
3326 (defvar org-show-positions nil
)
3328 (defun org-table-show-reference (&optional local
)
3329 "Show the location/value of the $ expression at point."
3331 (org-table-remove-rectangle-highlight)
3333 (let ((pos (if local
(point) org-pos
))
3335 (org-inhibit-highlight-removal t
)
3336 (win (selected-window))
3337 (org-show-positions nil
)
3338 var name e what match dest
)
3339 (if local
(org-table-get-specials))
3341 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3342 (setq match
(concat (substring (match-string 0) 0 -
1)
3344 (substring (match-string 0) 0 -
1)
3347 ((or (org-at-regexp-p org-table-range-regexp2
)
3348 (org-at-regexp-p org-table-translate-regexp
)
3349 (org-at-regexp-p org-table-range-regexp
))
3352 (org-table-convert-refs-to-rc (match-string 0))))
3354 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3355 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3357 (t (error "No reference at point")))
3358 match
(and what
(or match
(match-string 0))))
3359 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3360 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3361 'secondary-selection
))
3362 (org-add-hook 'before-change-functions
3363 'org-table-remove-rectangle-highlight
)
3364 (if (eq what
'name
) (setq var
(substring match
1)))
3365 (when (eq what
'range
)
3366 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3367 (setq match
(org-table-formula-substitute-names match
)))
3371 (re-search-backward "^\\S-" nil t
)
3372 (beginning-of-line 1)
3373 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3376 (org-table-convert-refs-to-rc (match-string 1))))
3377 (org-table-add-rectangle-overlay
3378 (match-beginning 1) (match-end 1) face2
))))
3379 (if (and (markerp pos
) (marker-buffer pos
))
3380 (if (get-buffer-window (marker-buffer pos
))
3381 (select-window (get-buffer-window (marker-buffer pos
)))
3382 (org-switch-to-buffer-other-window (get-buffer-window
3383 (marker-buffer pos
)))))
3385 (org-table-force-dataline)
3387 (setq name
(substring dest
1))
3389 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3390 (setq e
(assoc name org-table-named-field-locations
))
3391 (org-goto-line (nth 1 e
))
3392 (org-table-goto-column (nth 2 e
)))
3393 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3394 (let ((l (string-to-number (match-string 1 dest
)))
3395 (c (string-to-number (match-string 2 dest
))))
3396 (org-goto-line (aref org-table-dlines l
))
3397 (org-table-goto-column c
)))
3398 (t (org-table-goto-column (string-to-number name
))))
3399 (move-marker pos
(point))
3400 (org-table-highlight-rectangle nil nil face2
))
3402 ((equal dest match
))
3407 (org-table-get-range match nil nil
'highlight
))
3409 ((setq e
(assoc var org-table-named-field-locations
))
3410 (org-goto-line (nth 1 e
))
3411 (org-table-goto-column (nth 2 e
))
3412 (org-table-highlight-rectangle (point) (point))
3413 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3414 ((setq e
(assoc var org-table-column-names
))
3415 (org-table-goto-column (string-to-number (cdr e
)))
3416 (org-table-highlight-rectangle (point) (point))
3417 (goto-char (org-table-begin))
3418 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3421 (goto-char (match-beginning 1))
3422 (org-table-highlight-rectangle)
3423 (message "Named column (column %s)" (cdr e
)))
3424 (error "Column name not found")))
3427 (org-table-goto-column (string-to-number (substring match
1)))
3428 (org-table-highlight-rectangle (point) (point))
3429 (message "Column %s" (substring match
1)))
3430 ((setq e
(assoc var org-table-local-parameters
))
3431 (goto-char (org-table-begin))
3432 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3434 (goto-char (match-beginning 1))
3435 (org-table-highlight-rectangle)
3436 (message "Local parameter."))
3437 (error "Parameter not found")))
3440 ((not var
) (error "No reference at point"))
3441 ((setq e
(assoc var org-table-formula-constants-local
))
3442 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3444 ((setq e
(assoc var org-table-formula-constants
))
3445 (message "Constant: $%s=%s in `org-table-formula-constants'."
3447 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3448 (message "Constant: $%s=%s, from `constants.el'%s."
3449 var e
(format " (%s units)" constants-unit-system
)))
3450 (t (error "Undefined name $%s" var
)))))
3452 (when (and org-show-positions
3453 (not (memq this-command
'(org-table-fedit-scroll
3454 org-table-fedit-scroll-down
))))
3455 (push pos org-show-positions
)
3456 (push org-table-current-begin-pos org-show-positions
)
3457 (let ((min (apply 'min org-show-positions
))
3458 (max (apply 'max org-show-positions
)))
3459 (goto-char min
) (recenter 0)
3461 (or (pos-visible-in-window-p max
) (recenter -
1))))
3462 (select-window win
))))
3464 (defun org-table-force-dataline ()
3465 "Make sure the cursor is in a dataline in a table."
3466 (unless (save-excursion
3467 (beginning-of-line 1)
3468 (looking-at org-table-dataline-regexp
))
3469 (let* ((re org-table-dataline-regexp
)
3470 (p1 (save-excursion (re-search-forward re nil
'move
)))
3471 (p2 (save-excursion (re-search-backward re nil
'move
))))
3473 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3475 ((or p1 p2
) (goto-char (or p1 p2
)))
3476 (t (error "No table dataline around here"))))))
3478 (defun org-table-fedit-line-up ()
3479 "Move cursor one line up in the window showing the table."
3481 (org-table-fedit-move 'previous-line
))
3483 (defun org-table-fedit-line-down ()
3484 "Move cursor one line down in the window showing the table."
3486 (org-table-fedit-move 'next-line
))
3488 (defun org-table-fedit-move (command)
3489 "Move the cursor in the window showing the table.
3490 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3491 (let ((org-table-allow-automatic-line-recalculation nil
)
3492 (pos org-pos
) (win (selected-window)) p
)
3493 (select-window (get-buffer-window (marker-buffer org-pos
)))
3495 (call-interactively command
)
3496 (while (and (org-at-table-p)
3497 (org-at-table-hline-p))
3498 (call-interactively command
))
3499 (or (org-at-table-p) (goto-char p
))
3500 (move-marker pos
(point))
3501 (select-window win
)))
3503 (defun org-table-fedit-scroll (N)
3505 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3506 (scroll-other-window N
)))
3508 (defun org-table-fedit-scroll-down (N)
3510 (org-table-fedit-scroll (- N
)))
3512 (defvar org-table-rectangle-overlays nil
)
3514 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3515 "Add a new overlay."
3516 (let ((ov (make-overlay beg end
)))
3517 (overlay-put ov
'face
(or face
'secondary-selection
))
3518 (push ov org-table-rectangle-overlays
)))
3520 (defun org-table-highlight-rectangle (&optional beg end face
)
3521 "Highlight rectangular region in a table."
3522 (setq beg
(or beg
(point)) end
(or end
(point)))
3523 (let ((b (min beg end
))
3526 (and (boundp 'org-show-positions
)
3527 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3528 (goto-char (min beg end
))
3529 (setq l1
(org-current-line)
3530 c1
(org-table-current-column))
3531 (goto-char (max beg end
))
3532 (setq l2
(org-current-line)
3533 c2
(org-table-current-column))
3534 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3536 (beginning-of-line 1)
3537 (loop for line from l1 to l2 do
3538 (when (looking-at org-table-dataline-regexp
)
3539 (org-table-goto-column c1
)
3540 (skip-chars-backward "^|\n") (setq beg
(point))
3541 (org-table-goto-column c2
)
3542 (skip-chars-forward "^|\n") (setq end
(point))
3543 (org-table-add-rectangle-overlay beg end face
))
3544 (beginning-of-line 2))
3546 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3548 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3549 "Remove the rectangle overlays."
3550 (unless org-inhibit-highlight-removal
3551 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3552 (mapc 'delete-overlay org-table-rectangle-overlays
)
3553 (setq org-table-rectangle-overlays nil
)))
3555 (defvar org-table-coordinate-overlays nil
3556 "Collects the coordinate grid overlays, so that they can be removed.")
3557 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3559 (defun org-table-overlay-coordinates ()
3560 "Add overlays to the table at point, to show row/column coordinates."
3562 (mapc 'delete-overlay org-table-coordinate-overlays
)
3563 (setq org-table-coordinate-overlays nil
)
3565 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3566 (goto-char (org-table-begin))
3567 (while (org-at-table-p)
3568 (setq eol
(point-at-eol))
3569 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
3570 (push ov org-table-coordinate-overlays
)
3571 (setq hline
(looking-at org-table-hline-regexp
))
3572 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3573 (format "%4d" (setq id
(1+ id
)))))
3574 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3577 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3578 (setq beg
(1+ (match-beginning 0))
3580 s1
(concat "$" (int-to-string ic
))
3581 s2
(org-number-to-letters ic
)
3582 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3583 (setq ov
(make-overlay beg
(+ beg
(length str
))))
3584 (push ov org-table-coordinate-overlays
)
3585 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3586 (beginning-of-line 2)))))
3588 (defun org-table-toggle-coordinate-overlays ()
3589 "Toggle the display of Row/Column numbers in tables."
3591 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3592 (message "Row/Column number display turned %s"
3593 (if org-table-overlay-coordinates
"on" "off"))
3594 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3596 (unless org-table-overlay-coordinates
3597 (mapc 'delete-overlay org-table-coordinate-overlays
)
3598 (setq org-table-coordinate-overlays nil
)))
3600 (defun org-table-toggle-formula-debugger ()
3601 "Toggle the formula debugger in tables."
3603 (setq org-table-formula-debug
(not org-table-formula-debug
))
3604 (message "Formula debugging has been turned %s"
3605 (if org-table-formula-debug
"on" "off")))
3607 ;;; The orgtbl minor mode
3609 ;; Define a minor mode which can be used in other modes in order to
3610 ;; integrate the org-mode table editor.
3612 ;; This is really a hack, because the org-mode table editor uses several
3613 ;; keys which normally belong to the major mode, for example the TAB and
3614 ;; RET keys. Here is how it works: The minor mode defines all the keys
3615 ;; necessary to operate the table editor, but wraps the commands into a
3616 ;; function which tests if the cursor is currently inside a table. If that
3617 ;; is the case, the table editor command is executed. However, when any of
3618 ;; those keys is used outside a table, the function uses `key-binding' to
3619 ;; look up if the key has an associated command in another currently active
3620 ;; keymap (minor modes, major mode, global), and executes that command.
3621 ;; There might be problems if any of the keys used by the table editor is
3622 ;; otherwise used as a prefix key.
3624 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3625 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3626 ;; addresses this by checking explicitly for both bindings.
3628 ;; The optimized version (see variable `orgtbl-optimized') takes over
3629 ;; all keys which are bound to `self-insert-command' in the *global map*.
3630 ;; Some modes bind other commands to simple characters, for example
3631 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3632 ;; active, this binding is ignored inside tables and replaced with a
3633 ;; modified self-insert.
3636 (defvar orgtbl-mode-map
(make-keymap)
3637 "Keymap for `orgtbl-mode'.")
3640 (defun turn-on-orgtbl ()
3641 "Unconditionally turn on `orgtbl-mode'."
3644 (defvar org-old-auto-fill-inhibit-regexp nil
3645 "Local variable used by `orgtbl-mode'.")
3647 (defconst orgtbl-line-start-regexp
3648 "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\|TBLNAME\\):\\)"
3649 "Matches a line belonging to an orgtbl.")
3651 (defconst orgtbl-extra-font-lock-keywords
3652 (list (list (concat "^" orgtbl-line-start-regexp
".*")
3653 0 (quote 'org-table
) 'prepend
))
3654 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
3656 ;; Install it as a minor mode.
3657 (put 'orgtbl-mode
:included t
)
3658 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
3661 (define-minor-mode orgtbl-mode
3662 "The `org-mode' table editor as a minor mode for use in other modes."
3663 :lighter
" OrgTbl" :keymap orgtbl-mode-map
3664 (org-load-modules-maybe)
3667 ;; Exit without error, in case some hook functions calls this
3668 ;; by accident in org-mode.
3669 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
3671 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
3672 ;; Make sure we are first in minor-mode-map-alist
3673 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
3674 ;; FIXME: maybe it should use emulation-mode-map-alists?
3675 (and c
(setq minor-mode-map-alist
3676 (cons c
(delq c minor-mode-map-alist
)))))
3677 (org-set-local (quote org-table-may-need-update
) t
)
3678 (org-add-hook 'before-change-functions
'org-before-change-function
3680 (org-set-local 'org-old-auto-fill-inhibit-regexp
3681 auto-fill-inhibit-regexp
)
3682 (org-set-local 'auto-fill-inhibit-regexp
3683 (if auto-fill-inhibit-regexp
3684 (concat orgtbl-line-start-regexp
"\\|"
3685 auto-fill-inhibit-regexp
)
3686 orgtbl-line-start-regexp
))
3687 (add-to-invisibility-spec '(org-cwidth))
3688 (when (fboundp 'font-lock-add-keywords
)
3689 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
3690 (org-restart-font-lock))
3691 (easy-menu-add orgtbl-mode-menu
))
3693 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
3694 (org-table-cleanup-narrow-column-properties)
3695 (org-remove-from-invisibility-spec '(org-cwidth))
3696 (remove-hook 'before-change-functions
'org-before-change-function t
)
3697 (when (fboundp 'font-lock-remove-keywords
)
3698 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
3699 (org-restart-font-lock))
3700 (easy-menu-remove orgtbl-mode-menu
)
3701 (force-mode-line-update 'all
))))
3703 (defun org-table-cleanup-narrow-column-properties ()
3704 "Remove all properties related to narrow-column invisibility."
3706 (while (setq s
(text-property-any s
(point-max)
3707 'display org-narrow-column-arrow
))
3708 (remove-text-properties s
(1+ s
) '(display t
)))
3710 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
3711 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
3713 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
3714 (remove-text-properties s
(1+ s
) '(invisible t
)))))
3716 (defun orgtbl-make-binding (fun n
&rest keys
)
3717 "Create a function for binding in the table minor mode.
3718 FUN is the command to call inside a table. N is used to create a unique
3719 command name. KEYS are keys that should be checked in for a command
3720 to execute outside of tables."
3723 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
3725 (concat "In tables, run `" (symbol-name fun
) "'.\n"
3726 "Outside of tables, run the binding of `"
3727 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
3732 (list 'call-interactively
(list 'quote fun
))
3733 (list 'let
'(orgtbl-mode)
3734 (list 'call-interactively
3737 (list 'key-binding k
))
3739 '('orgtbl-error
))))))))
3741 (defun orgtbl-error ()
3742 "Error when there is no default binding for a table key."
3744 (error "This key has no function outside tables"))
3746 (defun orgtbl-setup ()
3747 "Setup orgtbl keymaps."
3750 '(([(meta shift left
)] org-table-delete-column
)
3751 ([(meta left
)] org-table-move-column-left
)
3752 ([(meta right
)] org-table-move-column-right
)
3753 ([(meta shift right
)] org-table-insert-column
)
3754 ([(meta shift up
)] org-table-kill-row
)
3755 ([(meta shift down
)] org-table-insert-row
)
3756 ([(meta up
)] org-table-move-row-up
)
3757 ([(meta down
)] org-table-move-row-down
)
3758 ("\C-c\C-w" org-table-cut-region
)
3759 ("\C-c\M-w" org-table-copy-region
)
3760 ("\C-c\C-y" org-table-paste-rectangle
)
3761 ("\C-c-" org-table-insert-hline
)
3762 ("\C-c}" org-table-toggle-coordinate-overlays
)
3763 ("\C-c{" org-table-toggle-formula-debugger
)
3764 ("\C-m" org-table-next-row
)
3765 ([(shift return
)] org-table-copy-down
)
3766 ("\C-c?" org-table-field-info
)
3767 ("\C-c " org-table-blank-field
)
3768 ("\C-c+" org-table-sum
)
3769 ("\C-c=" org-table-eval-formula
)
3770 ("\C-c'" org-table-edit-formulas
)
3771 ("\C-c`" org-table-edit-field
)
3772 ("\C-c*" org-table-recalculate
)
3773 ("\C-c^" org-table-sort-lines
)
3774 ("\M-a" org-table-beginning-of-field
)
3775 ("\M-e" org-table-end-of-field
)
3776 ([(control ?
#)] org-table-rotate-recalc-marks
)))
3778 (while (setq elt
(pop bindings
))
3779 (setq nfunc
(1+ nfunc
))
3780 (setq key
(org-key (car elt
))
3782 cmd
(orgtbl-make-binding fun nfunc key
))
3783 (org-defkey orgtbl-mode-map key cmd
))
3785 ;; Special treatment needed for TAB and RET
3786 (org-defkey orgtbl-mode-map
[(return)]
3787 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
3788 (org-defkey orgtbl-mode-map
"\C-m"
3789 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
3791 (org-defkey orgtbl-mode-map
[(tab)]
3792 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
3793 (org-defkey orgtbl-mode-map
"\C-i"
3794 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
3796 (org-defkey orgtbl-mode-map
[(shift tab
)]
3797 (orgtbl-make-binding 'org-table-previous-field
104
3798 [(shift tab
)] [(tab)] "\C-i"))
3801 (unless (featurep 'xemacs
)
3802 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
3803 (orgtbl-make-binding 'org-table-previous-field
107
3804 [S-iso-lefttab
] [backtab] [(shift tab)]
3807 (org-defkey orgtbl-mode-map [backtab]
3808 (orgtbl-make-binding 'org-table-previous-field
108
3809 [backtab] [S-iso-lefttab] [(shift tab)]
3812 (org-defkey orgtbl-mode-map "\M-\C-m"
3813 (orgtbl-make-binding 'org-table-wrap-region 105
3814 "\M-\C-m" [(meta return)]))
3815 (org-defkey orgtbl-mode-map [(meta return)]
3816 (orgtbl-make-binding 'org-table-wrap-region 106
3817 [(meta return)] "\M-\C-m"))
3819 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
3820 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
3822 (when orgtbl-optimized
3823 ;; If the user wants maximum table support, we need to hijack
3824 ;; some standard editing functions
3825 (org-remap orgtbl-mode-map
3826 'self-insert-command 'orgtbl-self-insert-command
3827 'delete-char 'org-delete-char
3828 'delete-backward-char 'org-delete-backward-char)
3829 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
3830 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
3832 ["Create or convert" org-table-create-or-convert-from-region
3833 :active (not (org-at-table-p)) :keys "C-c |" ]
3835 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
3836 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
3837 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
3838 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
3840 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
3841 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
3842 ["Copy Field from Above"
3843 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
3846 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
3847 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
3848 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
3849 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
3851 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
3852 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
3853 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
3854 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
3855 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
3857 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
3859 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
3860 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
3861 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
3862 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
3865 ["Insert table template" orgtbl-insert-radio-table
3866 (assq major-mode orgtbl-radio-table-templates)]
3867 ["Comment/uncomment table" orgtbl-toggle-comment t])
3869 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
3870 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
3871 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
3872 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
3873 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
3874 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
3875 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
3876 ["Sum Column/Rectangle" org-table-sum
3877 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
3878 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
3880 org-table-toggle-formula-debugger :active (org-at-table-p)
3882 :style toggle :selected org-table-formula-debug]
3883 ["Show Col/Row Numbers"
3884 org-table-toggle-coordinate-overlays :active (org-at-table-p)
3886 :style toggle :selected org-table-overlay-coordinates]
3890 (defun orgtbl-ctrl-c-ctrl-c (arg)
3891 "If the cursor is inside a table, realign the table.
3892 If it is a table to be sent away to a receiver, do it.
3893 With prefix arg, also recompute table."
3895 (let ((pos (point)) action consts-str consts cst const-str)
3897 (beginning-of-line 1)
3899 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
3900 ((looking-at "[ \t]*|") pos)
3901 ((looking-at "[ \t]*#\\+TBLFM:") 'recalc))))
3905 (org-table-maybe-eval-formula)
3907 (call-interactively 'org-table-recalculate)
3908 (org-table-maybe-recalculate-line))
3909 (call-interactively 'org-table-align)
3910 (when (orgtbl-send-table 'maybe)
3911 (run-hooks 'orgtbl-after-send-table-hook)))
3912 ((eq action 'recalc)
3914 (goto-char (point-min))
3915 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t)
3916 (setq const-str (substring-no-properties (match-string 1)))
3917 (setq consts (append consts (org-split-string const-str "[ \t]+")))
3920 (while (setq e (pop consts))
3921 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3922 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3923 (setq org-table-formula-constants-local cst)))))
3925 (beginning-of-line 1)
3926 (skip-chars-backward " \r\n\t")
3927 (if (org-at-table-p)
3928 (org-call-with-arg 'org-table-recalculate t))))
3929 (t (let (orgtbl-mode)
3930 (call-interactively (key-binding "\C-c\C-c")))))))
3932 (defun orgtbl-create-or-convert-from-region (arg)
3933 "Create table or convert region to table, if no conflicting binding.
3934 This installs the table binding `C-c |', but only if there is no
3935 conflicting binding to this key outside orgtbl-mode."
3937 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
3939 (call-interactively cmd)
3940 (call-interactively 'org-table-create-or-convert-from-region))))
3942 (defun orgtbl-tab (arg)
3943 "Justification and field motion for `orgtbl-mode'."
3945 (if arg (org-table-edit-field t)
3946 (org-table-justify-field-maybe)
3947 (org-table-next-field)))
3949 (defun orgtbl-ret ()
3950 "Justification and field motion for `orgtbl-mode'."
3954 (org-table-justify-field-maybe)
3955 (org-table-next-row)))
3957 (defun orgtbl-self-insert-command (N)
3958 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
3959 If the cursor is in a table looking at whitespace, the whitespace is
3960 overwritten, and the table is not marked as requiring realignment."
3962 (if (and (org-at-table-p)
3964 (and org-table-auto-blank-field
3965 (member last-command
3966 '(orgtbl-hijacker-command-100
3967 orgtbl-hijacker-command-101
3968 orgtbl-hijacker-command-102
3969 orgtbl-hijacker-command-103
3970 orgtbl-hijacker-command-104
3971 orgtbl-hijacker-command-105
3973 (org-table-blank-field))
3976 (looking-at "[^|\n]* +|"))
3977 (let (org-table-may-need-update)
3978 (goto-char (1- (match-end 0)))
3979 (delete-backward-char 1)
3980 (goto-char (match-beginning 0))
3981 (self-insert-command N))
3982 (setq org-table-may-need-update t)
3985 (cmd (or (key-binding
3986 (or (and (listp function-key-map)
3987 (setq a (assoc last-input-event function-key-map))
3989 (vector last-input-event)))
3990 'self-insert-command)))
3991 (call-interactively cmd)
3992 (if (and org-self-insert-cluster-for-undo
3993 (eq cmd 'self-insert-command))
3994 (if (not (eq last-command 'orgtbl-self-insert-command))
3995 (setq org-self-insert-command-undo-counter 1)
3996 (if (>= org-self-insert-command-undo-counter 20)
3997 (setq org-self-insert-command-undo-counter 1)
3998 (and (> org-self-insert-command-undo-counter 0)
4000 (not (cadr buffer-undo-list)) ; remove nil entry
4001 (setcdr buffer-undo-list (cddr buffer-undo-list)))
4002 (setq org-self-insert-command-undo-counter
4003 (1+ org-self-insert-command-undo-counter))))))))
4005 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
4006 "Regular expression matching exponentials as produced by calc.")
4008 (defun orgtbl-export (table target)
4010 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
4011 (lines (org-split-string table "[ \t]*\n[ \t]*"))
4012 org-table-last-alignment org-table-last-column-widths
4014 (if (not (fboundp func))
4015 (error "Cannot export orgtbl table to %s" target))
4016 (setq lines (org-table-clean-before-export lines))
4020 (if (string-match org-table-hline-regexp x)
4022 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4024 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
4026 (loop for i from (1- maxcol) downto 0 do
4027 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
4028 (setq column (delq nil column))
4029 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
4030 (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))
4031 (funcall func table nil)))
4033 (defun orgtbl-gather-send-defs ()
4034 "Gather a plist of :name, :transform, :params for each destination before
4037 (goto-char (org-table-begin))
4039 (beginning-of-line 0)
4040 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4041 (let ((name (org-no-properties (match-string 1)))
4042 (transform (intern (match-string 2)))
4043 (params (if (match-end 3)
4044 (read (concat "(" (match-string 3) ")")))))
4045 (push (list :name name :transform transform :params params)
4047 (beginning-of-line 0)))
4050 (defun orgtbl-send-replace-tbl (name txt)
4051 "Find and replace table NAME with TXT."
4053 (goto-char (point-min))
4054 (unless (re-search-forward
4055 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4056 (error "Don't know where to insert translated table"))
4057 (goto-char (match-beginning 0))
4058 (beginning-of-line 2)
4060 (let ((beg (point)))
4061 (unless (re-search-forward
4062 (concat "END RECEIVE ORGTBL +" name) nil t)
4063 (error "Cannot find end of insertion region"))
4064 (beginning-of-line 1)
4065 (delete-region beg (point))))
4069 (defun org-table-to-lisp (&optional txt)
4070 "Convert the table at point to a Lisp structure.
4071 The structure will be a list. Each item is either the symbol `hline'
4072 for a horizontal separator line, or a list of field values as strings.
4073 The table is taken from the parameter TXT, or from the buffer at point."
4075 (unless (org-at-table-p)
4076 (error "No table at point")))
4078 (buffer-substring-no-properties (org-table-begin)
4080 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4084 (if (string-match org-table-hline-regexp x)
4086 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4089 (defun orgtbl-send-table (&optional maybe)
4090 "Send a transformed version of this table to the receiver position.
4091 With argument MAYBE, fail quietly if no transformation is defined for
4095 (unless (org-at-table-p) (error "Not at a table"))
4096 ;; when non-interactive, we assume align has just happened.
4097 (when (interactive-p) (org-table-align))
4098 (let ((dests (orgtbl-gather-send-defs))
4099 (txt (buffer-substring-no-properties (org-table-begin)
4102 (unless dests (if maybe (throw 'exit nil)
4103 (error "Don't know how to transform this table")))
4104 (dolist (dest dests)
4105 (let* ((name (plist-get dest :name))
4106 (transform (plist-get dest :transform))
4107 (params (plist-get dest :params))
4108 (skip (plist-get params :skip))
4109 (skipcols (plist-get params :skipcols))
4111 (lines (org-table-clean-before-export
4113 (org-split-string txt "[ \t]*\n[ \t]*"))))
4114 (i0 (if org-table-clean-did-remove-column 2 1))
4117 (if (string-match org-table-hline-regexp x)
4119 (org-remove-by-index
4120 (org-split-string (org-trim x) "\\s-*|\\s-*")
4123 (fun (if (= i0 2) 'cdr 'identity))
4124 (org-table-last-alignment
4125 (org-remove-by-index (funcall fun org-table-last-alignment)
4127 (org-table-last-column-widths
4128 (org-remove-by-index (funcall fun org-table-last-column-widths)
4130 (txt (if (fboundp transform)
4131 (funcall transform table params)
4132 (error "No such transformation function %s" transform))))
4133 (orgtbl-send-replace-tbl name txt))
4134 (setq ntbl (1+ ntbl)))
4135 (message "Table converted and installed at %d receiver location%s"
4136 ntbl (if (> ntbl 1) "s" ""))
4141 (defun org-remove-by-index (list indices &optional i0)
4142 "Remove the elements in LIST with indices in INDICES.
4143 First element has index 0, or I0 if given."
4146 (if (integerp indices) (setq indices (list indices)))
4147 (setq i0 (1- (or i0 0)))
4148 (delq :rm (mapcar (lambda (x)
4150 (if (memq i0 indices) :rm x))
4153 (defun orgtbl-toggle-comment ()
4154 "Comment or uncomment the orgtbl at point."
4156 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4157 (re2 (concat "^" orgtbl-line-start-regexp))
4158 (commented (save-excursion (beginning-of-line 1)
4159 (cond ((looking-at re1) t)
4160 ((looking-at re2) nil)
4161 (t (error "Not at an org table")))))
4162 (re (if commented re1 re2))
4165 (beginning-of-line 1)
4166 (while (looking-at re) (beginning-of-line 0))
4167 (beginning-of-line 2)
4169 (while (looking-at re) (beginning-of-line 2))
4171 (comment-region beg end (if commented '(4) nil))))
4173 (defun orgtbl-insert-radio-table ()
4174 "Insert a radio table template appropriate for this major mode."
4176 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4179 (unless e (error "No radio table setup defined for %s" major-mode))
4180 (setq name (read-string "Table name: "))
4181 (while (string-match "%n" txt)
4182 (setq txt (replace-match name t t txt)))
4183 (or (bolp) (insert "\n"))
4188 ;; Dynamically bound input and output for table formatting.
4189 (defvar *orgtbl-table* nil
4190 "Carries the current table through formatting routines.")
4191 (defvar *orgtbl-rtn* nil
4192 "Formatting routines push the output lines here.")
4193 ;; Formatting parameters for the current table section.
4194 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4195 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4196 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4197 (defvar *orgtbl-fmt* nil "Format for each entry.")
4198 (defvar *orgtbl-efmt* nil "Format for numbers.")
4199 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4200 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4201 (defvar *orgtbl-lstart* nil "Text starting a row.")
4202 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4203 (defvar *orgtbl-lend* nil "Text ending a row.")
4204 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4206 (defsubst orgtbl-get-fmt (fmt i)
4207 "Retrieve the format from FMT corresponding to the Ith column."
4208 (if (and (not (functionp fmt)) (consp fmt))
4212 (defsubst orgtbl-apply-fmt (fmt &rest args)
4213 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4214 (cond ((functionp fmt) (apply fmt args))
4215 (fmt (apply 'format fmt args))
4219 (defsubst orgtbl-eval-str (str)
4220 "If STR is a function, evaluate it with no arguments."
4225 (defun orgtbl-format-line (line)
4226 "Format LINE as a table row."
4227 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4233 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4234 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4235 (orgtbl-apply-fmt efmt (match-string 1 f)
4238 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4239 *orgtbl-default-fmt*)
4242 (push (if *orgtbl-lfmt*
4243 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4244 (concat (orgtbl-eval-str *orgtbl-lstart*)
4245 (mapconcat 'identity line *orgtbl-sep*)
4246 (orgtbl-eval-str *orgtbl-lend*)))
4249 (defun orgtbl-format-section (section-stopper)
4250 "Format lines until the first occurrence of SECTION-STOPPER."
4253 (while (not (eq (car *orgtbl-table*) section-stopper))
4254 (if prevline (orgtbl-format-line prevline))
4255 (setq prevline (pop *orgtbl-table*)))
4256 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4257 (*orgtbl-lend* *orgtbl-llend*)
4258 (*orgtbl-lfmt* *orgtbl-llfmt*))
4259 (orgtbl-format-line prevline))))))
4261 (defun orgtbl-to-generic (table params)
4262 "Convert the orgtbl-mode TABLE to some other format.
4263 This generic routine can be used for many standard cases.
4264 TABLE is a list, each entry either the symbol `hline' for a horizontal
4265 separator line, or a list of fields for that line.
4266 PARAMS is a property list of parameters that can influence the conversion.
4267 For the generic converter, some parameters are obligatory: you need to
4268 specify either :lfmt, or all of (:lstart :lend :sep).
4270 Valid parameters are
4272 :splice When set to t, return only table body lines, don't wrap
4273 them into :tstart and :tend. Default is nil. When :splice
4274 is non-nil, this also means that the exporter should not look
4275 for and interpret header and footer sections.
4277 :hline String to be inserted on horizontal separation lines.
4278 May be nil to ignore hlines.
4280 :sep Separator between two fields
4281 :remove-nil-lines Do not include lines that evaluate to nil.
4284 Each in the following group may be either a string or a function
4285 of no arguments returning a string:
4286 :tstart String to start the table. Ignored when :splice is t.
4287 :tend String to end the table. Ignored when :splice is t.
4288 :lstart String to start a new table line.
4289 :llstart String to start the last table line, defaults to :lstart.
4290 :lend String to end a table line
4291 :llend String to end the last table line, defaults to :lend.
4293 Each in the following group may be a string, a function of one
4294 argument (the field or line) returning a string, or a plist
4295 mapping columns to either of the above:
4296 :lfmt Format for entire line, with enough %s to capture all fields.
4297 If this is present, :lstart, :lend, and :sep are ignored.
4298 :llfmt Format for the entire last line, defaults to :lfmt.
4299 :fmt A format to be used to wrap the field, should contain
4300 %s for the original field value. For example, to wrap
4301 everything in dollars, you could use :fmt \"$%s$\".
4302 This may also be a property list with column numbers and
4303 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4305 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4306 Same as above, specific for the header lines in the table.
4307 All lines before the first hline are treated as header.
4308 If any of these is not present, the data line value is used.
4310 This may be either a string or a function of two arguments:
4311 :efmt Use this format to print numbers with exponentials.
4312 The format should have %s twice for inserting mantissa
4313 and exponent, for example \"%s\\\\times10^{%s}\". This
4314 may also be a property list with column numbers and
4315 formats. :fmt will still be applied after :efmt.
4317 In addition to this, the parameters :skip and :skipcols are always handled
4318 directly by `orgtbl-send-table'. See manual."
4321 (let* ((splicep (plist-get params :splice))
4322 (hline (plist-get params :hline))
4323 (remove-nil-linesp (plist-get params :remove-nil-lines))
4324 (remove-newlines (plist-get params :remove-newlines))
4325 (*orgtbl-hline* hline)
4326 (*orgtbl-table* table)
4327 (*orgtbl-sep* (plist-get params :sep))
4328 (*orgtbl-efmt* (plist-get params :efmt))
4329 (*orgtbl-lstart* (plist-get params :lstart))
4330 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4331 (*orgtbl-lend* (plist-get params :lend))
4332 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4333 (*orgtbl-lfmt* (plist-get params :lfmt))
4334 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4335 (*orgtbl-fmt* (plist-get params :fmt))
4340 (when (plist-member params :tstart)
4341 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4342 (if tstart (push tstart *orgtbl-rtn*)))))
4344 ;; Do we have a heading section? If so, format it and handle the
4346 (if (and (not splicep)
4347 (or (consp (car *orgtbl-table*))
4348 (consp (nth 1 *orgtbl-table*)))
4349 (memq 'hline (cdr *orgtbl-table*)))
4351 (when (eq 'hline (car *orgtbl-table*))
4352 ;; there is a hline before the first data line
4353 (and hline (push hline *orgtbl-rtn*))
4354 (pop *orgtbl-table*))
4355 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4357 (*orgtbl-llstart* (or (plist-get params :hllstart)
4359 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4360 (*orgtbl-llend* (or (plist-get params :hllend)
4361 (plist-get params :hlend) *orgtbl-llend*))
4362 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4363 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4364 (plist-get params :hlfmt) *orgtbl-llfmt*))
4365 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4366 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4367 (orgtbl-format-section 'hline))
4368 (if hline (push hline *orgtbl-rtn*))
4369 (pop *orgtbl-table*)))
4371 ;; Now format the main section.
4372 (orgtbl-format-section nil)
4375 (when (plist-member params :tend)
4376 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4377 (if tend (push tend *orgtbl-rtn*)))))
4379 (mapconcat (if remove-newlines
4381 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4383 (nreverse (if remove-nil-linesp
4384 (remq nil *orgtbl-rtn*)
4385 *orgtbl-rtn*)) "\n")))
4387 (defun orgtbl-to-tsv (table params)
4388 "Convert the orgtbl-mode table to TAB separated material."
4389 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4390 (defun orgtbl-to-csv (table params)
4391 "Convert the orgtbl-mode table to CSV material.
4392 This does take care of the proper quoting of fields with comma or quotes."
4393 (orgtbl-to-generic table (org-combine-plists
4394 '(:sep "," :fmt org-quote-csv-field)
4397 (defun orgtbl-to-latex (table params)
4398 "Convert the orgtbl-mode TABLE to LaTeX.
4399 TABLE is a list, each entry either the symbol `hline' for a horizontal
4400 separator line, or a list of fields for that line.
4401 PARAMS is a property list of parameters that can influence the conversion.
4402 Supports all parameters from `orgtbl-to-generic'. Most important for
4405 :splice When set to t, return only table body lines, don't wrap
4406 them into a tabular environment. Default is nil.
4408 :fmt A format to be used to wrap the field, should contain %s for the
4409 original field value. For example, to wrap everything in dollars,
4410 use :fmt \"$%s$\". This may also be a property list with column
4411 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4412 The format may also be a function that formats its one argument.
4414 :efmt Format for transforming numbers with exponentials. The format
4415 should have %s twice for inserting mantissa and exponent, for
4416 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4417 This may also be a property list with column numbers and formats.
4418 The format may also be a function that formats its two arguments.
4420 :llend If you find too much space below the last line of a table,
4421 pass a value of \"\" for :llend to suppress the final \\\\.
4423 The general parameters :skip and :skipcols have already been applied when
4424 this function is called."
4425 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4426 org-table-last-alignment ""))
4429 :tstart (concat "\\begin{tabular}{" alignment "}")
4430 :tend "\\end{tabular}"
4431 :lstart "" :lend " \\\\" :sep " & "
4432 :efmt "%s\\,(%s)" :hline "\\hline")))
4433 (orgtbl-to-generic table (org-combine-plists params2 params))))
4435 (defun orgtbl-to-html (table params)
4436 "Convert the orgtbl-mode TABLE to HTML.
4437 TABLE is a list, each entry either the symbol `hline' for a horizontal
4438 separator line, or a list of fields for that line.
4439 PARAMS is a property list of parameters that can influence the conversion.
4440 Currently this function recognizes the following parameters:
4442 :splice When set to t, return only table body lines, don't wrap
4443 them into a <table> environment. Default is nil.
4445 The general parameters :skip and :skipcols have already been applied when
4446 this function is called. The function does *not* use `orgtbl-to-generic',
4447 so you cannot specify parameters for it."
4448 (let* ((splicep (plist-get params :splice))
4449 (html-table-tag org-export-html-table-tag)
4451 ;; Just call the formatter we already have
4452 ;; We need to make text lines for it, so put the fields back together.
4453 (setq html (org-format-org-table-html
4458 (concat "| " (mapconcat 'org-html-expand x " | ") " |")))
4461 (if (string-match "\n+\\'" html)
4462 (setq html (replace-match "" t t html)))
4465 (defun orgtbl-to-texinfo (table params)
4466 "Convert the orgtbl-mode TABLE to TeXInfo.
4467 TABLE is a list, each entry either the symbol `hline' for a horizontal
4468 separator line, or a list of fields for that line.
4469 PARAMS is a property list of parameters that can influence the conversion.
4470 Supports all parameters from `orgtbl-to-generic'. Most important for
4473 :splice nil/t When set to t, return only table body lines, don't wrap
4474 them into a multitable environment. Default is nil.
4476 :fmt fmt A format to be used to wrap the field, should contain
4477 %s for the original field value. For example, to wrap
4478 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4479 This may also be a property list with column numbers and
4480 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4481 Each format also may be a function that formats its one
4484 :cf \"f1 f2..\" The column fractions for the table. By default these
4485 are computed automatically from the width of the columns
4488 The general parameters :skip and :skipcols have already been applied when
4489 this function is called."
4490 (let* ((total (float (apply '+ org-table-last-column-widths)))
4491 (colfrac (or (plist-get params :cf)
4493 (lambda (x) (format "%.3f" (/ (float x) total)))
4494 org-table-last-column-widths " ")))
4497 :tstart (concat "@multitable @columnfractions " colfrac)
4498 :tend "@end multitable"
4499 :lstart "@item " :lend "" :sep " @tab "
4500 :hlstart "@headitem ")))
4501 (orgtbl-to-generic table (org-combine-plists params2 params))))
4503 (defun orgtbl-to-orgtbl (table params)
4504 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4505 Useful when slicing one table into many. The :hline, :sep,
4506 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4507 and :tend suppress strings without splicing; they can be set to
4508 provide ORGTBL directives for the generated table."
4512 :tstart nil :tend nil
4517 (params (org-combine-plists params2 params)))
4518 (orgtbl-to-generic table params)))
4520 (defun org-table-get-remote-range (name-or-id form)
4521 "Get a field value or a list of values in a range from table at ID.
4523 NAME-OR-ID may be the name of a table in the current file as set by
4524 a \"#+TBLNAME:\" directive. The first table following this line
4525 will then be used. Alternatively, it may be an ID referring to
4526 any entry, also in a different file. In this case, the first table
4527 in that entry will be referenced.
4528 FORM is a field or range descriptor like \"@2$3\" or or \"B3\" or
4529 \"@I$2..@II$2\". All the references must be absolute, not relative.
4531 The return value is either a single string for a single field, or a
4532 list of the fields in the rectangle ."
4535 org-table-column-names org-table-column-name-regexp
4536 org-table-local-parameters org-table-named-field-locations
4537 org-table-current-line-types org-table-current-begin-line
4538 org-table-current-begin-pos org-table-dlines
4539 org-table-current-ncol
4540 org-table-hlines org-table-last-alignment
4541 org-table-last-column-widths org-table-last-alignment
4542 org-table-last-column-widths tbeg
4544 (setq form (org-table-convert-refs-to-rc form))
4549 (goto-char (point-min))
4550 (if (re-search-forward
4551 (concat "^[ \t]*#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4553 (setq buffer (current-buffer) loc (match-beginning 0))
4554 (setq id-loc (org-id-find name-or-id 'marker))
4555 (unless (and id-loc (markerp id-loc))
4556 (error "Can't find remote table \"%s\"" name-or-id))
4557 (setq buffer (marker-buffer id-loc)
4558 loc (marker-position id-loc))
4559 (move-marker id-loc nil)))
4560 (with-current-buffer buffer
4566 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4567 (not (match-beginning 1)))
4568 (error "Cannot find a table at NAME or ID %s" name-or-id))
4569 (setq tbeg (point-at-bol))
4570 (org-table-get-specials)
4571 (setq form (org-table-formula-substitute-names form))
4572 (if (and (string-match org-table-range-regexp form)
4573 (> (length (match-string 0 form)) 1))
4575 (org-table-get-range (match-string 0 form) tbeg 1))
4578 (provide 'org-table)
4580 ;; arch-tag: 4d21cfdd-0268-440a-84b0-09237a0fe0ef
4582 ;;; org-table.el ends here