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
)
495 (format "^ *\\| *\t *\\| \\{%d,\\}" separator
))
496 (t (error "This should not happen"))))
497 (while (re-search-forward re end t
)
498 (replace-match "| " t t
)))
502 (defun org-table-import (file arg
)
503 "Import FILE as a table.
504 The file is assumed to be tab-separated. Such files can be produced by most
505 spreadsheet and database applications. If no tabs (at least one per line)
506 are found, lines will be split on whitespace into fields."
508 (or (bolp) (newline))
511 (insert-file-contents file
)
512 (org-table-convert-region beg
(+ (point) (- (point-max) pm
)) arg
)))
515 (defvar org-table-last-alignment
)
516 (defvar org-table-last-column-widths
)
517 (defun org-table-export (&optional file format
)
518 "Export table to a file, with configurable format.
519 Such a file can be imported into a spreadsheet program like Excel.
520 FILE can be the output file name. If not given, it will be taken from
521 a TABLE_EXPORT_FILE property in the current entry or higher up in the
522 hierarchy, or the user will be prompted for a file name.
523 FORMAT can be an export format, of the same kind as it used when
524 `orgtbl-mode' sends a table in a different format. The default format can
525 be found in the variable `org-table-export-default-format', but the function
526 first checks if there is an export format specified in a TABLE_EXPORT_FORMAT
527 property, locally or anywhere up in the hierarchy."
529 (unless (org-at-table-p)
530 (error "No table at point"))
532 (org-table-align) ;; make sure we have everything we need
533 (let* ((beg (org-table-begin))
534 (end (org-table-end))
535 (txt (buffer-substring-no-properties beg end
))
536 (file (or file
(org-entry-get beg
"TABLE_EXPORT_FILE" t
)))
538 (org-entry-get beg
"TABLE_EXPORT_FORMAT" t
)))
541 (setq file
(read-file-name "Export table to: "))
542 (unless (or (not (file-exists-p file
))
543 (y-or-n-p (format "Overwrite file %s? " file
)))
545 (if (file-directory-p file
)
546 (error "This is a directory path, not a file"))
547 (if (and (buffer-file-name)
548 (equal (file-truename file
)
549 (file-truename (buffer-file-name))))
550 (error "Please specify a file name that is different from current"))
552 (setq deffmt-readable org-table-export-default-format
)
553 (while (string-match "\t" deffmt-readable
)
554 (setq deffmt-readable
(replace-match "\\t" t t deffmt-readable
)))
555 (while (string-match "\n" deffmt-readable
)
556 (setq deffmt-readable
(replace-match "\\n" t t deffmt-readable
)))
557 (setq format
(org-completing-read
559 '("orgtbl-to-tsv" "orgtbl-to-csv"
560 "orgtbl-to-latex" "orgtbl-to-html"
561 "orgtbl-to-generic" "orgtbl-to-texinfo"
562 "orgtbl-to-orgtbl") nil nil
564 (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format
)
565 (let* ((transform (intern (match-string 1 format
)))
566 (params (if (match-end 2)
567 (read (concat "(" (match-string 2 format
) ")"))))
568 (skip (plist-get params
:skip
))
569 (skipcols (plist-get params
:skipcols
))
570 (lines (nthcdr (or skip
0) (org-split-string txt
"[ \t]*\n[ \t]*")))
571 (lines (org-table-clean-before-export lines
))
572 (i0 (if org-table-clean-did-remove-column
2 1))
575 (if (string-match org-table-hline-regexp x
)
578 (org-split-string (org-trim x
) "\\s-*|\\s-*")
581 (fun (if (= i0
2) 'cdr
'identity
))
582 (org-table-last-alignment
583 (org-remove-by-index (funcall fun org-table-last-alignment
)
585 (org-table-last-column-widths
586 (org-remove-by-index (funcall fun org-table-last-column-widths
)
589 (unless (fboundp transform
)
590 (error "No such transformation function %s" transform
))
591 (setq txt
(funcall transform table params
))
593 (with-current-buffer (find-file-noselect file
)
594 (setq buf
(current-buffer))
600 (message "Export done."))
601 (error "TABLE_EXPORT_FORMAT invalid"))))
603 (defvar org-table-aligned-begin-marker
(make-marker)
604 "Marker at the beginning of the table last aligned.
605 Used to check if cursor still is in that table, to minimize realignment.")
606 (defvar org-table-aligned-end-marker
(make-marker)
607 "Marker at the end of the table last aligned.
608 Used to check if cursor still is in that table, to minimize realignment.")
609 (defvar org-table-last-alignment nil
610 "List of flags for flushright alignment, from the last re-alignment.
611 This is being used to correctly align a single field after TAB or RET.")
612 (defvar org-table-last-column-widths nil
613 "List of max width of fields in each column.
614 This is being used to correctly align a single field after TAB or RET.")
615 (defvar org-table-formula-debug nil
616 "Non-nil means debug table formulas.
617 When nil, simply write \"#ERROR\" in corrupted fields.")
618 (make-variable-buffer-local 'org-table-formula-debug
)
619 (defvar org-table-overlay-coordinates nil
620 "Overlay coordinates after each align of a table.")
621 (make-variable-buffer-local 'org-table-overlay-coordinates
)
623 (defvar org-last-recalc-line nil
)
624 (defvar org-table-do-narrow t
) ; for dynamic scoping
625 (defconst org-narrow-column-arrow
"=>"
626 "Used as display property in narrowed table columns.")
628 (defun org-table-align ()
629 "Align the table at point by aligning all vertical bars."
633 (beg (org-table-begin))
634 (end (org-table-end))
635 ;; Current cursor position
636 (linepos (org-current-line))
637 (colpos (org-table-current-column))
638 (winstart (window-start))
639 (winstartline (org-current-line (min winstart
(1- (point-max)))))
640 lines
(new "") lengths l typenums ty fields maxfields i
648 (make-string sp2 ?\
) "%%%s%ds" (make-string sp1 ?\
) "|"))
650 (make-string sp2 ?-
) "%s" (make-string sp1 ?-
) "+"))
651 emptystrings links dates emph raise narrow
652 falign falign1 fmax f1 len c e space
)
654 (remove-text-properties beg end
'(org-cwidth t org-dwidth t display t
))
655 ;; Check if we have links or dates
657 (setq links
(re-search-forward org-bracket-link-regexp end t
))
659 (setq emph
(and org-hide-emphasis-markers
660 (re-search-forward org-emph-re end t
)))
662 (setq raise
(and org-use-sub-superscripts
663 (re-search-forward org-match-substring-regexp end t
)))
665 (setq dates
(and org-display-custom-times
666 (re-search-forward org-ts-regexp-both end t
)))
667 ;; Make sure the link properties are right
668 (when links
(goto-char beg
) (while (org-activate-bracket-links end
)))
669 ;; Make sure the date properties are right
670 (when dates
(goto-char beg
) (while (org-activate-dates end
)))
671 (when emph
(goto-char beg
) (while (org-do-emphasis-faces end
)))
672 (when raise
(goto-char beg
) (while (org-raise-scripts end
)))
674 ;; Check if we are narrowing any columns
676 (setq narrow
(and org-table-do-narrow
677 org-format-transports-properties-p
678 (re-search-forward "<[lrc]?[0-9]+>" end t
)))
680 (setq falign
(re-search-forward "<[lrc][0-9]*>" end t
))
683 (setq lines
(org-split-string
684 (buffer-substring beg end
) "\n"))
685 ;; Store the indentation of the first line
686 (if (string-match "^ *" (car lines
))
687 (setq indent
(make-string (- (match-end 0) (match-beginning 0)) ?\
)))
688 ;; Mark the hlines by setting the corresponding element to nil
689 ;; At the same time, we remove trailing space.
690 (setq lines
(mapcar (lambda (l)
691 (if (string-match "^ *|-" l
)
693 (if (string-match "[ \t]+$" l
)
694 (substring l
0 (match-beginning 0))
697 ;; Get the data fields by splitting the lines.
700 (org-split-string l
" *| *"))
701 (delq nil
(copy-sequence lines
))))
702 ;; How many fields in the longest line?
704 (setq maxfields
(apply 'max
(mapcar 'length fields
)))
706 (kill-region beg end
)
707 (org-table-create org-table-default-size
)
708 (error "Empty table - created default table")))
709 ;; A list of empty strings to fill any short rows on output
710 (setq emptystrings
(make-list maxfields
""))
711 ;; Check for special formatting.
713 (while (< (setq i
(1+ i
)) maxfields
) ;; Loop over all columns
714 (setq column
(mapcar (lambda (x) (or (nth i x
) "")) fields
))
715 ;; Check if there is an explicit width specified
717 (when (or narrow falign
)
718 (setq c column fmax nil falign1 nil
)
721 (when (and (stringp e
) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e
))
722 (if (match-end 1) (setq falign1
(match-string 1 e
)))
723 (if (and org-table-do-narrow
(match-end 2))
724 (setq fmax
(string-to-number (match-string 2 e
)) c nil
))))
725 ;; Find fields that are wider than fmax, and shorten them
727 (loop for xx in column do
728 (when (and (stringp xx
)
729 (> (org-string-width xx
) fmax
))
730 (org-add-props xx nil
732 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx
))))
733 (setq f1
(min fmax
(or (string-match org-bracket-link-regexp xx
) fmax
)))
735 (error "Cannot narrow field starting with wide link \"%s\""
736 (match-string 0 xx
)))
737 (add-text-properties f1
(length xx
) (list 'org-cwidth t
) xx
)
738 (add-text-properties (- f1
2) f1
739 (list 'display org-narrow-column-arrow
)
741 ;; Get the maximum width for each column
742 (push (apply 'max
(or fmax
1) 1 (mapcar 'org-string-width column
))
744 ;; Get the fraction of numbers, to decide about alignment of the column
746 (push (equal (downcase falign1
) "r") typenums
)
747 (setq cnt
0 frac
0.0)
748 (loop for x in column do
751 (setq frac
( / (+ (* frac cnt
)
752 (if (string-match org-table-number-regexp x
) 1 0))
753 (setq cnt
(1+ cnt
))))))
754 (push (>= frac org-table-number-fraction
) typenums
)))
755 (setq lengths
(nreverse lengths
) typenums
(nreverse typenums
))
757 ;; Store the alignment of this table, for later editing of single fields
758 (setq org-table-last-alignment typenums
759 org-table-last-column-widths lengths
)
761 ;; With invisible characters, `format' does not get the field width right
762 ;; So we need to make these fields wide by hand.
763 (when (or links emph raise
)
764 (loop for i from
0 upto
(1- maxfields
) do
765 (setq len
(nth i lengths
))
766 (loop for j from
0 upto
(1- (length fields
)) do
767 (setq c
(nthcdr i
(car (nthcdr j fields
))))
768 (if (and (stringp (car c
))
769 (or (text-property-any 0 (length (car c
))
770 'invisible
'org-link
(car c
))
771 (text-property-any 0 (length (car c
))
772 'org-dwidth t
(car c
)))
773 (< (org-string-width (car c
)) len
))
775 (setq space
(make-string (- len
(org-string-width (car c
))) ?\
))
776 (setcar c
(if (nth i typenums
)
777 (concat space
(car c
))
778 (concat (car c
) space
))))))))
780 ;; Compute the formats needed for output of the table
781 (setq rfmt
(concat indent
"|") hfmt
(concat indent
"|"))
782 (while (setq l
(pop lengths
))
783 (setq ty
(if (pop typenums
) "" "-")) ; number types flushright
784 (setq rfmt
(concat rfmt
(format rfmt1 ty l
))
785 hfmt
(concat hfmt
(format hfmt1
(make-string l ?-
)))))
786 (setq rfmt
(concat rfmt
"\n")
787 hfmt
(concat (substring hfmt
0 -
1) "|\n"))
791 (if l
(apply 'format rfmt
792 (append (pop fields
) emptystrings
))
795 (if (equal (char-before) ?
\n)
796 ;; This hack is for org-indent, to force redisplay of the
797 ;; line prefix of the first line. Apparently the redisplay
798 ;; is tied to the newline, which is, I think, a bug.
799 ;; To force this redisplay, we remove and re-insert the
800 ;; newline, so that the redisplay engine thinks it belongs
801 ;; to the changed text.
803 (backward-delete-char 1)
805 (move-marker org-table-aligned-begin-marker
(point))
807 ;; Replace the old one
808 (delete-region (point) end
)
809 (move-marker end nil
)
810 (move-marker org-table-aligned-end-marker
(point))
811 (when (and orgtbl-mode
(not (org-mode-p)))
812 (goto-char org-table-aligned-begin-marker
)
813 (while (org-hide-wide-columns org-table-aligned-end-marker
)))
814 ;; Try to move to the old location
815 (org-goto-line winstartline
)
816 (setq winstart
(point-at-bol))
817 (org-goto-line linepos
)
818 (set-window-start (selected-window) winstart
'noforce
)
819 (org-table-goto-column colpos
)
820 (and org-table-overlay-coordinates
(org-table-overlay-coordinates))
821 (setq org-table-may-need-update nil
)
824 (defun org-table-begin (&optional table-type
)
825 "Find the beginning of the table and return its position.
826 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
828 (if (not (re-search-backward
829 (if table-type org-table-any-border-regexp
830 org-table-border-regexp
)
832 (progn (goto-char (point-min)) (point))
833 (goto-char (match-beginning 0))
834 (beginning-of-line 2)
837 (defun org-table-end (&optional table-type
)
838 "Find the end of the table and return its position.
839 With argument TABLE-TYPE, go to the end of a table.el-type table."
841 (if (not (re-search-forward
842 (if table-type org-table-any-border-regexp
843 org-table-border-regexp
)
845 (goto-char (point-max))
846 (goto-char (match-beginning 0)))
849 (defun org-table-justify-field-maybe (&optional new
)
850 "Justify the current field, text to left, number to right.
851 Optional argument NEW may specify text to replace the current field content."
853 ((and (not new
) org-table-may-need-update
)) ; Realignment will happen anyway
854 ((org-at-table-hline-p))
856 (or (not (equal (marker-buffer org-table-aligned-begin-marker
)
858 (< (point) org-table-aligned-begin-marker
)
859 (>= (point) org-table-aligned-end-marker
)))
860 ;; This is not the same table, force a full re-align
861 (setq org-table-may-need-update t
))
862 (t ;; realign the current field, based on previous full realign
863 (let* ((pos (point)) s
864 (col (org-table-current-column))
865 (num (if (> col
0) (nth (1- col
) org-table-last-alignment
)))
868 (skip-chars-backward "^|\n")
869 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
871 (setq s
(match-string 1)
873 l
(max 1 (- (match-end 0) (match-beginning 0) 3))
874 e
(not (= (match-beginning 2) (match-end 2))))
875 (setq f
(format (if num
" %%%ds %s" " %%-%ds %s")
876 l
(if e
"|" (setq org-table-may-need-update t
) ""))
879 (if (<= (length new
) l
) ;; FIXME: length -> str-width?
880 (setq n
(format f new
))
881 (setq n
(concat new
"|") org-table-may-need-update t
)))
882 (if (equal (string-to-char n
) ?-
) (setq n
(concat " " n
)))
884 (let (org-table-may-need-update)
885 (replace-match n t t
))))
886 (setq org-table-may-need-update t
))
889 (defun org-table-next-field ()
890 "Go to the next field in the current table, creating new lines as needed.
891 Before doing so, re-align the table if necessary."
893 (org-table-maybe-eval-formula)
894 (org-table-maybe-recalculate-line)
895 (if (and org-table-automatic-realign
896 org-table-may-need-update
)
898 (let ((end (org-table-end)))
899 (if (org-at-table-hline-p)
903 (re-search-forward "|" end
)
904 (if (looking-at "[ \t]*$")
905 (re-search-forward "|" end
))
906 (if (and (looking-at "-")
907 org-table-tab-jumps-over-hlines
908 (re-search-forward "^[ \t]*|\\([^-]\\)" end t
))
909 (goto-char (match-beginning 1)))
912 (beginning-of-line 0)
913 (org-table-insert-row 'below
))
914 (if (looking-at " ") (forward-char 1))))
916 (org-table-insert-row 'below
)))))
918 (defun org-table-previous-field ()
919 "Go to the previous field in the table.
920 Before doing so, re-align the table if necessary."
922 (org-table-justify-field-maybe)
923 (org-table-maybe-recalculate-line)
924 (if (and org-table-automatic-realign
925 org-table-may-need-update
)
927 (if (org-at-table-hline-p)
931 (re-search-backward "|" (org-table-begin))
932 (re-search-backward "|" (org-table-begin)))
933 (error (error "Cannot move to previous table field")))
934 (while (looking-at "|\\(-\\|[ \t]*$\\)")
935 (re-search-backward "|" (org-table-begin)))
936 (if (looking-at "| ?")
937 (goto-char (match-end 0))))
939 (defun org-table-beginning-of-field (&optional n
)
940 "Move to the end of the current table field.
941 If already at or after the end, move to the end of the next table field.
942 With numeric argument N, move N-1 fields forward first."
947 (org-table-previous-field))
948 (if (not (re-search-backward "|" (point-at-bol 0) t
))
949 (error "No more table fields before the current")
950 (goto-char (match-end 0))
951 (and (looking-at " ") (forward-char 1)))
952 (if (>= (point) pos
) (org-table-beginning-of-field 2))))
954 (defun org-table-end-of-field (&optional n
)
955 "Move to the beginning of the current table field.
956 If already at or before the beginning, move to the beginning of the
958 With numeric argument N, move N-1 fields backward first."
963 (org-table-next-field))
964 (when (re-search-forward "|" (point-at-eol 1) t
)
966 (skip-chars-backward " ")
967 (if (and (equal (char-before (point)) ?|
) (looking-at " "))
969 (if (<= (point) pos
) (org-table-end-of-field 2))))
971 (defun org-table-next-row ()
972 "Go to the next row (same column) in the current table.
973 Before doing so, re-align the table if necessary."
975 (org-table-maybe-eval-formula)
976 (org-table-maybe-recalculate-line)
977 (if (or (looking-at "[ \t]*$")
978 (save-excursion (skip-chars-backward " \t") (bolp)))
980 (if (and org-table-automatic-realign
981 org-table-may-need-update
)
983 (let ((col (org-table-current-column)))
984 (beginning-of-line 2)
985 (if (or (not (org-at-table-p))
986 (org-at-table-hline-p))
988 (beginning-of-line 0)
989 (org-table-insert-row 'below
)))
990 (org-table-goto-column col
)
991 (skip-chars-backward "^|\n\r")
992 (if (looking-at " ") (forward-char 1)))))
994 (defun org-table-copy-down (n)
995 "Copy a field down in the current column.
996 If the field at the cursor is empty, copy into it the content of
997 the nearest non-empty field above. With argument N, use the Nth
998 non-empty field. If the current field is not empty, it is copied
999 down to the next row, and the cursor is moved with it.
1000 Therefore, repeating this command causes the column to be filled
1002 If the variable `org-table-copy-increment' is non-nil and the
1003 field is an integer or a timestamp, it will be incremented while
1004 copying. In the case of a timestamp, increment by one day."
1006 (let* ((colpos (org-table-current-column))
1007 (col (current-column))
1008 (field (org-table-get-field))
1009 (non-empty (string-match "[^ \t]" field
))
1010 (beg (org-table-begin))
1013 (org-table-check-inside-data-field)
1016 (setq txt
(org-trim field
))
1017 (org-table-next-row)
1018 (org-table-blank-field))
1022 (while (progn (beginning-of-line 1)
1023 (re-search-backward org-table-dataline-regexp
1025 (org-table-goto-column colpos t
)
1026 (if (and (looking-at
1027 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
1028 (<= (setq n
(1- n
)) 0))
1029 (throw 'exit
(match-string 1))))))))
1032 (if (and org-table-copy-increment
1033 (not (equal orig-n
0))
1034 (string-match "^[0-9]+$" txt
)
1035 (< (string-to-number txt
) 100000000))
1036 (setq txt
(format "%d" (+ (string-to-number txt
) 1))))
1038 (org-move-to-column col
)
1039 (if (and org-table-copy-increment
(org-at-timestamp-p t
))
1040 (org-timestamp-up-day)
1041 (org-table-maybe-recalculate-line))
1043 (org-move-to-column col
))
1044 (error "No non-empty field found"))))
1046 (defun org-table-check-inside-data-field ()
1047 "Is point inside a table data field?
1048 I.e. not on a hline or before the first or after the last column?
1049 This actually throws an error, so it aborts the current command."
1050 (if (or (not (org-at-table-p))
1051 (= (org-table-current-column) 0)
1052 (org-at-table-hline-p)
1053 (looking-at "[ \t]*$"))
1054 (error "Not in table data field")))
1056 (defvar org-table-clip nil
1057 "Clipboard for table regions.")
1059 (defun org-table-get (line column
)
1060 "Get the field in table line LINE, column COLUMN.
1061 If LINE is larger than the number of data lines in the table, the function
1062 returns nil. However, if COLUMN is too large, we will simply return an
1064 If LINE is nil, use the current line.
1065 If column is nil, use the current column."
1066 (setq column
(or column
(org-table-current-column)))
1068 (and (or (not line
) (org-table-goto-line line
))
1069 (org-trim (org-table-get-field column
)))))
1071 (defun org-table-put (line column value
&optional align
)
1072 "Put VALUE into line LINE, column COLUMN.
1073 When ALIGN is set, also realign the table."
1074 (setq column
(or column
(org-table-current-column)))
1075 (prog1 (save-excursion
1076 (and (or (not line
) (org-table-goto-line line
))
1077 (progn (org-table-goto-column column nil
'force
) t
)
1078 (org-table-get-field column value
)))
1079 (and align
(org-table-align))))
1081 (defun org-table-current-line ()
1082 "Return the index of the current data line."
1083 (let ((pos (point)) (end (org-table-end)) (cnt 0))
1085 (goto-char (org-table-begin))
1086 (while (and (re-search-forward org-table-dataline-regexp end t
)
1088 (< (point-at-eol) pos
))))
1091 (defun org-table-goto-line (N)
1092 "Go to the Nth data line in the current table.
1093 Return t when the line exists, nil if it does not exist."
1094 (goto-char (org-table-begin))
1095 (let ((end (org-table-end)) (cnt 0))
1096 (while (and (re-search-forward org-table-dataline-regexp end t
)
1097 (< (setq cnt
(1+ cnt
)) N
)))
1100 (defun org-table-blank-field ()
1101 "Blank the current table field or active region."
1103 (org-table-check-inside-data-field)
1104 (if (and (interactive-p) (org-region-active-p))
1105 (let (org-table-clip)
1106 (org-table-cut-region (region-beginning) (region-end)))
1107 (skip-chars-backward "^|")
1109 (if (looking-at "|[^|\n]+")
1110 (let* ((pos (match-beginning 0))
1111 (match (match-string 0))
1112 (len (org-string-width match
)))
1113 (replace-match (concat "|" (make-string (1- len
) ?\
)))
1114 (goto-char (+ 2 pos
))
1115 (substring match
1)))))
1117 (defun org-table-get-field (&optional n replace
)
1118 "Return the value of the field in column N of current row.
1119 N defaults to current field.
1120 If REPLACE is a string, replace field with this value. The return value
1121 is always the old value."
1122 (and n
(org-table-goto-column n
))
1123 (skip-chars-backward "^|\n")
1125 (if (looking-at "|[^|\r\n]*")
1126 (let* ((pos (match-beginning 0))
1127 (val (buffer-substring (1+ pos
) (match-end 0))))
1129 (replace-match (concat "|" replace
) t t
))
1130 (goto-char (min (point-at-eol) (+ 2 pos
)))
1132 (forward-char 1) ""))
1134 (defun org-table-field-info (arg)
1135 "Show info about the current field, and highlight any reference at point."
1137 (org-table-get-specials)
1139 (let* ((pos (point))
1140 (col (org-table-current-column))
1141 (cname (car (rassoc (int-to-string col
) org-table-column-names
)))
1142 (name (car (rassoc (list (org-current-line) col
)
1143 org-table-named-field-locations
)))
1144 (eql (org-table-expand-lhs-ranges
1147 (cons (org-table-formula-handle-lastrc (car e
)) (cdr e
)))
1148 (org-table-get-stored-formulas))))
1149 (dline (org-table-current-dline))
1150 (ref (format "@%d$%d" dline col
))
1151 (ref1 (org-table-convert-refs-to-an ref
))
1152 (fequation (or (assoc name eql
) (assoc ref eql
)))
1153 (cequation (assoc (int-to-string col
) eql
))
1154 (eqn (or fequation cequation
)))
1155 (if (and eqn
(get-text-property 0 :orig-eqn
(car eqn
)))
1156 (setq eqn
(get-text-property 0 :orig-eqn
(car eqn
))))
1159 (org-table-show-reference 'local
)
1161 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
1163 (if cname
(concat " or $" cname
) "")
1165 (if name
(concat " or $" name
) "")
1166 ;; FIXME: formula info not correct if special table line
1168 (concat ", formula: "
1169 (org-table-formula-to-user
1171 (if (string-match "^[$@]"(car eqn
)) "" "$")
1172 (car eqn
) "=" (cdr eqn
))))
1175 (defun org-table-current-column ()
1176 "Find out which column we are in."
1178 (if (interactive-p) (org-table-check-inside-data-field))
1180 (let ((cnt 0) (pos (point)))
1181 (beginning-of-line 1)
1182 (while (search-forward "|" pos t
)
1183 (setq cnt
(1+ cnt
)))
1184 (if (interactive-p) (message "In table column %d" cnt
))
1187 (defun org-table-current-dline ()
1188 "Find out what table data line we are in.
1189 Only data lines count for this."
1191 (if (interactive-p) (org-table-check-inside-data-field))
1193 (let ((cnt 0) (pos (point)))
1194 (goto-char (org-table-begin))
1195 (while (<= (point) pos
)
1196 (if (looking-at org-table-dataline-regexp
) (setq cnt
(1+ cnt
)))
1197 (beginning-of-line 2))
1198 (if (interactive-p) (message "This is table line %d" cnt
))
1201 (defun org-table-goto-column (n &optional on-delim force
)
1202 "Move the cursor to the Nth column in the current table line.
1203 With optional argument ON-DELIM, stop with point before the left delimiter
1205 If there are less than N fields, just go to after the last delimiter.
1206 However, when FORCE is non-nil, create new columns if necessary."
1208 (beginning-of-line 1)
1210 (while (and (> (setq n
(1- n
)) -
1)
1211 (or (search-forward "|" (point-at-eol) t
)
1213 (progn (end-of-line 1)
1214 (skip-chars-backward "^|")
1217 (when (and force
(not (looking-at ".*|")))
1218 (save-excursion (end-of-line 1) (insert " | ")))
1221 (if (looking-at " ") (forward-char 1)))))
1223 (defun org-table-insert-column ()
1224 "Insert a new column into the table."
1226 (if (not (org-at-table-p))
1227 (error "Not at a table"))
1228 (org-table-find-dataline)
1229 (let* ((col (max 1 (org-table-current-column)))
1230 (beg (org-table-begin))
1231 (end (org-table-end))
1232 ;; Current cursor position
1233 (linepos (org-current-line))
1236 (while (< (point) end
)
1237 (if (org-at-table-hline-p)
1239 (org-table-goto-column col t
)
1241 (beginning-of-line 2))
1242 (move-marker end nil
)
1243 (org-goto-line linepos
)
1244 (org-table-goto-column colpos
)
1246 (when (or (not org-table-fix-formulas-confirm
)
1247 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1248 (org-table-fix-formulas "$" nil
(1- col
) 1)
1249 (org-table-fix-formulas "$LR" nil
(1- col
) 1))))
1251 (defun org-table-find-dataline ()
1252 "Find a data line in the current table, which is needed for column commands."
1253 (if (and (org-at-table-p)
1254 (not (org-at-table-hline-p)))
1256 (let ((col (current-column))
1257 (end (org-table-end)))
1258 (org-move-to-column col
)
1259 (while (and (< (point) end
)
1260 (or (not (= (current-column) col
))
1261 (org-at-table-hline-p)))
1262 (beginning-of-line 2)
1263 (org-move-to-column col
))
1264 (if (and (org-at-table-p)
1265 (not (org-at-table-hline-p)))
1268 "Please position cursor in a data line for column operations")))))
1270 (defun org-table-line-to-dline (line &optional above
)
1271 "Turn a buffer line number into a data line number.
1272 If there is no data line in this line, return nil.
1273 If there is no matchin dline (most likely te refrence was a hline), the
1274 first dline below it is used. When ABOVE is non-nil, the one above is used."
1276 (let ((ll (length org-table-dlines
))
1282 (if (<= (aref org-table-dlines i
) line
)
1287 (if (>= (aref org-table-dlines i
) line
)
1292 (defun org-table-delete-column ()
1293 "Delete a column from the table."
1295 (if (not (org-at-table-p))
1296 (error "Not at a table"))
1297 (org-table-find-dataline)
1298 (org-table-check-inside-data-field)
1299 (let* ((col (org-table-current-column))
1300 (beg (org-table-begin))
1301 (end (org-table-end))
1302 ;; Current cursor position
1303 (linepos (org-current-line))
1306 (while (< (point) end
)
1307 (if (org-at-table-hline-p)
1309 (org-table-goto-column col t
)
1310 (and (looking-at "|[^|\n]+|")
1311 (replace-match "|")))
1312 (beginning-of-line 2))
1313 (move-marker end nil
)
1314 (org-goto-line linepos
)
1315 (org-table-goto-column colpos
)
1317 (when (or (not org-table-fix-formulas-confirm
)
1318 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1319 (org-table-fix-formulas "$" (list (cons (number-to-string col
) "INVALID"))
1321 (org-table-fix-formulas "$LR" (list (cons (number-to-string col
) "INVALID"))
1324 (defun org-table-move-column-right ()
1325 "Move column to the right."
1327 (org-table-move-column nil
))
1328 (defun org-table-move-column-left ()
1329 "Move column to the left."
1331 (org-table-move-column 'left
))
1333 (defun org-table-move-column (&optional left
)
1334 "Move the current column to the right. With arg LEFT, move to the left."
1336 (if (not (org-at-table-p))
1337 (error "Not at a table"))
1338 (org-table-find-dataline)
1339 (org-table-check-inside-data-field)
1340 (let* ((col (org-table-current-column))
1341 (col1 (if left
(1- col
) col
))
1342 (beg (org-table-begin))
1343 (end (org-table-end))
1344 ;; Current cursor position
1345 (linepos (org-current-line))
1346 (colpos (if left
(1- col
) (1+ col
))))
1347 (if (and left
(= col
1))
1348 (error "Cannot move column further left"))
1349 (if (and (not left
) (looking-at "[^|\n]*|[^|\n]*$"))
1350 (error "Cannot move column further right"))
1352 (while (< (point) end
)
1353 (if (org-at-table-hline-p)
1355 (org-table-goto-column col1 t
)
1356 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
1357 (replace-match "|\\2|\\1|")))
1358 (beginning-of-line 2))
1359 (move-marker end nil
)
1360 (org-goto-line linepos
)
1361 (org-table-goto-column colpos
)
1363 (when (or (not org-table-fix-formulas-confirm
)
1364 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1365 (org-table-fix-formulas
1366 "$" (list (cons (number-to-string col
) (number-to-string colpos
))
1367 (cons (number-to-string colpos
) (number-to-string col
))))
1368 (org-table-fix-formulas
1369 "$LR" (list (cons (number-to-string col
) (number-to-string colpos
))
1370 (cons (number-to-string colpos
) (number-to-string col
)))))))
1372 (defun org-table-move-row-down ()
1373 "Move table row down."
1375 (org-table-move-row nil
))
1376 (defun org-table-move-row-up ()
1377 "Move table row up."
1379 (org-table-move-row 'up
))
1381 (defun org-table-move-row (&optional up
)
1382 "Move the current table line down. With arg UP, move it up."
1384 (let* ((col (current-column))
1386 (hline1p (save-excursion (beginning-of-line 1)
1387 (looking-at org-table-hline-regexp
)))
1388 (dline1 (org-table-current-dline))
1389 (dline2 (+ dline1
(if up -
1 1)))
1392 (beginning-of-line tonew
)
1393 (unless (org-at-table-p)
1395 (error "Cannot move row further"))
1396 (setq hline2p
(looking-at org-table-hline-regexp
))
1398 (beginning-of-line 1)
1400 (setq txt
(buffer-substring (point) (1+ (point-at-eol))))
1401 (delete-region (point) (1+ (point-at-eol)))
1402 (beginning-of-line tonew
)
1404 (beginning-of-line 0)
1405 (org-move-to-column col
)
1406 (unless (or hline1p hline2p
1407 (not (or (not org-table-fix-formulas-confirm
)
1408 (funcall org-table-fix-formulas-confirm
1409 "Fix formulas? "))))
1410 (org-table-fix-formulas
1411 "@" (list (cons (number-to-string dline1
) (number-to-string dline2
))
1412 (cons (number-to-string dline2
) (number-to-string dline1
)))))))
1414 (defun org-table-insert-row (&optional arg
)
1415 "Insert a new row above the current line into the table.
1416 With prefix ARG, insert below the current line."
1418 (if (not (org-at-table-p))
1419 (error "Not at a table"))
1420 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
1421 (new (org-table-clean-line line
)))
1422 ;; Fix the first field if necessary
1423 (if (string-match "^[ \t]*| *[#$] *|" line
)
1424 (setq new
(replace-match (match-string 0 line
) t t new
)))
1425 (beginning-of-line (if arg
2 1))
1426 (let (org-table-may-need-update) (insert-before-markers new
"\n"))
1427 (beginning-of-line 0)
1428 (re-search-forward "| ?" (point-at-eol) t
)
1429 (and (or org-table-may-need-update org-table-overlay-coordinates
)
1431 (when (or (not org-table-fix-formulas-confirm
)
1432 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1433 (org-table-fix-formulas "@" nil
(1- (org-table-current-dline)) 1))))
1435 (defun org-table-insert-hline (&optional above
)
1436 "Insert a horizontal-line below the current line into the table.
1437 With prefix ABOVE, insert above the current line."
1439 (if (not (org-at-table-p))
1440 (error "Not at a table"))
1441 (when (eobp) (insert "\n") (backward-char 1))
1442 (if (not (string-match "|[ \t]*$" (org-current-line-string)))
1444 (let ((line (org-table-clean-line
1445 (buffer-substring (point-at-bol) (point-at-eol))))
1446 (col (current-column)))
1447 (while (string-match "|\\( +\\)|" line
)
1448 (setq line
(replace-match
1449 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
1450 ?-
) "|") t t line
)))
1451 (and (string-match "\\+" line
) (setq line
(replace-match "|" t t line
)))
1452 (beginning-of-line (if above
1 2))
1454 (beginning-of-line (if above
1 -
1))
1455 (org-move-to-column col
)
1456 (and org-table-overlay-coordinates
(org-table-align))))
1458 (defun org-table-hline-and-move (&optional same-column
)
1459 "Insert a hline and move to the row below that line."
1461 (let ((col (org-table-current-column)))
1462 (org-table-maybe-eval-formula)
1463 (org-table-maybe-recalculate-line)
1464 (org-table-insert-hline)
1466 (if (looking-at "\n[ \t]*|-")
1467 (progn (insert "\n|") (org-table-align))
1468 (org-table-next-field))
1469 (if same-column
(org-table-goto-column col
))))
1471 (defun org-table-clean-line (s)
1472 "Convert a table line S into a string with only \"|\" and space.
1473 In particular, this does handle wide and invisible characters."
1474 (if (string-match "^[ \t]*|-" s
)
1475 ;; It's a hline, just map the characters
1476 (setq s
(mapconcat (lambda (x) (if (member x
'(?| ?
+)) "|" " ")) s
""))
1477 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s
)
1478 (setq s
(replace-match
1479 (concat "|" (make-string (org-string-width (match-string 1 s
))
1484 (defun org-table-kill-row ()
1485 "Delete the current row or horizontal line from the table."
1487 (if (not (org-at-table-p))
1488 (error "Not at a table"))
1489 (let ((col (current-column))
1490 (dline (org-table-current-dline)))
1491 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
1492 (if (not (org-at-table-p)) (beginning-of-line 0))
1493 (org-move-to-column col
)
1494 (when (or (not org-table-fix-formulas-confirm
)
1495 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
1496 (org-table-fix-formulas "@" (list (cons (number-to-string dline
) "INVALID"))
1499 (defun org-table-sort-lines (with-case &optional sorting-type
)
1500 "Sort table lines according to the column at point.
1502 The position of point indicates the column to be used for
1503 sorting, and the range of lines is the range between the nearest
1504 horizontal separator lines, or the entire table of no such lines
1505 exist. If point is before the first column, you will be prompted
1506 for the sorting column. If there is an active region, the mark
1507 specifies the first line and the sorting column, while point
1508 should be in the last line to be included into the sorting.
1510 The command then prompts for the sorting type which can be
1511 alphabetically, numerically, or by time (as given in a time stamp
1512 in the field). Sorting in reverse order is also possible.
1514 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
1516 If SORTING-TYPE is specified when this function is called from a Lisp
1517 program, no prompting will take place. SORTING-TYPE must be a character,
1518 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
1519 should be done in reverse order."
1521 (let* ((thisline (org-current-line))
1522 (thiscol (org-table-current-column))
1523 beg end bcol ecol tend tbeg column lns pos
)
1524 (when (equal thiscol
0)
1528 (read-string "Use column N for sorting: ")))
1530 (org-table-goto-column thiscol
))
1531 (org-table-check-inside-data-field)
1532 (if (org-region-active-p)
1534 (setq beg
(region-beginning) end
(region-end))
1536 (setq column
(org-table-current-column)
1539 (setq end
(point-at-bol 2)))
1540 (setq column
(org-table-current-column)
1542 tbeg
(org-table-begin)
1543 tend
(org-table-end))
1544 (if (re-search-backward org-table-hline-regexp tbeg t
)
1545 (setq beg
(point-at-bol 2))
1547 (setq beg
(point-at-bol 1)))
1549 (if (re-search-forward org-table-hline-regexp tend t
)
1550 (setq end
(point-at-bol 1))
1552 (setq end
(point-at-bol))))
1553 (setq beg
(move-marker (make-marker) beg
)
1554 end
(move-marker (make-marker) end
))
1557 (org-table-goto-column column
)
1558 (skip-chars-backward "^|")
1559 (setq bcol
(current-column))
1560 (org-table-goto-column (1+ column
))
1561 (skip-chars-backward "^|")
1562 (setq ecol
(1- (current-column)))
1563 (org-table-goto-column column
)
1564 (setq lns
(mapcar (lambda(x) (cons
1565 (org-sort-remove-invisible
1567 (org-split-string x
"[ \t]*|[ \t]*")))
1569 (org-split-string (buffer-substring beg end
) "\n")))
1570 (setq lns
(org-do-sort lns
"Table" with-case sorting-type
))
1571 (delete-region beg end
)
1572 (move-marker beg nil
)
1573 (move-marker end nil
)
1574 (insert (mapconcat 'cdr lns
"\n") "\n")
1575 (org-goto-line thisline
)
1576 (org-table-goto-column thiscol
)
1577 (message "%d lines sorted, based on column %d" (length lns
) column
)))
1580 (defun org-table-cut-region (beg end
)
1581 "Copy region in table to the clipboard and blank all relevant fields.
1582 If there is no active region, use just the field at point."
1584 (if (org-region-active-p) (region-beginning) (point))
1585 (if (org-region-active-p) (region-end) (point))))
1586 (org-table-copy-region beg end
'cut
))
1588 (defun org-table-copy-region (beg end
&optional cut
)
1589 "Copy rectangular region in table to clipboard.
1590 A special clipboard is used which can only be accessed
1591 with `org-table-paste-rectangle'."
1593 (if (org-region-active-p) (region-beginning) (point))
1594 (if (org-region-active-p) (region-end) (point))
1595 current-prefix-arg
))
1596 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
1598 (rpl (if cut
" " nil
)))
1600 (org-table-check-inside-data-field)
1601 (setq l01
(org-current-line)
1602 c01
(org-table-current-column))
1604 (org-table-check-inside-data-field)
1605 (setq l02
(org-current-line)
1606 c02
(org-table-current-column))
1607 (setq l1
(min l01 l02
) l2
(max l01 l02
)
1608 c1
(min c01 c02
) c2
(max c01 c02
))
1612 (if (> l1 l2
) (throw 'exit t
))
1614 (if (org-at-table-hline-p) (throw 'nextline
(setq l1
(1+ l1
))))
1615 (setq cols nil ic1 c1 ic2 c2
)
1616 (while (< ic1
(1+ ic2
))
1617 (push (org-table-get-field ic1 rpl
) cols
)
1618 (setq ic1
(1+ ic1
)))
1619 (push (nreverse cols
) region
)
1620 (setq l1
(1+ l1
)))))
1621 (setq org-table-clip
(nreverse region
))
1622 (if cut
(org-table-align))
1625 (defun org-table-paste-rectangle ()
1626 "Paste a rectangular region into a table.
1627 The upper right corner ends up in the current field. All involved fields
1628 will be overwritten. If the rectangle does not fit into the present table,
1629 the table is enlarged as needed. The process ignores horizontal separator
1632 (unless (and org-table-clip
(listp org-table-clip
))
1633 (error "First cut/copy a region to paste!"))
1634 (org-table-check-inside-data-field)
1635 (let* ((clip org-table-clip
)
1636 (line (org-current-line))
1637 (col (org-table-current-column))
1638 (org-enable-table-editor t
)
1639 (org-table-automatic-realign nil
)
1641 (while (setq cols
(pop clip
))
1642 (while (org-at-table-hline-p) (beginning-of-line 2))
1643 (if (not (org-at-table-p))
1644 (progn (end-of-line 0) (org-table-next-field)))
1646 (while (setq field
(pop cols
))
1647 (org-table-goto-column c nil
'force
)
1648 (org-table-get-field nil field
)
1650 (beginning-of-line 2))
1651 (org-goto-line line
)
1652 (org-table-goto-column col
)
1655 (defun org-table-convert ()
1656 "Convert from `org-mode' table to table.el and back.
1657 Obviously, this only works within limits. When an Org-mode table is
1658 converted to table.el, all horizontal separator lines get lost, because
1659 table.el uses these as cell boundaries and has no notion of horizontal lines.
1660 A table.el table can be converted to an Org-mode table only if it does not
1661 do row or column spanning. Multiline cells will become multiple cells.
1662 Beware, Org-mode does not test if the table can be successfully converted - it
1663 blindly applies a recipe that works for simple tables."
1666 (if (org-at-table.el-p
)
1667 ;; convert to Org-mode table
1668 (let ((beg (move-marker (make-marker) (org-table-begin t
)))
1669 (end (move-marker (make-marker) (org-table-end t
))))
1670 (table-unrecognize-region beg end
)
1672 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t
)
1675 (if (org-at-table-p)
1676 ;; convert to table.el table
1677 (let ((beg (move-marker (make-marker) (org-table-begin)))
1678 (end (move-marker (make-marker) (org-table-end))))
1679 ;; first, get rid of all horizontal lines
1681 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t
)
1683 ;; insert a hline before first
1685 (org-table-insert-hline 'above
)
1686 (beginning-of-line -
1)
1687 ;; insert a hline after each line
1688 (while (progn (beginning-of-line 3) (< (point) end
))
1689 (org-table-insert-hline))
1691 (setq end
(move-marker end
(org-table-end)))
1692 ;; replace "+" at beginning and ending of hlines
1693 (while (re-search-forward "^\\([ \t]*\\)|-" end t
)
1694 (replace-match "\\1+-"))
1696 (while (re-search-forward "-|[ \t]*$" end t
)
1697 (replace-match "-+"))
1700 (defun org-table-wrap-region (arg)
1701 "Wrap several fields in a column like a paragraph.
1702 This is useful if you'd like to spread the contents of a field over several
1703 lines, in order to keep the table compact.
1705 If there is an active region, and both point and mark are in the same column,
1706 the text in the column is wrapped to minimum width for the given number of
1707 lines. Generally, this makes the table more compact. A prefix ARG may be
1708 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
1709 formats the selected text to two lines. If the region was longer than two
1710 lines, the remaining lines remain empty. A negative prefix argument reduces
1711 the current number of lines by that amount. The wrapped text is pasted back
1712 into the table. If you formatted it to more lines than it was before, fields
1713 further down in the table get overwritten - so you might need to make space in
1716 If there is no region, the current field is split at the cursor position and
1717 the text fragment to the right of the cursor is prepended to the field one
1720 If there is no region, but you specify a prefix ARG, the current field gets
1721 blank, and the content is appended to the field above."
1723 (org-table-check-inside-data-field)
1724 (if (org-region-active-p)
1725 ;; There is a region: fill as a paragraph
1726 (let* ((beg (region-beginning))
1727 (cline (save-excursion (goto-char beg
) (org-current-line)))
1728 (ccol (save-excursion (goto-char beg
) (org-table-current-column)))
1730 (org-table-cut-region (region-beginning) (region-end))
1731 (if (> (length (car org-table-clip
)) 1)
1732 (error "Region must be limited to single column"))
1733 (setq nlines
(if arg
1735 (+ (length org-table-clip
) arg
)
1737 (length org-table-clip
)))
1738 (setq org-table-clip
1739 (mapcar 'list
(org-wrap (mapconcat 'car org-table-clip
" ")
1741 (org-goto-line cline
)
1742 (org-table-goto-column ccol
)
1743 (org-table-paste-rectangle))
1744 ;; No region, split the current field at point
1745 (unless (org-get-alist-option org-M-RET-may-split-line
'table
)
1746 (skip-chars-forward "^\r\n|"))
1748 ;; combine with field above
1749 (let ((s (org-table-blank-field))
1750 (col (org-table-current-column)))
1751 (beginning-of-line 0)
1752 (while (org-at-table-hline-p) (beginning-of-line 0))
1753 (org-table-goto-column col
)
1754 (skip-chars-forward "^|")
1755 (skip-chars-backward " ")
1756 (insert " " (org-trim s
))
1759 (if (looking-at "\\([^|]+\\)+|")
1760 (let ((s (match-string 1)))
1761 (replace-match " |")
1762 (goto-char (match-beginning 0))
1763 (org-table-next-row)
1764 (insert (org-trim s
) " ")
1766 (org-table-next-row)))))
1768 (defvar org-field-marker nil
)
1770 (defun org-table-edit-field (arg)
1771 "Edit table field in a different window.
1772 This is mainly useful for fields that contain hidden parts.
1773 When called with a \\[universal-argument] prefix, just make the full field visible so that
1774 it can be edited in place."
1777 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
1778 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
1779 (remove-text-properties b e
'(org-cwidth t invisible t
1780 display t intangible t
))
1781 (if (and (boundp 'font-lock-mode
) font-lock-mode
)
1782 (font-lock-fontify-block)))
1783 (let ((pos (move-marker (make-marker) (point)))
1784 (field (org-table-get-field))
1785 (cw (current-window-configuration))
1787 (org-switch-to-buffer-other-window "*Org tmp*")
1789 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
1790 (let ((org-inhibit-startup t
)) (org-mode))
1791 (goto-char (setq p
(point-max)))
1792 (insert (org-trim field
))
1793 (remove-text-properties p
(point-max)
1794 '(invisible t org-cwidth t display t
1797 (org-set-local 'org-finish-function
'org-table-finish-edit-field
)
1798 (org-set-local 'org-window-configuration cw
)
1799 (org-set-local 'org-field-marker pos
)
1800 (message "Edit and finish with C-c C-c"))))
1802 (defun org-table-finish-edit-field ()
1803 "Finish editing a table data field.
1804 Remove all newline characters, insert the result into the table, realign
1805 the table and kill the editing buffer."
1806 (let ((pos org-field-marker
)
1807 (cw org-window-configuration
)
1808 (cb (current-buffer))
1810 (goto-char (point-min))
1811 (while (re-search-forward "^#.*\n?" nil t
) (replace-match ""))
1812 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t
)
1813 (replace-match " "))
1814 (setq text
(org-trim (buffer-string)))
1815 (set-window-configuration cw
)
1817 (select-window (get-buffer-window (marker-buffer pos
)))
1819 (move-marker pos nil
)
1820 (org-table-check-inside-data-field)
1821 (org-table-get-field nil text
)
1823 (message "New field value inserted")))
1825 (defvar org-timecnt
) ; dynamically scoped parameter
1827 (defun org-table-sum (&optional beg end nlast
)
1828 "Sum numbers in region of current table column.
1829 The result will be displayed in the echo area, and will be available
1830 as kill to be inserted with \\[yank].
1832 If there is an active region, it is interpreted as a rectangle and all
1833 numbers in that rectangle will be summed. If there is no active
1834 region and point is located in a table column, sum all numbers in that
1837 If at least one number looks like a time HH:MM or HH:MM:SS, all other
1838 numbers are assumed to be times as well (in decimal hours) and the
1839 numbers are added as such.
1841 If NLAST is a number, only the NLAST fields will actually be summed."
1844 (let (col (org-timecnt 0) diff h m s org-table-clip
)
1846 ((and beg end
)) ; beg and end given explicitly
1847 ((org-region-active-p)
1848 (setq beg
(region-beginning) end
(region-end)))
1850 (setq col
(org-table-current-column))
1851 (goto-char (org-table-begin))
1852 (unless (re-search-forward "^[ \t]*|[^-]" nil t
)
1853 (error "No table data"))
1854 (org-table-goto-column col
)
1856 (goto-char (org-table-end))
1857 (unless (re-search-backward "^[ \t]*|[^-]" nil t
)
1858 (error "No table data"))
1859 (org-table-goto-column col
)
1860 (setq end
(point))))
1861 (let* ((items (apply 'append
(org-table-copy-region beg end
)))
1862 (items1 (cond ((not nlast
) items
)
1863 ((>= nlast
(length items
)) items
)
1864 (t (setq items
(reverse items
))
1865 (setcdr (nthcdr (1- nlast
) items
) nil
)
1867 (numbers (delq nil
(mapcar 'org-table-get-number-for-summing
1869 (res (apply '+ numbers
))
1870 (sres (if (= org-timecnt
0)
1871 (number-to-string res
)
1872 (setq diff
(* 3600 res
)
1873 h
(floor (/ diff
3600)) diff
(mod diff
3600)
1874 m
(floor (/ diff
60)) diff
(mod diff
60)
1876 (format "%d:%02d:%02d" h m s
))))
1880 (substitute-command-keys
1881 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
1882 (length numbers
) sres
))))
1885 (defun org-table-get-number-for-summing (s)
1887 (if (string-match "^ *|? *" s
)
1888 (setq s
(replace-match "" nil nil s
)))
1889 (if (string-match " *|? *$" s
)
1890 (setq s
(replace-match "" nil nil s
)))
1891 (setq n
(string-to-number s
))
1893 ((and (string-match "0" s
)
1894 (string-match "\\`[-+ \t0.edED]+\\'" s
)) 0)
1895 ((string-match "\\`[ \t]+\\'" s
) nil
)
1896 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s
)
1897 (let ((h (string-to-number (or (match-string 1 s
) "0")))
1898 (m (string-to-number (or (match-string 2 s
) "0")))
1899 (s (string-to-number (or (match-string 4 s
) "0"))))
1900 (if (boundp 'org-timecnt
) (setq org-timecnt
(1+ org-timecnt
)))
1901 (* 1.0 (+ h
(/ m
60.0) (/ s
3600.0)))))
1905 (defun org-table-current-field-formula (&optional key noerror
)
1906 "Return the formula active for the current field.
1907 Assumes that specials are in place.
1908 If KEY is given, return the key to this formula.
1909 Otherwise return the formula preceded with \"=\" or \":=\"."
1910 (let* ((name (car (rassoc (list (org-current-line)
1911 (org-table-current-column))
1912 org-table-named-field-locations
)))
1913 (col (org-table-current-column))
1914 (scol (int-to-string col
))
1915 (ref (format "@%d$%d" (org-table-current-dline) col
))
1916 (stored-list (org-table-get-stored-formulas noerror
))
1917 (ass (or (assoc name stored-list
)
1918 (assoc ref stored-list
)
1919 (assoc scol stored-list
))))
1922 (if ass
(concat (if (string-match "^[0-9]+$" (car ass
)) "=" ":=")
1925 (defun org-table-get-formula (&optional equation named
)
1926 "Read a formula from the minibuffer, offer stored formula as default.
1927 When NAMED is non-nil, look for a named equation."
1928 (let* ((stored-list (org-table-get-stored-formulas))
1929 (name (car (rassoc (list (org-current-line)
1930 (org-table-current-column))
1931 org-table-named-field-locations
)))
1932 (ref (format "@%d$%d" (org-table-current-dline)
1933 (org-table-current-column)))
1934 (refass (assoc ref stored-list
))
1935 (nameass (assoc name stored-list
))
1937 (if (and name
(not (string-match "^LR[0-9]+$" name
)))
1940 (int-to-string (org-table-current-column))))
1941 (dummy (and (or nameass refass
) (not named
)
1942 (not (y-or-n-p "Replace existing field formula with column formula? " ))
1944 (name (or name ref
))
1945 (org-table-may-need-update nil
)
1946 (stored (cdr (assoc scol stored-list
)))
1948 ((and stored equation
(string-match "^ *=? *$" equation
))
1952 (t (org-table-formula-from-user
1954 (org-table-formula-to-user
1955 (format "%s formula %s%s="
1956 (if named
"Field" "Column")
1957 (if (member (string-to-char scol
) '(?$ ?
@)) "" "$")
1959 (if stored
(org-table-formula-to-user stored
) "")
1960 'org-table-formula-history
1963 (when (not (string-match "\\S-" eq
))
1965 (setq stored-list
(delq (assoc scol stored-list
) stored-list
))
1966 (org-table-store-formulas stored-list
)
1967 (error "Formula removed"))
1968 (if (string-match "^ *=?" eq
) (setq eq
(replace-match "" t t eq
)))
1969 (if (string-match " *$" eq
) (setq eq
(replace-match "" t t eq
)))
1970 (if (and name
(not named
))
1971 ;; We set the column equation, delete the named one.
1972 (setq stored-list
(delq (assoc name stored-list
) stored-list
)
1975 (setcdr (assoc scol stored-list
) eq
)
1976 (setq stored-list
(cons (cons scol eq
) stored-list
)))
1977 (if (or mustsave
(not (equal stored eq
)))
1978 (org-table-store-formulas stored-list
))
1981 (defun org-table-store-formulas (alist)
1982 "Store the list of formulas below the current table."
1983 (setq alist
(sort alist
'org-table-formula-less-p
))
1985 (goto-char (org-table-end))
1986 (if (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM:\\(.*\n?\\)")
1988 ;; don't overwrite TBLFM, we might use text properties to store stuff
1989 (goto-char (match-beginning 2))
1990 (delete-region (match-beginning 2) (match-end 0)))
1991 (org-indent-line-function)
1992 (insert "#+TBLFM:"))
1994 (mapconcat (lambda (x)
1996 (if (equal (string-to-char (car x
)) ?
@) "" "$")
1997 (car x
) "=" (cdr x
)))
2001 (defsubst org-table-formula-make-cmp-string
(a)
2002 (when (string-match "\\`$>" a
)
2003 ;; Fake a high number to make sure this is sorted at the end.
2004 (setq a
(org-table-formula-handle-lastrc a
))
2005 (setq a
(format "$%d" (+ 10000 (string-to-number (substring a
1))))))
2006 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a
)
2008 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a
))) "")
2009 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a
))) "")
2010 (if (match-end 5) (concat "@@" (match-string 5 a
))))))
2012 (defun org-table-formula-less-p (a b
)
2013 "Compare two formulas for sorting."
2014 (let ((as (org-table-formula-make-cmp-string (car a
)))
2015 (bs (org-table-formula-make-cmp-string (car b
))))
2016 (and as bs
(string< as bs
))))
2018 (defun org-table-get-stored-formulas (&optional noerror
)
2019 "Return an alist with the stored formulas directly after current table."
2021 (let (scol eq eq-alist strings string seen
)
2023 (goto-char (org-table-end))
2024 (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
2025 (setq strings
(org-split-string (org-match-string-no-properties 2)
2027 (while (setq string
(pop strings
))
2028 (when (string-match "\\`\\(@[-+I>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|>\\(?:[-+][0-9]+\\)?\\)\\) *= *\\(.*[^ \t]\\)" string
)
2029 (setq scol
(if (match-end 2)
2030 (match-string 2 string
)
2031 (match-string 1 string
))
2032 scol
(if (= (string-to-char scol
) ?
>) (concat "$" scol
) scol
)
2033 eq
(match-string 3 string
)
2034 eq-alist
(cons (cons scol eq
) eq-alist
))
2035 (if (member scol seen
)
2038 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol
)
2041 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol
))
2042 (push scol seen
))))))
2043 (nreverse eq-alist
)))
2045 (defun org-table-fix-formulas (key replace
&optional limit delta remove
)
2046 "Modify the equations after the table structure has been edited.
2047 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
2048 For all numbers larger than LIMIT, shift them by DELTA."
2050 (goto-char (org-table-end))
2051 (when (looking-at "[ \t]*#\\+TBLFM:")
2052 (let ((re (concat key
"\\([0-9]+\\)"))
2055 (if (or (equal key
"$") (equal key
"$LR"))
2056 (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
2057 (regexp-quote key
) remove
)
2058 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove
))))
2061 (while (re-search-forward re2
(point-at-eol) t
)
2062 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2063 (replace-match ""))))
2064 (while (re-search-forward re
(point-at-eol) t
)
2065 (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
2066 (setq s
(match-string 1) n
(string-to-number s
))
2068 ((setq a
(assoc s replace
))
2069 (replace-match (concat key
(cdr a
)) t t
))
2070 ((and limit
(> n limit
))
2071 (replace-match (concat key
(int-to-string (+ n delta
)))
2074 (defun org-table-get-specials ()
2075 "Get the column names and local parameters for this table."
2077 (let ((beg (org-table-begin)) (end (org-table-end))
2078 names name fields fields1 field cnt
2079 c v l line col types dlines hlines last-dline
)
2080 (setq org-table-column-names nil
2081 org-table-local-parameters nil
2082 org-table-named-field-locations nil
2083 org-table-current-begin-line nil
2084 org-table-current-begin-pos nil
2085 org-table-current-line-types nil
2086 org-table-current-ncol
0)
2088 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t
)
2089 (setq names
(org-split-string (match-string 1) " *| *")
2091 (while (setq name
(pop names
))
2093 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name
)
2094 (push (cons name
(int-to-string cnt
)) org-table-column-names
))))
2095 (setq org-table-column-names
(nreverse org-table-column-names
))
2096 (setq org-table-column-name-regexp
2097 (concat "\\$\\(" (mapconcat 'car org-table-column-names
"\\|") "\\)\\>"))
2099 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t
)
2100 (setq fields
(org-split-string (match-string 1) " *| *"))
2101 (while (setq field
(pop fields
))
2102 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field
)
2103 (push (cons (match-string 1 field
) (match-string 2 field
))
2104 org-table-local-parameters
))))
2106 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t
)
2107 (setq c
(match-string 1)
2108 fields
(org-split-string (match-string 2) " *| *"))
2110 (beginning-of-line (if (equal c
"_") 2 0))
2111 (setq line
(org-current-line) col
1)
2112 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
2113 (setq fields1
(org-split-string (match-string 1) " *| *"))))
2114 (while (and fields1
(setq field
(pop fields
)))
2115 (setq v
(pop fields1
) col
(1+ col
))
2116 (when (and (stringp field
) (stringp v
)
2117 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field
))
2118 (push (cons field v
) org-table-local-parameters
)
2119 (push (list field line col
) org-table-named-field-locations
))))
2120 ;; Analyse the line types
2122 (setq org-table-current-begin-line
(org-current-line)
2123 org-table-current-begin-pos
(point)
2124 l org-table-current-begin-line
)
2125 (while (looking-at "[ \t]*|\\(-\\)?")
2126 (push (if (match-end 1) 'hline
'dline
) types
)
2127 (if (match-end 1) (push l hlines
) (push l dlines
))
2128 (beginning-of-line 2)
2130 (push 'hline types
) ;; add an imaginary extra hline to the end
2131 (setq org-table-current-line-types
(apply 'vector
(nreverse types
))
2132 last-dline
(car dlines
)
2133 org-table-dlines
(apply 'vector
(cons nil
(nreverse dlines
)))
2134 org-table-hlines
(apply 'vector
(cons nil
(nreverse hlines
))))
2135 (org-goto-line last-dline
)
2136 (let* ((l last-dline
)
2137 (fields (org-split-string
2138 (buffer-substring (point-at-bol) (point-at-eol))
2140 (nfields (length fields
))
2142 (setq org-table-current-ncol nfields
)
2143 (loop for i from
1 to nfields do
2144 (push (list (format "LR%d" i
) l i
) al
)
2145 (push (cons (format "LR%d" i
) (nth (1- i
) fields
)) al2
))
2146 (setq org-table-named-field-locations
2147 (append org-table-named-field-locations al
))
2148 (setq org-table-local-parameters
2149 (append org-table-local-parameters al2
))))))
2151 (defun org-table-maybe-eval-formula ()
2152 "Check if the current field starts with \"=\" or \":=\".
2153 If yes, store the formula and apply it."
2154 ;; We already know we are in a table. Get field will only return a formula
2155 ;; when appropriate. It might return a separator line, but no problem.
2156 (when org-table-formula-evaluate-inline
2157 (let* ((field (org-trim (or (org-table-get-field) "")))
2159 (when (string-match "^:?=\\(.*\\)" field
)
2160 (setq named
(equal (string-to-char field
) ?
:)
2161 eq
(match-string 1 field
))
2162 (if (or (fboundp 'calc-eval
)
2163 (equal (substring eq
0 (min 2 (length eq
))) "'("))
2164 (org-table-eval-formula (if named
'(4) nil
)
2165 (org-table-formula-from-user eq
))
2166 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
2168 (defvar org-recalc-commands nil
2169 "List of commands triggering the recalculation of a line.
2170 Will be filled automatically during use.")
2172 (defvar org-recalc-marks
2173 '((" " .
"Unmarked: no special line, no automatic recalculation")
2174 ("#" .
"Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
2175 ("*" .
"Recalculate only when entire table is recalculated with `C-u C-c *'")
2176 ("!" .
"Column name definition line. Reference in formula as $name.")
2177 ("$" .
"Parameter definition line name=value. Reference in formula as $name.")
2178 ("_" .
"Names for values in row below this one.")
2179 ("^" .
"Names for values in row above this one.")))
2181 (defun org-table-rotate-recalc-marks (&optional newchar
)
2182 "Rotate the recalculation mark in the first column.
2183 If in any row, the first field is not consistent with a mark,
2184 insert a new column for the markers.
2185 When there is an active region, change all the lines in the region,
2186 after prompting for the marking character.
2187 After each change, a message will be displayed indicating the meaning
2190 (unless (org-at-table-p) (error "Not at a table"))
2191 (let* ((marks (append (mapcar 'car org-recalc-marks
) '(" ")))
2192 (beg (org-table-begin))
2193 (end (org-table-end))
2194 (l (org-current-line))
2195 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
2196 (l2 (if (org-region-active-p) (org-current-line (region-end))))
2200 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t
))))
2201 (col (org-table-current-column))
2202 (forcenew (car (assoc newchar org-recalc-marks
)))
2205 (message "Change region to what mark? Type # * ! $ or SPC: ")
2206 (setq newchar
(char-to-string (read-char-exclusive))
2207 forcenew
(car (assoc newchar org-recalc-marks
))))
2208 (if (and newchar
(not forcenew
))
2209 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
2211 (if l1
(org-goto-line l1
))
2213 (beginning-of-line 1)
2214 (unless (looking-at org-table-dataline-regexp
)
2215 (error "Not at a table data line")))
2217 (org-table-goto-column 1)
2218 (org-table-insert-column)
2219 (org-table-goto-column (1+ col
)))
2220 (setq epos
(point-at-eol))
2222 (beginning-of-line 1)
2223 (org-table-get-field
2224 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
2226 (setq new
(or forcenew
2227 (cadr (member (match-string 1) marks
))))
2233 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2
)))
2234 (and (looking-at org-table-dataline-regexp
)
2235 (org-table-get-field 1 (concat " " new
" "))))
2236 (org-goto-line l1
)))
2237 (if (not (= epos
(point-at-eol))) (org-table-align))
2239 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks
))))))
2241 (defun org-table-maybe-recalculate-line ()
2242 "Recompute the current line if marked for it, and if we haven't just done it."
2244 (and org-table-allow-automatic-line-recalculation
2245 (not (and (memq last-command org-recalc-commands
)
2246 (equal org-last-recalc-line
(org-current-line))))
2247 (save-excursion (beginning-of-line 1)
2248 (looking-at org-table-auto-recalculate-regexp
))
2249 (org-table-recalculate) t
))
2252 (defsubst org-set-calc-mode
(var &optional value
)
2254 (setq var
(assoc var
'(("D" calc-angle-mode deg
)
2255 ("R" calc-angle-mode rad
)
2256 ("F" calc-prefer-frac t
)
2257 ("S" calc-symbolic-mode t
)))
2258 value
(nth 2 var
) var
(nth 1 var
)))
2259 (if (memq var modes
)
2260 (setcar (cdr (memq var modes
)) value
)
2261 (cons var
(cons value modes
)))
2264 (defun org-table-eval-formula (&optional arg equation
2265 suppress-align suppress-const
2266 suppress-store suppress-analysis
)
2267 "Replace the table field value at the cursor by the result of a calculation.
2269 This function makes use of Dave Gillespie's Calc package, in my view the
2270 most exciting program ever written for GNU Emacs. So you need to have Calc
2271 installed in order to use this function.
2273 In a table, this command replaces the value in the current field with the
2274 result of a formula. It also installs the formula as the \"current\" column
2275 formula, by storing it in a special line below the table. When called
2276 with a `C-u' prefix, the current field must be a named field, and the
2277 formula is installed as valid in only this specific field.
2279 When called with two `C-u' prefixes, insert the active equation
2280 for the field back into the current field, so that it can be
2281 edited there. This is useful in order to use \\[org-table-show-reference]
2282 to check the referenced fields.
2284 When called, the command first prompts for a formula, which is read in
2285 the minibuffer. Previously entered formulas are available through the
2286 history list, and the last used formula is offered as a default.
2287 These stored formulas are adapted correctly when moving, inserting, or
2288 deleting columns with the corresponding commands.
2290 The formula can be any algebraic expression understood by the Calc package.
2291 For details, see the Org-mode manual.
2293 This function can also be called from Lisp programs and offers
2294 additional arguments: EQUATION can be the formula to apply. If this
2295 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
2296 used to speed-up recursive calls by by-passing unnecessary aligns.
2297 SUPPRESS-CONST suppresses the interpretation of constants in the
2298 formula, assuming that this has been done already outside the function.
2299 SUPPRESS-STORE means the formula should not be stored, either because
2300 it is already stored, or because it is a modified equation that should
2301 not overwrite the stored one."
2303 (org-table-check-inside-data-field)
2304 (or suppress-analysis
(org-table-get-specials))
2305 (if (equal arg
'(16))
2306 (let ((eq (org-table-current-field-formula)))
2307 (or eq
(error "No equation active for current field"))
2308 (org-table-get-field nil eq
)
2310 (setq org-table-may-need-update t
))
2312 (ndown (if (integerp arg
) arg
1))
2313 (org-table-automatic-realign nil
)
2314 (case-fold-search nil
)
2316 (formula (if (and equation suppress-store
)
2318 (org-table-get-formula equation
(equal arg
'(4)))))
2319 (n0 (org-table-current-column))
2320 (modes (copy-sequence org-calc-default-modes
))
2321 (numbers nil
) ; was a variable, now fixed default
2323 n form form0 bw fmt x ev orig c lispp literal
)
2324 ;; Parse the format string. Since we have a lot of modes, this is
2325 ;; a lot of work. However, I think calc still uses most of the time.
2326 (if (string-match ";" formula
)
2327 (let ((tmp (org-split-string formula
";")))
2328 (setq formula
(car tmp
)
2329 fmt
(concat (cdr (assoc "%" org-table-local-parameters
))
2331 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt
)
2332 (setq c
(string-to-char (match-string 1 fmt
))
2333 n
(string-to-number (match-string 2 fmt
)))
2335 (setq modes
(org-set-calc-mode 'calc-internal-prec n
))
2336 (setq modes
(org-set-calc-mode
2338 (list (cdr (assoc c
'((?n . float
) (?f . fix
)
2339 (?s . sci
) (?e . eng
))))
2341 (setq fmt
(replace-match "" t t fmt
)))
2342 (if (string-match "[NT]" fmt
)
2343 (setq numbers
(equal (match-string 0 fmt
) "N")
2344 fmt
(replace-match "" t t fmt
)))
2345 (if (string-match "L" fmt
)
2347 fmt
(replace-match "" t t fmt
)))
2348 (if (string-match "E" fmt
)
2350 fmt
(replace-match "" t t fmt
)))
2351 (while (string-match "[DRFS]" fmt
)
2352 (setq modes
(org-set-calc-mode (match-string 0 fmt
)))
2353 (setq fmt
(replace-match "" t t fmt
)))
2354 (unless (string-match "\\S-" fmt
)
2356 (if (and (not suppress-const
) org-table-formula-use-constants
)
2357 (setq formula
(org-table-formula-substitute-names formula
)))
2358 (setq orig
(or (get-text-property 1 :orig-formula formula
) "?"))
2360 (setq fields
(org-split-string
2362 (buffer-substring (point-at-bol) (point-at-eol)))
2365 (setq fields
(mapcar
2366 (lambda (x) (number-to-string (string-to-number x
)))
2368 (setq ndown
(1- ndown
))
2369 (setq form
(copy-sequence formula
)
2370 lispp
(and (> (length form
) 2)(equal (substring form
0 2) "'(")))
2371 (if (and lispp literal
) (setq lispp
'literal
))
2373 ;; Insert row and column number of formula result field
2374 (while (string-match "[@$]#" form
)
2379 (if (equal (substring form
(match-beginning 0)
2380 (1+ (match-beginning 0)))
2382 (org-table-current-dline)
2383 (org-table-current-column))))
2386 ;; Check for old vertical references
2387 (setq form
(org-table-rewrite-old-row-references form
))
2388 ;; Insert remote references
2389 (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form
)
2393 (org-table-make-reference
2394 (org-table-get-remote-range
2395 (match-string 1 form
) (match-string 2 form
))
2396 keep-empty numbers lispp
))
2398 ;; Insert complex ranges
2399 (while (and (string-match org-table-range-regexp form
)
2400 (> (length (match-string 0 form
)) 1))
2404 (org-table-make-reference
2405 (org-table-get-range (match-string 0 form
) nil n0
)
2406 keep-empty numbers lispp
))
2408 ;; Insert simple ranges
2409 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form
)
2413 (org-table-make-reference
2415 fields
(string-to-number (match-string 1 form
))
2416 (string-to-number (match-string 2 form
)))
2417 keep-empty numbers lispp
))
2420 ;; Insert the references to fields in same row
2421 (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form
)
2422 (setq n
(+ (string-to-number (match-string 1 form
))
2423 (if (match-end 2) n0
0))
2424 x
(nth (1- (if (= n
0) n0
(max n
1))) fields
))
2425 (unless x
(error "Invalid field specifier \"%s\""
2426 (match-string 0 form
)))
2427 (setq form
(replace-match
2429 (org-table-make-reference x nil numbers lispp
))
2433 (setq ev
(condition-case nil
2434 (eval (eval (read form
)))
2436 ev
(if (numberp ev
) (number-to-string ev
) ev
))
2437 (or (fboundp 'calc-eval
)
2438 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
2439 (setq ev
(calc-eval (cons form modes
)
2440 (if numbers
'num
))))
2442 (when org-table-formula-debug
2443 (with-output-to-temp-buffer "*Substitution History*"
2444 (princ (format "Substitution history of formula
2448 $1-> %s\n" orig formula form0 form
))
2450 (princ (format " %s^\nError: %s"
2451 (make-string (car ev
) ?\-
) (nth 1 ev
)))
2452 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
2454 (if fmt
(format fmt
(string-to-number ev
)) ev
)))))
2455 (setq bw
(get-buffer-window "*Substitution History*"))
2456 (org-fit-window-to-buffer bw
)
2457 (unless (and (interactive-p) (not ndown
))
2458 (unless (let (inhibit-redisplay)
2459 (y-or-n-p "Debugging Formula. Continue to next? "))
2464 (if (listp ev
) (setq fmt nil ev
"#ERROR"))
2465 (org-table-justify-field-maybe
2466 (if fmt
(format fmt
(string-to-number ev
)) ev
))
2467 (if (and down
(> ndown
0) (looking-at ".*\n[ \t]*|[^-]"))
2468 (call-interactively 'org-return
)
2470 (and down
(org-table-maybe-recalculate-line))
2471 (or suppress-align
(and org-table-may-need-update
2472 (org-table-align))))))
2474 (defun org-table-put-field-property (prop value
)
2476 (put-text-property (progn (skip-chars-backward "^|") (point))
2477 (progn (skip-chars-forward "^|") (point))
2480 (defun org-table-get-range (desc &optional tbeg col highlight corners-only
)
2481 "Get a calc vector from a column, according to descriptor DESC.
2482 Optional arguments TBEG and COL can give the beginning of the table and
2483 the current column, to avoid unnecessary parsing.
2485 HIGHLIGHT means just highlight the range.
2487 When CORNERS-ONLY is set, only return the corners of the range as
2488 a list (line1 column1 line2 column2) where line1 and line2 are line numbers
2489 in the buffer and column1 and column2 are table column numbers."
2490 (if (not (equal (string-to-char desc
) ?
@))
2491 (setq desc
(concat "@" desc
)))
2493 (or tbeg
(setq tbeg
(org-table-begin)))
2494 (or col
(setq col
(org-table-current-column)))
2495 (let ((thisline (org-current-line))
2496 beg end c1 c2 r1 r2 rangep tmp
)
2497 (unless (string-match org-table-range-regexp desc
)
2498 (error "Invalid table range specifier `%s'" desc
))
2499 (setq rangep
(match-end 3)
2500 r1
(and (match-end 1) (match-string 1 desc
))
2501 r2
(and (match-end 4) (match-string 4 desc
))
2502 c1
(and (match-end 2) (substring (match-string 2 desc
) 1))
2503 c2
(and (match-end 5) (substring (match-string 5 desc
) 1)))
2505 (and c1
(setq c1
(+ (string-to-number c1
)
2506 (if (memq (string-to-char c1
) '(?- ?
+)) col
0))))
2507 (and c2
(setq c2
(+ (string-to-number c2
)
2508 (if (memq (string-to-char c2
) '(?- ?
+)) col
0))))
2509 (if (equal r1
"") (setq r1 nil
))
2510 (if (equal r2
"") (setq r2 nil
))
2511 (if r1
(setq r1
(org-table-get-descriptor-line r1
)))
2512 (if r2
(setq r2
(org-table-get-descriptor-line r2
)))
2513 ; (setq r2 (or r2 r1) c2 (or c2 c1))
2514 (if (not r1
) (setq r1 thisline
))
2515 (if (not r2
) (setq r2 thisline
))
2516 (if (not c1
) (setq c1 col
))
2517 (if (not c2
) (setq c2 col
))
2518 (if (and (not corners-only
)
2519 (or (not rangep
) (and (= r1 r2
) (= c1 c2
))))
2523 (while (not (looking-at org-table-dataline-regexp
))
2524 (beginning-of-line 2))
2525 (prog1 (org-trim (org-table-get-field c1
))
2526 (if highlight
(org-table-highlight-rectangle (point) (point)))))
2527 ;; A range, return a vector
2528 ;; First sort the numbers to get a regular ractangle
2529 (if (< r2 r1
) (setq tmp r1 r1 r2 r2 tmp
))
2530 (if (< c2 c1
) (setq tmp c1 c1 c2 c2 tmp
))
2532 ;; Only return the corners of the range
2534 ;; Copy the range values into a list
2536 (while (not (looking-at org-table-dataline-regexp
))
2537 (beginning-of-line 2))
2538 (org-table-goto-column c1
)
2541 (while (not (looking-at org-table-dataline-regexp
))
2542 (beginning-of-line 0))
2543 (org-table-goto-column c2
)
2546 (org-table-highlight-rectangle
2547 beg
(progn (skip-chars-forward "^|\n") (point))))
2548 ;; return string representation of calc vector
2550 (apply 'append
(org-table-copy-region beg end
))))))))
2552 (defun org-table-get-descriptor-line (desc &optional cline bline table
)
2553 "Analyze descriptor DESC and retrieve the corresponding line number.
2554 The cursor is currently in line CLINE, the table begins in line BLINE,
2555 and TABLE is a vector with line types."
2556 (if (string-match "^[0-9]+$" desc
)
2557 (aref org-table-dlines
(string-to-number desc
))
2558 (setq cline
(or cline
(org-current-line))
2559 bline
(or bline org-table-current-begin-line
)
2560 table
(or table org-table-current-line-types
))
2562 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc
))
2564 (and (not (match-end 3)) (not (match-end 6)))
2565 (and (match-end 3) (match-end 6) (not (match-end 5))))
2566 (error "Invalid row descriptor `%s'" desc
))
2567 (let* ((hdir (and (match-end 2) (match-string 2 desc
)))
2568 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil
))
2569 (odir (and (match-end 5) (match-string 5 desc
)))
2570 (on (if (match-end 6) (string-to-number (match-string 6 desc
))))
2572 (rel (and (match-end 6)
2573 (or (and (match-end 1) (not (match-end 3)))
2575 (if (and hn
(not hdir
))
2578 (if (eq (aref table
0) 'hline
) (setq hn
(1- hn
)))))
2579 (if (and (not hn
) on
(not odir
))
2580 (error "Should never happen");;(aref org-table-dlines on)
2581 (if (and hn
(> hn
0))
2582 (setq i
(org-table-find-row-type table i
'hline
(equal hdir
"-")
2583 nil hn cline desc
)))
2585 (setq i
(org-table-find-row-type table i
'dline
(equal odir
"-")
2586 rel on cline desc
)))
2589 (defun org-table-find-row-type (table i type backwards relative n cline desc
)
2590 "FIXME: Needs more documentation."
2591 (let ((l (length table
)))
2593 (while (and (setq i
(+ i
(if backwards -
1 1)))
2595 (not (eq (aref table i
) type
))
2596 (if (and relative
(eq (aref table i
) 'hline
))
2598 ((eq org-table-relative-ref-may-cross-hline t
) t
)
2599 ((eq org-table-relative-ref-may-cross-hline
'error
)
2600 (error "Row descriptor %s used in line %d crosses hline" desc cline
))
2601 (t (setq i
(- i
(if backwards -
1 1))
2606 (if (or (< i
0) (>= i l
))
2607 (error "Row descriptor %s used in line %d leads outside table"
2611 (defun org-table-rewrite-old-row-references (s)
2612 (if (string-match "&[-+0-9I]" s
)
2613 (error "Formula contains old &row reference, please rewrite using @-syntax")
2616 (defun org-table-make-reference (elements keep-empty numbers lispp
)
2617 "Convert list ELEMENTS to something appropriate to insert into formula.
2618 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
2619 NUMBERS indicates that everything should be converted to numbers.
2620 LISPP means to return something appropriate for a Lisp list."
2621 (if (stringp elements
) ; just a single val
2623 (if (eq lispp
'literal
)
2625 (prin1-to-string (if numbers
(string-to-number elements
) elements
)))
2626 (if (equal elements
"") (setq elements
"0"))
2627 (if numbers
(setq elements
(number-to-string (string-to-number elements
))))
2628 (concat "(" elements
")"))
2632 (mapcar (lambda (x) (if (string-match "\\S-" x
) x nil
))
2634 (setq elements
(or elements
'("0")))
2638 (if (eq lispp
'literal
)
2640 (prin1-to-string (if numbers
(string-to-number x
) x
))))
2642 (concat "[" (mapconcat
2644 (if numbers
(number-to-string (string-to-number x
)) x
))
2648 (defun org-table-recalculate (&optional all noalign
)
2649 "Recalculate the current table line by applying all stored formulas.
2650 With prefix arg ALL, do this for all lines in the table.
2651 With the prefix argument ALL is `(16)' \
2652 \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
2653 it is the symbol `iterate', recompute the table until it no longer changes.
2654 If NOALIGN is not nil, do not re-align the table after the computations
2655 are done. This is typically used internally to save time, if it is
2656 known that the table will be realigned a little later anyway."
2658 (or (memq this-command org-recalc-commands
)
2659 (setq org-recalc-commands
(cons this-command org-recalc-commands
)))
2660 (unless (org-at-table-p) (error "Not at a table"))
2661 (if (or (eq all
'iterate
) (equal all
'(16)))
2663 (org-table-get-specials)
2664 (let* ((eqlist (sort (org-table-get-stored-formulas)
2665 (lambda (a b
) (string< (car a
) (car b
)))))
2666 (eqlist1 (copy-sequence eqlist
))
2667 (inhibit-redisplay (not debug-on-error
))
2668 (line-re org-table-dataline-regexp
)
2669 (thisline (org-current-line))
2670 (thiscol (org-table-current-column))
2672 beg end entry eqlnum eqlname eqlname1 eql
(cnt 0) eq a name name1
)
2673 ;; Insert constants in all formulas
2676 (when (string-match "\\`$>" (car x
))
2678 (setq x
(cons (substring
2679 (org-table-formula-handle-lastrc
2682 (if (assoc (car x
) eqlist1
)
2683 (error "\"%s=\" formula tries to overwrite existing formula for column %s"
2686 (org-table-formula-handle-lastrc (car x
))
2687 (org-table-formula-substitute-names
2688 (org-table-formula-handle-lastrc (cdr x
)))))
2690 ;; Split the equation list
2691 (while (setq eq
(pop eqlist
))
2692 (if (<= (string-to-char (car eq
)) ?
9)
2695 (setq eqlnum
(nreverse eqlnum
) eqlname
(nreverse eqlname
))
2696 ;; Expand ranges in lhs of formulas
2697 (setq eqlname
(org-table-expand-lhs-ranges eqlname
))
2699 ;; Get the correct line range to process
2702 (setq end
(move-marker (make-marker) (1+ (org-table-end))))
2703 (goto-char (setq beg
(org-table-begin)))
2704 (if (re-search-forward org-table-calculate-mark-regexp end t
)
2705 ;; This is a table with marked lines, compute selected lines
2706 (setq line-re org-table-recalculate-regexp
)
2707 ;; Move forward to the first non-header line
2708 (if (and (re-search-forward org-table-dataline-regexp end t
)
2709 (re-search-forward org-table-hline-regexp end t
)
2710 (re-search-forward org-table-dataline-regexp end t
))
2711 (setq beg
(match-beginning 0))
2712 nil
))) ;; just leave beg where it is
2713 (setq beg
(point-at-bol)
2714 end
(move-marker (make-marker) (1+ (point-at-eol)))))
2716 (and all
(message "Re-applying formulas to full table..."))
2718 ;; First find the named fields, and mark them untouchable.
2719 ;; Also check if several field/range formulas try to set the same field.
2720 (remove-text-properties beg end
'(org-untouchable t
))
2721 (while (setq eq
(pop eqlname
))
2723 a
(assoc name org-table-named-field-locations
))
2725 (if a
(setq name1
(format "@%d$%d" (org-table-line-to-dline (nth 1 a
))
2727 (when (member name1 seen-fields
)
2728 (error "Several field/range formulas try to set %s" name1
))
2729 (push name1 seen-fields
)
2732 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name
)
2735 (aref org-table-dlines
2736 (string-to-number (match-string 1 name
)))
2737 (error (error "Invalid row number in %s"
2739 (string-to-number (match-string 2 name
)))))
2740 (when (and a
(or all
(equal (nth 1 a
) thisline
)))
2741 (message "Re-applying formula to field: %s" name
)
2742 (org-goto-line (nth 1 a
))
2743 (org-table-goto-column (nth 2 a
))
2744 (push (append a
(list (cdr eq
))) eqlname1
)
2745 (org-table-put-field-property :org-untouchable t
)))
2746 (setq eqlname1
(nreverse eqlname1
))
2748 ;; Now evaluate the column formulas, but skip fields covered by
2751 (while (re-search-forward line-re end t
)
2752 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
2753 ;; Unprotected line, recalculate
2754 (and all
(message "Re-applying formulas to full table...(line %d)"
2755 (setq cnt
(1+ cnt
))))
2756 (setq org-last-recalc-line
(org-current-line))
2758 (while (setq entry
(pop eql
))
2759 (org-goto-line org-last-recalc-line
)
2760 (org-table-goto-column (string-to-number (car entry
)) nil
'force
)
2761 (unless (get-text-property (point) :org-untouchable
)
2762 (org-table-eval-formula nil
(cdr entry
)
2763 'noalign
'nocst
'nostore
'noanalysis
)))))
2765 ;; Now evaluate the field formulas
2766 (while (setq eq
(pop eqlname1
))
2767 (message "Re-applying formula to field: %s" (car eq
))
2768 (org-goto-line (nth 1 eq
))
2769 (org-table-goto-column (nth 2 eq
))
2770 (org-table-eval-formula nil
(nth 3 eq
) 'noalign
'nocst
2771 'nostore
'noanalysis
))
2773 (org-goto-line thisline
)
2774 (org-table-goto-column thiscol
)
2775 (remove-text-properties (point-min) (point-max) '(org-untouchable t
))
2776 (or noalign
(and org-table-may-need-update
(org-table-align))
2777 (and all
(message "Re-applying formulas to %d lines...done" cnt
)))
2779 ;; back to initial position
2780 (message "Re-applying formulas...done")
2781 (org-goto-line thisline
)
2782 (org-table-goto-column thiscol
)
2783 (or noalign
(and org-table-may-need-update
(org-table-align))
2784 (and all
(message "Re-applying formulas...done"))))))
2786 (defun org-table-iterate (&optional arg
)
2787 "Recalculate the table until it does not change anymore.
2788 The maximun number of iterations is 10, but you can chose a different value
2789 with the prefix ARG."
2791 (let ((imax (if arg
(prefix-numeric-value arg
) 10))
2793 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
2798 (org-table-recalculate 'all
)
2799 (setq thistbl
(buffer-substring (org-table-begin) (org-table-end)))
2800 (if (not (string= lasttbl thistbl
))
2801 (setq lasttbl thistbl
)
2803 (message "Convergence after %d iterations" i
)
2804 (message "Table was already stable"))
2806 (error "No convergence after %d iterations" i
))))
2808 (defun org-table-recalculate-buffer-tables ()
2809 "Recalculate all tables in the current buffer."
2814 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
))))
2816 (defun org-table-iterate-buffer-tables ()
2817 "Iterate all tables in the buffer, to converge inter-table dependencies."
2820 (checksum (md5 (buffer-string)))
2830 (org-table-map-tables (lambda () (org-table-recalculate t
)) t
)
2831 (if (equal checksum
(setq c1
(md5 (buffer-string))))
2833 (message "Convergence after %d iterations" (- imax i
))
2835 (setq checksum c1
)))
2836 (error "No convergence after %d iterations" imax
))))))
2838 (defun org-table-expand-lhs-ranges (equations)
2839 "Expand list of formulas.
2840 If some of the RHS in the formulas are ranges or a row reference, expand
2841 them to individual field equations for each field."
2842 (let (e res lhs rhs range r1 r2 c1 c2
)
2843 (while (setq e
(pop equations
))
2844 (setq lhs
(car e
) rhs
(cdr e
))
2846 ((string-match "^@-?[-+I0-9]+\\$-?[0-9]+$" lhs
)
2847 ;; This just refers to one fixed field
2849 ((string-match "^[a-zA-Z][a-zA-Z0-9]*$" lhs
)
2850 ;; This just refers to one fixed named field
2852 ((string-match "^@[0-9]+$" lhs
)
2853 (loop for ic from
1 to org-table-current-ncol do
2854 (push (cons (format "%s$%d" lhs ic
) rhs
) res
)
2855 (put-text-property 0 (length (caar res
))
2856 :orig-eqn e
(caar res
))))
2858 (setq range
(org-table-get-range lhs org-table-current-begin-pos
2860 (setq r1
(nth 0 range
) c1
(nth 1 range
)
2861 r2
(nth 2 range
) c2
(nth 3 range
))
2862 (setq r1
(org-table-line-to-dline r1
))
2863 (setq r2
(org-table-line-to-dline r2
'above
))
2864 (loop for ir from r1 to r2 do
2865 (loop for ic from c1 to c2 do
2866 (push (cons (format "@%d$%d" ir ic
) rhs
) res
)
2867 (put-text-property 0 (length (caar res
))
2868 :orig-eqn e
(caar res
)))))))
2871 (defun org-table-formula-handle-lastrc (s)
2872 "Replace @> / $> with the last row/column of the table."
2873 (while (string-match "\\([@$]\\)>\\(-[0-9]+\\)?" s
)
2874 (setq s
(replace-match
2877 (+ (if (equal (match-string 1 s
) "@")
2878 (1- (length org-table-dlines
))
2879 org-table-current-ncol
)
2881 (string-to-number (match-string 2 s
))
2886 (defun org-table-formula-substitute-names (f)
2887 "Replace $const with values in string F."
2888 (let ((start 0) a
(f1 f
) (pp (/= (string-to-char f
) ?
')))
2889 ;; First, check for column names
2890 (while (setq start
(string-match org-table-column-name-regexp f start
))
2891 (setq start
(1+ start
))
2892 (setq a
(assoc (match-string 1 f
) org-table-column-names
))
2893 (setq f
(replace-match (concat "$" (cdr a
)) t t f
)))
2894 ;; Parameters and constants
2896 (while (setq start
(string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start
))
2898 (setq start
(match-end 2))
2899 (setq start
(1+ start
))
2900 (if (setq a
(save-match-data
2901 (org-table-get-constant (match-string 1 f
))))
2902 (setq f
(replace-match
2903 (concat (if pp
"(") a
(if pp
")")) t t f
)))))
2904 (if org-table-formula-debug
2905 (put-text-property 0 (length f
) :orig-formula f1 f
))
2908 (defun org-table-get-constant (const)
2909 "Find the value for a parameter or constant in a formula.
2910 Parameters get priority."
2911 (or (cdr (assoc const org-table-local-parameters
))
2912 (cdr (assoc const org-table-formula-constants-local
))
2913 (cdr (assoc const org-table-formula-constants
))
2914 (and (fboundp 'constants-get
) (constants-get const
))
2915 (and (string= (substring const
0 (min 5 (length const
))) "PROP_")
2916 (org-entry-get nil
(substring const
5) 'inherit
))
2919 (defvar org-table-fedit-map
2920 (let ((map (make-sparse-keymap)))
2921 (org-defkey map
"\C-x\C-s" 'org-table-fedit-finish
)
2922 (org-defkey map
"\C-c\C-s" 'org-table-fedit-finish
)
2923 (org-defkey map
"\C-c\C-c" 'org-table-fedit-finish
)
2924 (org-defkey map
"\C-c'" 'org-table-fedit-finish
)
2925 (org-defkey map
"\C-c\C-q" 'org-table-fedit-abort
)
2926 (org-defkey map
"\C-c?" 'org-table-show-reference
)
2927 (org-defkey map
[(meta shift up
)] 'org-table-fedit-line-up
)
2928 (org-defkey map
[(meta shift down
)] 'org-table-fedit-line-down
)
2929 (org-defkey map
[(shift up
)] 'org-table-fedit-ref-up
)
2930 (org-defkey map
[(shift down
)] 'org-table-fedit-ref-down
)
2931 (org-defkey map
[(shift left
)] 'org-table-fedit-ref-left
)
2932 (org-defkey map
[(shift right
)] 'org-table-fedit-ref-right
)
2933 (org-defkey map
[(meta up
)] 'org-table-fedit-scroll-down
)
2934 (org-defkey map
[(meta down
)] 'org-table-fedit-scroll
)
2935 (org-defkey map
[(meta tab
)] 'lisp-complete-symbol
)
2936 (org-defkey map
"\M-\C-i" 'lisp-complete-symbol
)
2937 (org-defkey map
[(tab)] 'org-table-fedit-lisp-indent
)
2938 (org-defkey map
"\C-i" 'org-table-fedit-lisp-indent
)
2939 (org-defkey map
"\C-c\C-r" 'org-table-fedit-toggle-ref-type
)
2940 (org-defkey map
"\C-c}" 'org-table-fedit-toggle-coordinates
)
2943 (easy-menu-define org-table-fedit-menu org-table-fedit-map
"Org Edit Formulas Menu"
2945 ["Finish and Install" org-table-fedit-finish t
]
2946 ["Finish, Install, and Apply" (org-table-fedit-finish t
) :keys
"C-u C-c C-c"]
2947 ["Abort" org-table-fedit-abort t
]
2949 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t
]
2950 ["Complete Lisp Symbol" lisp-complete-symbol t
]
2952 "Shift Reference at Point"
2953 ["Up" org-table-fedit-ref-up t
]
2954 ["Down" org-table-fedit-ref-down t
]
2955 ["Left" org-table-fedit-ref-left t
]
2956 ["Right" org-table-fedit-ref-right t
]
2958 "Change Test Row for Column Formulas"
2959 ["Up" org-table-fedit-line-up t
]
2960 ["Down" org-table-fedit-line-down t
]
2962 ["Scroll Table Window" org-table-fedit-scroll t
]
2963 ["Scroll Table Window down" org-table-fedit-scroll-down t
]
2964 ["Show Table Grid" org-table-fedit-toggle-coordinates
2965 :style toggle
:selected
(with-current-buffer (marker-buffer org-pos
)
2966 org-table-overlay-coordinates
)]
2968 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
2969 :style toggle
:selected org-table-buffer-is-an
]))
2973 (defun org-table-edit-formulas ()
2974 "Edit the formulas of the current table in a separate buffer."
2976 (when (save-excursion (beginning-of-line 1) (looking-at "[ \t]*#\\+TBLFM"))
2977 (beginning-of-line 0))
2978 (unless (org-at-table-p) (error "Not at a table"))
2979 (org-table-get-specials)
2980 (let ((key (org-table-current-field-formula 'key
'noerror
))
2981 (eql (sort (org-table-get-stored-formulas 'noerror
)
2982 'org-table-formula-less-p
))
2983 (pos (move-marker (make-marker) (point)))
2985 (wc (current-window-configuration))
2986 (sel-win (selected-window))
2987 (titles '((column .
"# Column Formulas\n")
2988 (field .
"# Field and Range Formulas\n")
2989 (named .
"# Named Field Formulas\n")))
2991 (org-switch-to-buffer-other-window "*Edit Formulas*")
2993 ;; Keep global-font-lock-mode from turning on font-lock-mode
2994 (let ((font-lock-global-modes '(not fundamental-mode
)))
2996 (org-set-local 'font-lock-global-modes
(list 'not major-mode
))
2997 (org-set-local 'org-pos pos
)
2998 (org-set-local 'org-window-configuration wc
)
2999 (org-set-local 'org-selected-window sel-win
)
3000 (use-local-map org-table-fedit-map
)
3001 (org-add-hook 'post-command-hook
'org-table-fedit-post-command t t
)
3002 (easy-menu-add org-table-fedit-menu
)
3003 (setq startline
(org-current-line))
3004 (while (setq entry
(pop eql
))
3006 ((string-match "\\`$>" (car entry
)) 'column
)
3007 ((equal (string-to-char (car entry
)) ?
@) 'field
)
3008 ((string-match "^[0-9]" (car entry
)) 'column
)
3010 (when (setq title
(assq type titles
))
3011 (or (bobp) (insert "\n"))
3012 (insert (org-add-props (cdr title
) nil
'face font-lock-comment-face
))
3013 (setq titles
(remove title titles
)))
3014 (if (equal key
(car entry
)) (setq startline
(org-current-line)))
3015 (setq s
(concat (if (member (string-to-char (car entry
)) '(?
@ ?$
)) "" "$")
3016 (car entry
) " = " (cdr entry
) "\n"))
3017 (remove-text-properties 0 (length s
) '(face nil
) s
)
3019 (if (eq org-table-use-standard-references t
)
3020 (org-table-fedit-toggle-ref-type))
3021 (org-goto-line startline
)
3022 (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
3024 (defun org-table-fedit-post-command ()
3025 (when (not (memq this-command
'(lisp-complete-symbol)))
3026 (let ((win (selected-window)))
3029 (org-table-show-reference)
3031 (select-window win
)))))
3033 (defun org-table-formula-to-user (s)
3034 "Convert a formula from internal to user representation."
3035 (if (eq org-table-use-standard-references t
)
3036 (org-table-convert-refs-to-an s
)
3039 (defun org-table-formula-from-user (s)
3040 "Convert a formula from user to internal representation."
3041 (if org-table-use-standard-references
3042 (org-table-convert-refs-to-rc s
)
3045 (defun org-table-convert-refs-to-rc (s)
3046 "Convert spreadsheet references from A7 to @7$28.
3047 Works for single references, but also for entire formulas and even the
3050 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^)]*)\\)" s start
)
3053 ;; format match, just advance
3054 (setq start
(match-end 0)))
3055 ((and (> (match-beginning 0) 0)
3056 (equal ?.
(aref s
(max (1- (match-beginning 0)) 0)))
3057 (not (equal ?.
(aref s
(max (- (match-beginning 0) 2) 0)))))
3058 ;; 3.e5 or something like this.
3059 (setq start
(match-end 0)))
3060 ((or (> (- (match-end 1) (match-beginning 1)) 2)
3061 ;; (member (match-string 1 s)
3062 ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
3064 ;; function name, just advance
3065 (setq start
(match-end 0)))
3067 (setq start
(match-beginning 0)
3069 (if (equal (match-string 2 s
) "&")
3070 (format "$%d" (org-letters-to-number (match-string 1 s
)))
3072 (string-to-number (match-string 2 s
))
3073 (org-letters-to-number (match-string 1 s
))))
3077 (defun org-table-convert-refs-to-an (s)
3078 "Convert spreadsheet references from to @7$28 to AB7.
3079 Works for single references, but also for entire formulas and even the
3081 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s
)
3082 (setq s
(replace-match
3084 (org-number-to-letters
3085 (string-to-number (match-string 2 s
)))
3086 (string-to-number (match-string 1 s
)))
3088 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s
)
3089 (setq s
(replace-match (concat "\\1"
3090 (org-number-to-letters
3091 (string-to-number (match-string 2 s
))) "&")
3095 (defun org-letters-to-number (s)
3096 "Convert a base 26 number represented by letters into an integer.
3097 For example: AB -> 28."
3100 (while (> (length s
) 0)
3101 (setq n
(+ (* n
26) (string-to-char s
) (- ?A
) 1)
3105 (defun org-number-to-letters (n)
3106 "Convert an integer into a base 26 number represented by letters.
3107 For example: 28 -> AB."
3110 (setq s
(concat (char-to-string (+ (mod (1- n
) 26) ?A
)) s
)
3114 (defun org-table-fedit-convert-buffer (function)
3115 "Convert all references in this buffer, using FUNCTION."
3116 (let ((line (org-current-line)))
3117 (goto-char (point-min))
3119 (insert (funcall function
(buffer-substring (point) (point-at-eol))))
3120 (delete-region (point) (point-at-eol))
3121 (or (eobp) (forward-char 1)))
3122 (org-goto-line line
)))
3124 (defun org-table-fedit-toggle-ref-type ()
3125 "Convert all references in the buffer from B3 to @3$2 and back."
3127 (org-set-local 'org-table-buffer-is-an
(not org-table-buffer-is-an
))
3128 (org-table-fedit-convert-buffer
3129 (if org-table-buffer-is-an
3130 'org-table-convert-refs-to-an
'org-table-convert-refs-to-rc
))
3131 (message "Reference type switched to %s"
3132 (if org-table-buffer-is-an
"A1 etc" "@row$column")))
3134 (defun org-table-fedit-ref-up ()
3135 "Shift the reference at point one row/hline up."
3137 (org-table-fedit-shift-reference 'up
))
3138 (defun org-table-fedit-ref-down ()
3139 "Shift the reference at point one row/hline down."
3141 (org-table-fedit-shift-reference 'down
))
3142 (defun org-table-fedit-ref-left ()
3143 "Shift the reference at point one field to the left."
3145 (org-table-fedit-shift-reference 'left
))
3146 (defun org-table-fedit-ref-right ()
3147 "Shift the reference at point one field to the right."
3149 (org-table-fedit-shift-reference 'right
))
3151 (defun org-table-fedit-shift-reference (dir)
3153 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
3154 (if (memq dir
'(left right
))
3155 (org-rematch-and-replace 1 (eq dir
'left
))
3156 (error "Cannot shift reference in this direction")))
3157 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
3158 ;; A B3-like reference
3159 (if (memq dir
'(up down
))
3160 (org-rematch-and-replace 2 (eq dir
'up
))
3161 (org-rematch-and-replace 1 (eq dir
'left
))))
3163 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
3164 ;; An internal reference
3165 (if (memq dir
'(up down
))
3166 (org-rematch-and-replace 2 (eq dir
'up
) (match-end 3))
3167 (org-rematch-and-replace 5 (eq dir
'left
))))))
3169 (defun org-rematch-and-replace (n &optional decr hline
)
3170 "Re-match the group N, and replace it with the shifted reference."
3171 (or (match-end n
) (error "Cannot shift reference in this direction"))
3172 (goto-char (match-beginning n
))
3173 (and (looking-at (regexp-quote (match-string n
)))
3174 (replace-match (org-table-shift-refpart (match-string 0) decr hline
)
3177 (defun org-table-shift-refpart (ref &optional decr hline
)
3178 "Shift a reference part REF.
3179 If DECR is set, decrease the references row/column, else increase.
3180 If HLINE is set, this may be a hline reference, it certainly is not
3181 a translation reference."
3183 (let* ((sign (string-match "^[-+]" ref
)) n
)
3185 (if sign
(setq sign
(substring ref
0 1) ref
(substring ref
1)))
3187 ((and hline
(string-match "^I+" ref
))
3188 (setq n
(string-to-number (concat sign
(number-to-string (length ref
)))))
3189 (setq n
(+ n
(if decr -
1 1)))
3190 (if (= n
0) (setq n
(+ n
(if decr -
1 1))))
3192 (setq sign
(if (< n
0) "-" "+") n
(abs n
))
3194 (concat sign
(make-string n ?I
)))
3196 ((string-match "^[0-9]+" ref
)
3197 (setq n
(string-to-number (concat sign ref
)))
3198 (setq n
(+ n
(if decr -
1 1)))
3200 (concat (if (< n
0) "-" "+") (number-to-string (abs n
)))
3201 (number-to-string (max 1 n
))))
3203 ((string-match "^[a-zA-Z]+" ref
)
3204 (org-number-to-letters
3205 (max 1 (+ (org-letters-to-number ref
) (if decr -
1 1)))))
3207 (t (error "Cannot shift reference"))))))
3209 (defun org-table-fedit-toggle-coordinates ()
3210 "Toggle the display of coordinates in the referenced table."
3212 (let ((pos (marker-position org-pos
)))
3213 (with-current-buffer (marker-buffer org-pos
)
3216 (org-table-toggle-coordinate-overlays)))))
3218 (defun org-table-fedit-finish (&optional arg
)
3219 "Parse the buffer for formula definitions and install them.
3220 With prefix ARG, apply the new formulas to the table."
3222 (org-table-remove-rectangle-highlight)
3223 (if org-table-use-standard-references
3225 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc
)
3226 (setq org-table-buffer-is-an nil
)))
3227 (let ((pos org-pos
) (sel-win org-selected-window
) eql var form
)
3228 (goto-char (point-min))
3229 (while (re-search-forward
3230 "^\\(@[-+I>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|>[-+0-9]*\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
3232 (setq var
(if (match-end 2) (match-string 2) (match-string 1))
3233 form
(match-string 3))
3234 (setq form
(org-trim form
))
3235 (when (not (equal form
""))
3236 (while (string-match "[ \t]*\n[ \t]*" form
)
3237 (setq form
(replace-match " " t t form
)))
3238 (when (assoc var eql
)
3239 (error "Double formulas for %s" var
))
3240 (push (cons var form
) eql
)))
3242 (set-window-configuration org-window-configuration
)
3243 (select-window sel-win
)
3245 (unless (org-at-table-p)
3246 (error "Lost table position - cannot install formulas"))
3247 (org-table-store-formulas eql
)
3248 (move-marker pos nil
)
3249 (kill-buffer "*Edit Formulas*")
3251 (org-table-recalculate 'all
)
3252 (message "New formulas installed - press C-u C-c C-c to apply."))))
3254 (defun org-table-fedit-abort ()
3255 "Abort editing formulas, without installing the changes."
3257 (org-table-remove-rectangle-highlight)
3258 (let ((pos org-pos
) (sel-win org-selected-window
))
3259 (set-window-configuration org-window-configuration
)
3260 (select-window sel-win
)
3262 (move-marker pos nil
)
3263 (message "Formula editing aborted without installing changes")))
3265 (defun org-table-fedit-lisp-indent ()
3266 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
3268 (let ((pos (point)) beg end ind
)
3269 (beginning-of-line 1)
3271 ((looking-at "[ \t]")
3273 (call-interactively 'lisp-indent-line
))
3274 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos
))
3275 ((not (fboundp 'pp-buffer
))
3276 (error "Cannot pretty-print. Command `pp-buffer' is not available"))
3277 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
3278 (goto-char (- (match-end 0) 2))
3280 (setq ind
(make-string (current-column) ?\
))
3281 (condition-case nil
(forward-sexp 1)
3283 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
3286 (narrow-to-region beg end
)
3287 (if (eq last-command this-command
)
3289 (goto-char (point-min))
3290 (setq this-command nil
)
3291 (while (re-search-forward "[ \t]*\n[ \t]*" nil t
)
3292 (replace-match " ")))
3294 (untabify (point-min) (point-max))
3295 (goto-char (1+ (point-min)))
3296 (while (re-search-forward "^." nil t
)
3297 (beginning-of-line 1)
3299 (goto-char (point-max))
3300 (backward-delete-char 1)))
3304 (defvar org-show-positions nil
)
3306 (defun org-table-show-reference (&optional local
)
3307 "Show the location/value of the $ expression at point."
3309 (org-table-remove-rectangle-highlight)
3311 (let ((pos (if local
(point) org-pos
))
3313 (org-inhibit-highlight-removal t
)
3314 (win (selected-window))
3315 (org-show-positions nil
)
3316 var name e what match dest
)
3317 (if local
(org-table-get-specials))
3319 ((org-at-regexp-p "^@[0-9]+[ \t=]")
3320 (setq match
(concat (substring (match-string 0) 0 -
1)
3322 (substring (match-string 0) 0 -
1)
3325 ((or (org-at-regexp-p org-table-range-regexp2
)
3326 (org-at-regexp-p org-table-translate-regexp
)
3327 (org-at-regexp-p org-table-range-regexp
))
3330 (org-table-convert-refs-to-rc (match-string 0))))
3332 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name
)
3333 ((org-at-regexp-p "\\$[0-9]+") 'column
)
3335 (t (error "No reference at point")))
3336 match
(and what
(or match
(match-string 0))))
3337 (when (and match
(not (equal (match-beginning 0) (point-at-bol))))
3338 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
3339 'secondary-selection
))
3340 (org-add-hook 'before-change-functions
3341 'org-table-remove-rectangle-highlight
)
3342 (if (eq what
'name
) (setq var
(substring match
1)))
3343 (when (eq what
'range
)
3344 (or (equal (string-to-char match
) ?
@) (setq match
(concat "@" match
)))
3345 (setq match
(org-table-formula-substitute-names match
)))
3349 (re-search-backward "^\\S-" nil t
)
3350 (beginning-of-line 1)
3351 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
3354 (org-table-convert-refs-to-rc (match-string 1))))
3355 (org-table-add-rectangle-overlay
3356 (match-beginning 1) (match-end 1) face2
))))
3357 (if (and (markerp pos
) (marker-buffer pos
))
3358 (if (get-buffer-window (marker-buffer pos
))
3359 (select-window (get-buffer-window (marker-buffer pos
)))
3360 (org-switch-to-buffer-other-window (get-buffer-window
3361 (marker-buffer pos
)))))
3363 (org-table-force-dataline)
3365 (setq name
(substring dest
1))
3367 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest
)
3368 (setq e
(assoc name org-table-named-field-locations
))
3369 (org-goto-line (nth 1 e
))
3370 (org-table-goto-column (nth 2 e
)))
3371 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest
)
3372 (let ((l (string-to-number (match-string 1 dest
)))
3373 (c (string-to-number (match-string 2 dest
))))
3374 (org-goto-line (aref org-table-dlines l
))
3375 (org-table-goto-column c
)))
3376 (t (org-table-goto-column (string-to-number name
))))
3377 (move-marker pos
(point))
3378 (org-table-highlight-rectangle nil nil face2
))
3380 ((equal dest match
))
3385 (org-table-get-range match nil nil
'highlight
))
3387 ((setq e
(assoc var org-table-named-field-locations
))
3388 (org-goto-line (nth 1 e
))
3389 (org-table-goto-column (nth 2 e
))
3390 (org-table-highlight-rectangle (point) (point))
3391 (message "Named field, column %d of line %d" (nth 2 e
) (nth 1 e
)))
3392 ((setq e
(assoc var org-table-column-names
))
3393 (org-table-goto-column (string-to-number (cdr e
)))
3394 (org-table-highlight-rectangle (point) (point))
3395 (goto-char (org-table-begin))
3396 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var
"\\) *|")
3399 (goto-char (match-beginning 1))
3400 (org-table-highlight-rectangle)
3401 (message "Named column (column %s)" (cdr e
)))
3402 (error "Column name not found")))
3405 (org-table-goto-column (string-to-number (substring match
1)))
3406 (org-table-highlight-rectangle (point) (point))
3407 (message "Column %s" (substring match
1)))
3408 ((setq e
(assoc var org-table-local-parameters
))
3409 (goto-char (org-table-begin))
3410 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var
"=\\)") nil t
)
3412 (goto-char (match-beginning 1))
3413 (org-table-highlight-rectangle)
3414 (message "Local parameter."))
3415 (error "Parameter not found")))
3418 ((not var
) (error "No reference at point"))
3419 ((setq e
(assoc var org-table-formula-constants-local
))
3420 (message "Local Constant: $%s=%s in #+CONSTANTS line."
3422 ((setq e
(assoc var org-table-formula-constants
))
3423 (message "Constant: $%s=%s in `org-table-formula-constants'."
3425 ((setq e
(and (fboundp 'constants-get
) (constants-get var
)))
3426 (message "Constant: $%s=%s, from `constants.el'%s."
3427 var e
(format " (%s units)" constants-unit-system
)))
3428 (t (error "Undefined name $%s" var
)))))
3430 (when (and org-show-positions
3431 (not (memq this-command
'(org-table-fedit-scroll
3432 org-table-fedit-scroll-down
))))
3433 (push pos org-show-positions
)
3434 (push org-table-current-begin-pos org-show-positions
)
3435 (let ((min (apply 'min org-show-positions
))
3436 (max (apply 'max org-show-positions
)))
3437 (goto-char min
) (recenter 0)
3439 (or (pos-visible-in-window-p max
) (recenter -
1))))
3440 (select-window win
))))
3442 (defun org-table-force-dataline ()
3443 "Make sure the cursor is in a dataline in a table."
3444 (unless (save-excursion
3445 (beginning-of-line 1)
3446 (looking-at org-table-dataline-regexp
))
3447 (let* ((re org-table-dataline-regexp
)
3448 (p1 (save-excursion (re-search-forward re nil
'move
)))
3449 (p2 (save-excursion (re-search-backward re nil
'move
))))
3451 (goto-char (if (< (abs (- p1
(point))) (abs (- p2
(point))))
3453 ((or p1 p2
) (goto-char (or p1 p2
)))
3454 (t (error "No table dataline around here"))))))
3456 (defun org-table-fedit-line-up ()
3457 "Move cursor one line up in the window showing the table."
3459 (org-table-fedit-move 'previous-line
))
3461 (defun org-table-fedit-line-down ()
3462 "Move cursor one line down in the window showing the table."
3464 (org-table-fedit-move 'next-line
))
3466 (defun org-table-fedit-move (command)
3467 "Move the cursor in the window showing the table.
3468 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
3469 (let ((org-table-allow-automatic-line-recalculation nil
)
3470 (pos org-pos
) (win (selected-window)) p
)
3471 (select-window (get-buffer-window (marker-buffer org-pos
)))
3473 (call-interactively command
)
3474 (while (and (org-at-table-p)
3475 (org-at-table-hline-p))
3476 (call-interactively command
))
3477 (or (org-at-table-p) (goto-char p
))
3478 (move-marker pos
(point))
3479 (select-window win
)))
3481 (defun org-table-fedit-scroll (N)
3483 (let ((other-window-scroll-buffer (marker-buffer org-pos
)))
3484 (scroll-other-window N
)))
3486 (defun org-table-fedit-scroll-down (N)
3488 (org-table-fedit-scroll (- N
)))
3490 (defvar org-table-rectangle-overlays nil
)
3492 (defun org-table-add-rectangle-overlay (beg end
&optional face
)
3493 "Add a new overlay."
3494 (let ((ov (make-overlay beg end
)))
3495 (overlay-put ov
'face
(or face
'secondary-selection
))
3496 (push ov org-table-rectangle-overlays
)))
3498 (defun org-table-highlight-rectangle (&optional beg end face
)
3499 "Highlight rectangular region in a table."
3500 (setq beg
(or beg
(point)) end
(or end
(point)))
3501 (let ((b (min beg end
))
3504 (and (boundp 'org-show-positions
)
3505 (setq org-show-positions
(cons b
(cons e org-show-positions
))))
3506 (goto-char (min beg end
))
3507 (setq l1
(org-current-line)
3508 c1
(org-table-current-column))
3509 (goto-char (max beg end
))
3510 (setq l2
(org-current-line)
3511 c2
(org-table-current-column))
3512 (if (> c1 c2
) (setq tmp c1 c1 c2 c2 tmp
))
3514 (beginning-of-line 1)
3515 (loop for line from l1 to l2 do
3516 (when (looking-at org-table-dataline-regexp
)
3517 (org-table-goto-column c1
)
3518 (skip-chars-backward "^|\n") (setq beg
(point))
3519 (org-table-goto-column c2
)
3520 (skip-chars-forward "^|\n") (setq end
(point))
3521 (org-table-add-rectangle-overlay beg end face
))
3522 (beginning-of-line 2))
3524 (add-hook 'before-change-functions
'org-table-remove-rectangle-highlight
))
3526 (defun org-table-remove-rectangle-highlight (&rest ignore
)
3527 "Remove the rectangle overlays."
3528 (unless org-inhibit-highlight-removal
3529 (remove-hook 'before-change-functions
'org-table-remove-rectangle-highlight
)
3530 (mapc 'delete-overlay org-table-rectangle-overlays
)
3531 (setq org-table-rectangle-overlays nil
)))
3533 (defvar org-table-coordinate-overlays nil
3534 "Collects the coordinate grid overlays, so that they can be removed.")
3535 (make-variable-buffer-local 'org-table-coordinate-overlays
)
3537 (defun org-table-overlay-coordinates ()
3538 "Add overlays to the table at point, to show row/column coordinates."
3540 (mapc 'delete-overlay org-table-coordinate-overlays
)
3541 (setq org-table-coordinate-overlays nil
)
3543 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg
)
3544 (goto-char (org-table-begin))
3545 (while (org-at-table-p)
3546 (setq eol
(point-at-eol))
3547 (setq ov
(make-overlay (point-at-bol) (1+ (point-at-bol))))
3548 (push ov org-table-coordinate-overlays
)
3549 (setq hline
(looking-at org-table-hline-regexp
))
3550 (setq str
(if hline
(format "I*%-2d" (setq ih
(1+ ih
)))
3551 (format "%4d" (setq id
(1+ id
)))))
3552 (org-overlay-before-string ov str
'org-special-keyword
'evaporate
)
3555 (while (re-search-forward "[+|]\\(-+\\)" eol t
)
3556 (setq beg
(1+ (match-beginning 0))
3558 s1
(concat "$" (int-to-string ic
))
3559 s2
(org-number-to-letters ic
)
3560 str
(if (eq org-table-use-standard-references t
) s2 s1
))
3561 (setq ov
(make-overlay beg
(+ beg
(length str
))))
3562 (push ov org-table-coordinate-overlays
)
3563 (org-overlay-display ov str
'org-special-keyword
'evaporate
)))
3564 (beginning-of-line 2)))))
3566 (defun org-table-toggle-coordinate-overlays ()
3567 "Toggle the display of Row/Column numbers in tables."
3569 (setq org-table-overlay-coordinates
(not org-table-overlay-coordinates
))
3570 (message "Row/Column number display turned %s"
3571 (if org-table-overlay-coordinates
"on" "off"))
3572 (if (and (org-at-table-p) org-table-overlay-coordinates
)
3574 (unless org-table-overlay-coordinates
3575 (mapc 'delete-overlay org-table-coordinate-overlays
)
3576 (setq org-table-coordinate-overlays nil
)))
3578 (defun org-table-toggle-formula-debugger ()
3579 "Toggle the formula debugger in tables."
3581 (setq org-table-formula-debug
(not org-table-formula-debug
))
3582 (message "Formula debugging has been turned %s"
3583 (if org-table-formula-debug
"on" "off")))
3585 ;;; The orgtbl minor mode
3587 ;; Define a minor mode which can be used in other modes in order to
3588 ;; integrate the org-mode table editor.
3590 ;; This is really a hack, because the org-mode table editor uses several
3591 ;; keys which normally belong to the major mode, for example the TAB and
3592 ;; RET keys. Here is how it works: The minor mode defines all the keys
3593 ;; necessary to operate the table editor, but wraps the commands into a
3594 ;; function which tests if the cursor is currently inside a table. If that
3595 ;; is the case, the table editor command is executed. However, when any of
3596 ;; those keys is used outside a table, the function uses `key-binding' to
3597 ;; look up if the key has an associated command in another currently active
3598 ;; keymap (minor modes, major mode, global), and executes that command.
3599 ;; There might be problems if any of the keys used by the table editor is
3600 ;; otherwise used as a prefix key.
3602 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
3603 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
3604 ;; addresses this by checking explicitly for both bindings.
3606 ;; The optimized version (see variable `orgtbl-optimized') takes over
3607 ;; all keys which are bound to `self-insert-command' in the *global map*.
3608 ;; Some modes bind other commands to simple characters, for example
3609 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
3610 ;; active, this binding is ignored inside tables and replaced with a
3611 ;; modified self-insert.
3614 (defvar orgtbl-mode-map
(make-keymap)
3615 "Keymap for `orgtbl-mode'.")
3618 (defun turn-on-orgtbl ()
3619 "Unconditionally turn on `orgtbl-mode'."
3622 (defvar org-old-auto-fill-inhibit-regexp nil
3623 "Local variable used by `orgtbl-mode'.")
3625 (defconst orgtbl-line-start-regexp
3626 "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\|TBLNAME\\):\\)"
3627 "Matches a line belonging to an orgtbl.")
3629 (defconst orgtbl-extra-font-lock-keywords
3630 (list (list (concat "^" orgtbl-line-start-regexp
".*")
3631 0 (quote 'org-table
) 'prepend
))
3632 "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
3634 ;; Install it as a minor mode.
3635 (put 'orgtbl-mode
:included t
)
3636 (put 'orgtbl-mode
:menu-tag
"Org Table Mode")
3639 (define-minor-mode orgtbl-mode
3640 "The `org-mode' table editor as a minor mode for use in other modes."
3641 :lighter
" OrgTbl" :keymap orgtbl-mode-map
3642 (org-load-modules-maybe)
3645 ;; Exit without error, in case some hook functions calls this
3646 ;; by accident in org-mode.
3647 (message "Orgtbl-mode is not useful in org-mode, command ignored"))
3649 (and (orgtbl-setup) (defun orgtbl-setup () nil
)) ;; FIXME: Yuck!?!
3650 ;; Make sure we are first in minor-mode-map-alist
3651 (let ((c (assq 'orgtbl-mode minor-mode-map-alist
)))
3652 ;; FIXME: maybe it should use emulation-mode-map-alists?
3653 (and c
(setq minor-mode-map-alist
3654 (cons c
(delq c minor-mode-map-alist
)))))
3655 (org-set-local (quote org-table-may-need-update
) t
)
3656 (org-add-hook 'before-change-functions
'org-before-change-function
3658 (org-set-local 'org-old-auto-fill-inhibit-regexp
3659 auto-fill-inhibit-regexp
)
3660 (org-set-local 'auto-fill-inhibit-regexp
3661 (if auto-fill-inhibit-regexp
3662 (concat orgtbl-line-start-regexp
"\\|"
3663 auto-fill-inhibit-regexp
)
3664 orgtbl-line-start-regexp
))
3665 (add-to-invisibility-spec '(org-cwidth))
3666 (when (fboundp 'font-lock-add-keywords
)
3667 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords
)
3668 (org-restart-font-lock))
3669 (easy-menu-add orgtbl-mode-menu
))
3671 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp
)
3672 (org-table-cleanup-narrow-column-properties)
3673 (org-remove-from-invisibility-spec '(org-cwidth))
3674 (remove-hook 'before-change-functions
'org-before-change-function t
)
3675 (when (fboundp 'font-lock-remove-keywords
)
3676 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords
)
3677 (org-restart-font-lock))
3678 (easy-menu-remove orgtbl-mode-menu
)
3679 (force-mode-line-update 'all
))))
3681 (defun org-table-cleanup-narrow-column-properties ()
3682 "Remove all properties related to narrow-column invisibility."
3684 (while (setq s
(text-property-any s
(point-max)
3685 'display org-narrow-column-arrow
))
3686 (remove-text-properties s
(1+ s
) '(display t
)))
3688 (while (setq s
(text-property-any s
(point-max) 'org-cwidth
1))
3689 (remove-text-properties s
(1+ s
) '(org-cwidth t
)))
3691 (while (setq s
(text-property-any s
(point-max) 'invisible
'org-cwidth
))
3692 (remove-text-properties s
(1+ s
) '(invisible t
)))))
3694 (defun orgtbl-make-binding (fun n
&rest keys
)
3695 "Create a function for binding in the table minor mode.
3696 FUN is the command to call inside a table. N is used to create a unique
3697 command name. KEYS are keys that should be checked in for a command
3698 to execute outside of tables."
3701 (intern (concat "orgtbl-hijacker-command-" (int-to-string n
)))
3703 (concat "In tables, run `" (symbol-name fun
) "'.\n"
3704 "Outside of tables, run the binding of `"
3705 (mapconcat (lambda (x) (format "%s" x
)) keys
"' or `")
3710 (list 'call-interactively
(list 'quote fun
))
3711 (list 'let
'(orgtbl-mode)
3712 (list 'call-interactively
3715 (list 'key-binding k
))
3717 '('orgtbl-error
))))))))
3719 (defun orgtbl-error ()
3720 "Error when there is no default binding for a table key."
3722 (error "This key has no function outside tables"))
3724 (defun orgtbl-setup ()
3725 "Setup orgtbl keymaps."
3728 '(([(meta shift left
)] org-table-delete-column
)
3729 ([(meta left
)] org-table-move-column-left
)
3730 ([(meta right
)] org-table-move-column-right
)
3731 ([(meta shift right
)] org-table-insert-column
)
3732 ([(meta shift up
)] org-table-kill-row
)
3733 ([(meta shift down
)] org-table-insert-row
)
3734 ([(meta up
)] org-table-move-row-up
)
3735 ([(meta down
)] org-table-move-row-down
)
3736 ("\C-c\C-w" org-table-cut-region
)
3737 ("\C-c\M-w" org-table-copy-region
)
3738 ("\C-c\C-y" org-table-paste-rectangle
)
3739 ("\C-c-" org-table-insert-hline
)
3740 ("\C-c}" org-table-toggle-coordinate-overlays
)
3741 ("\C-c{" org-table-toggle-formula-debugger
)
3742 ("\C-m" org-table-next-row
)
3743 ([(shift return
)] org-table-copy-down
)
3744 ("\C-c?" org-table-field-info
)
3745 ("\C-c " org-table-blank-field
)
3746 ("\C-c+" org-table-sum
)
3747 ("\C-c=" org-table-eval-formula
)
3748 ("\C-c'" org-table-edit-formulas
)
3749 ("\C-c`" org-table-edit-field
)
3750 ("\C-c*" org-table-recalculate
)
3751 ("\C-c^" org-table-sort-lines
)
3752 ("\M-a" org-table-beginning-of-field
)
3753 ("\M-e" org-table-end-of-field
)
3754 ([(control ?
#)] org-table-rotate-recalc-marks
)))
3756 (while (setq elt
(pop bindings
))
3757 (setq nfunc
(1+ nfunc
))
3758 (setq key
(org-key (car elt
))
3760 cmd
(orgtbl-make-binding fun nfunc key
))
3761 (org-defkey orgtbl-mode-map key cmd
))
3763 ;; Special treatment needed for TAB and RET
3764 (org-defkey orgtbl-mode-map
[(return)]
3765 (orgtbl-make-binding 'orgtbl-ret
100 [(return)] "\C-m"))
3766 (org-defkey orgtbl-mode-map
"\C-m"
3767 (orgtbl-make-binding 'orgtbl-ret
101 "\C-m" [(return)]))
3769 (org-defkey orgtbl-mode-map
[(tab)]
3770 (orgtbl-make-binding 'orgtbl-tab
102 [(tab)] "\C-i"))
3771 (org-defkey orgtbl-mode-map
"\C-i"
3772 (orgtbl-make-binding 'orgtbl-tab
103 "\C-i" [(tab)]))
3774 (org-defkey orgtbl-mode-map
[(shift tab
)]
3775 (orgtbl-make-binding 'org-table-previous-field
104
3776 [(shift tab
)] [(tab)] "\C-i"))
3779 (unless (featurep 'xemacs
)
3780 (org-defkey orgtbl-mode-map
[S-iso-lefttab
]
3781 (orgtbl-make-binding 'org-table-previous-field
107
3782 [S-iso-lefttab
] [backtab] [(shift tab)]
3785 (org-defkey orgtbl-mode-map [backtab]
3786 (orgtbl-make-binding 'org-table-previous-field
108
3787 [backtab] [S-iso-lefttab] [(shift tab)]
3790 (org-defkey orgtbl-mode-map "\M-\C-m"
3791 (orgtbl-make-binding 'org-table-wrap-region 105
3792 "\M-\C-m" [(meta return)]))
3793 (org-defkey orgtbl-mode-map [(meta return)]
3794 (orgtbl-make-binding 'org-table-wrap-region 106
3795 [(meta return)] "\M-\C-m"))
3797 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
3798 (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
3800 (when orgtbl-optimized
3801 ;; If the user wants maximum table support, we need to hijack
3802 ;; some standard editing functions
3803 (org-remap orgtbl-mode-map
3804 'self-insert-command 'orgtbl-self-insert-command
3805 'delete-char 'org-delete-char
3806 'delete-backward-char 'org-delete-backward-char)
3807 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
3808 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
3810 ["Create or convert" org-table-create-or-convert-from-region
3811 :active (not (org-at-table-p)) :keys "C-c |" ]
3813 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
3814 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
3815 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
3816 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
3818 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
3819 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
3820 ["Copy Field from Above"
3821 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
3824 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
3825 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
3826 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
3827 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
3829 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
3830 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
3831 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
3832 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
3833 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
3835 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
3837 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
3838 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
3839 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
3840 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
3843 ["Insert table template" orgtbl-insert-radio-table
3844 (assq major-mode orgtbl-radio-table-templates)]
3845 ["Comment/uncomment table" orgtbl-toggle-comment t])
3847 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
3848 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
3849 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
3850 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
3851 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
3852 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
3853 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
3854 ["Sum Column/Rectangle" org-table-sum
3855 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
3856 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
3858 org-table-toggle-formula-debugger :active (org-at-table-p)
3860 :style toggle :selected org-table-formula-debug]
3861 ["Show Col/Row Numbers"
3862 org-table-toggle-coordinate-overlays :active (org-at-table-p)
3864 :style toggle :selected org-table-overlay-coordinates]
3868 (defun orgtbl-ctrl-c-ctrl-c (arg)
3869 "If the cursor is inside a table, realign the table.
3870 If it is a table to be sent away to a receiver, do it.
3871 With prefix arg, also recompute table."
3873 (let ((pos (point)) action consts-str consts cst const-str)
3875 (beginning-of-line 1)
3877 ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
3878 ((looking-at "[ \t]*|") pos)
3879 ((looking-at "[ \t]*#\\+TBLFM:") 'recalc))))
3883 (org-table-maybe-eval-formula)
3885 (call-interactively 'org-table-recalculate)
3886 (org-table-maybe-recalculate-line))
3887 (call-interactively 'org-table-align)
3888 (when (orgtbl-send-table 'maybe)
3889 (run-hooks 'orgtbl-after-send-table-hook)))
3890 ((eq action 'recalc)
3892 (goto-char (point-min))
3893 (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t)
3894 (setq const-str (substring-no-properties (match-string 1)))
3895 (setq consts (append consts (org-split-string const-str "[ \t]+")))
3898 (while (setq e (pop consts))
3899 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3900 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3901 (setq org-table-formula-constants-local cst)))))
3903 (beginning-of-line 1)
3904 (skip-chars-backward " \r\n\t")
3905 (if (org-at-table-p)
3906 (org-call-with-arg 'org-table-recalculate t))))
3907 (t (let (orgtbl-mode)
3908 (call-interactively (key-binding "\C-c\C-c")))))))
3910 (defun orgtbl-create-or-convert-from-region (arg)
3911 "Create table or convert region to table, if no conflicting binding.
3912 This installs the table binding `C-c |', but only if there is no
3913 conflicting binding to this key outside orgtbl-mode."
3915 (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
3917 (call-interactively cmd)
3918 (call-interactively 'org-table-create-or-convert-from-region))))
3920 (defun orgtbl-tab (arg)
3921 "Justification and field motion for `orgtbl-mode'."
3923 (if arg (org-table-edit-field t)
3924 (org-table-justify-field-maybe)
3925 (org-table-next-field)))
3927 (defun orgtbl-ret ()
3928 "Justification and field motion for `orgtbl-mode'."
3932 (org-table-justify-field-maybe)
3933 (org-table-next-row)))
3935 (defun orgtbl-self-insert-command (N)
3936 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
3937 If the cursor is in a table looking at whitespace, the whitespace is
3938 overwritten, and the table is not marked as requiring realignment."
3940 (if (and (org-at-table-p)
3942 (and org-table-auto-blank-field
3943 (member last-command
3944 '(orgtbl-hijacker-command-100
3945 orgtbl-hijacker-command-101
3946 orgtbl-hijacker-command-102
3947 orgtbl-hijacker-command-103
3948 orgtbl-hijacker-command-104
3949 orgtbl-hijacker-command-105
3951 (org-table-blank-field))
3954 (looking-at "[^|\n]* +|"))
3955 (let (org-table-may-need-update)
3956 (goto-char (1- (match-end 0)))
3957 (delete-backward-char 1)
3958 (goto-char (match-beginning 0))
3959 (self-insert-command N))
3960 (setq org-table-may-need-update t)
3963 (cmd (or (key-binding
3964 (or (and (listp function-key-map)
3965 (setq a (assoc last-input-event function-key-map))
3967 (vector last-input-event)))
3968 'self-insert-command)))
3969 (call-interactively cmd)
3970 (if (and org-self-insert-cluster-for-undo
3971 (eq cmd 'self-insert-command))
3972 (if (not (eq last-command 'orgtbl-self-insert-command))
3973 (setq org-self-insert-command-undo-counter 1)
3974 (if (>= org-self-insert-command-undo-counter 20)
3975 (setq org-self-insert-command-undo-counter 1)
3976 (and (> org-self-insert-command-undo-counter 0)
3978 (not (cadr buffer-undo-list)) ; remove nil entry
3979 (setcdr buffer-undo-list (cddr buffer-undo-list)))
3980 (setq org-self-insert-command-undo-counter
3981 (1+ org-self-insert-command-undo-counter))))))))
3983 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
3984 "Regular expression matching exponentials as produced by calc.")
3986 (defun orgtbl-export (table target)
3988 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
3989 (lines (org-split-string table "[ \t]*\n[ \t]*"))
3990 org-table-last-alignment org-table-last-column-widths
3992 (if (not (fboundp func))
3993 (error "Cannot export orgtbl table to %s" target))
3994 (setq lines (org-table-clean-before-export lines))
3998 (if (string-match org-table-hline-regexp x)
4000 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4002 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
4004 (loop for i from (1- maxcol) downto 0 do
4005 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
4006 (setq column (delq nil column))
4007 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
4008 (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))
4009 (funcall func table nil)))
4011 (defun orgtbl-gather-send-defs ()
4012 "Gather a plist of :name, :transform, :params for each destination before
4015 (goto-char (org-table-begin))
4017 (beginning-of-line 0)
4018 (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
4019 (let ((name (org-no-properties (match-string 1)))
4020 (transform (intern (match-string 2)))
4021 (params (if (match-end 3)
4022 (read (concat "(" (match-string 3) ")")))))
4023 (push (list :name name :transform transform :params params)
4025 (beginning-of-line 0)))
4028 (defun orgtbl-send-replace-tbl (name txt)
4029 "Find and replace table NAME with TXT."
4031 (goto-char (point-min))
4032 (unless (re-search-forward
4033 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
4034 (error "Don't know where to insert translated table"))
4035 (goto-char (match-beginning 0))
4036 (beginning-of-line 2)
4038 (let ((beg (point)))
4039 (unless (re-search-forward
4040 (concat "END RECEIVE ORGTBL +" name) nil t)
4041 (error "Cannot find end of insertion region"))
4042 (beginning-of-line 1)
4043 (delete-region beg (point))))
4047 (defun org-table-to-lisp (&optional txt)
4048 "Convert the table at point to a Lisp structure.
4049 The structure will be a list. Each item is either the symbol `hline'
4050 for a horizontal separator line, or a list of field values as strings.
4051 The table is taken from the parameter TXT, or from the buffer at point."
4053 (unless (org-at-table-p)
4054 (error "No table at point")))
4056 (buffer-substring-no-properties (org-table-begin)
4058 (lines (org-split-string txt "[ \t]*\n[ \t]*")))
4062 (if (string-match org-table-hline-regexp x)
4064 (org-split-string (org-trim x) "\\s-*|\\s-*")))
4067 (defun orgtbl-send-table (&optional maybe)
4068 "Send a transformed version of this table to the receiver position.
4069 With argument MAYBE, fail quietly if no transformation is defined for
4073 (unless (org-at-table-p) (error "Not at a table"))
4074 ;; when non-interactive, we assume align has just happened.
4075 (when (interactive-p) (org-table-align))
4076 (let ((dests (orgtbl-gather-send-defs))
4077 (txt (buffer-substring-no-properties (org-table-begin)
4080 (unless dests (if maybe (throw 'exit nil)
4081 (error "Don't know how to transform this table")))
4082 (dolist (dest dests)
4083 (let* ((name (plist-get dest :name))
4084 (transform (plist-get dest :transform))
4085 (params (plist-get dest :params))
4086 (skip (plist-get params :skip))
4087 (skipcols (plist-get params :skipcols))
4089 (lines (org-table-clean-before-export
4091 (org-split-string txt "[ \t]*\n[ \t]*"))))
4092 (i0 (if org-table-clean-did-remove-column 2 1))
4095 (if (string-match org-table-hline-regexp x)
4097 (org-remove-by-index
4098 (org-split-string (org-trim x) "\\s-*|\\s-*")
4101 (fun (if (= i0 2) 'cdr 'identity))
4102 (org-table-last-alignment
4103 (org-remove-by-index (funcall fun org-table-last-alignment)
4105 (org-table-last-column-widths
4106 (org-remove-by-index (funcall fun org-table-last-column-widths)
4108 (txt (if (fboundp transform)
4109 (funcall transform table params)
4110 (error "No such transformation function %s" transform))))
4111 (orgtbl-send-replace-tbl name txt))
4112 (setq ntbl (1+ ntbl)))
4113 (message "Table converted and installed at %d receiver location%s"
4114 ntbl (if (> ntbl 1) "s" ""))
4119 (defun org-remove-by-index (list indices &optional i0)
4120 "Remove the elements in LIST with indices in INDICES.
4121 First element has index 0, or I0 if given."
4124 (if (integerp indices) (setq indices (list indices)))
4125 (setq i0 (1- (or i0 0)))
4126 (delq :rm (mapcar (lambda (x)
4128 (if (memq i0 indices) :rm x))
4131 (defun orgtbl-toggle-comment ()
4132 "Comment or uncomment the orgtbl at point."
4134 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
4135 (re2 (concat "^" orgtbl-line-start-regexp))
4136 (commented (save-excursion (beginning-of-line 1)
4137 (cond ((looking-at re1) t)
4138 ((looking-at re2) nil)
4139 (t (error "Not at an org table")))))
4140 (re (if commented re1 re2))
4143 (beginning-of-line 1)
4144 (while (looking-at re) (beginning-of-line 0))
4145 (beginning-of-line 2)
4147 (while (looking-at re) (beginning-of-line 2))
4149 (comment-region beg end (if commented '(4) nil))))
4151 (defun orgtbl-insert-radio-table ()
4152 "Insert a radio table template appropriate for this major mode."
4154 (let* ((e (assq major-mode orgtbl-radio-table-templates))
4157 (unless e (error "No radio table setup defined for %s" major-mode))
4158 (setq name (read-string "Table name: "))
4159 (while (string-match "%n" txt)
4160 (setq txt (replace-match name t t txt)))
4161 (or (bolp) (insert "\n"))
4166 ;; Dynamically bound input and output for table formatting.
4167 (defvar *orgtbl-table* nil
4168 "Carries the current table through formatting routines.")
4169 (defvar *orgtbl-rtn* nil
4170 "Formatting routines push the output lines here.")
4171 ;; Formatting parameters for the current table section.
4172 (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
4173 (defvar *orgtbl-sep* nil "Text used as a column separator.")
4174 (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
4175 (defvar *orgtbl-fmt* nil "Format for each entry.")
4176 (defvar *orgtbl-efmt* nil "Format for numbers.")
4177 (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
4178 (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
4179 (defvar *orgtbl-lstart* nil "Text starting a row.")
4180 (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
4181 (defvar *orgtbl-lend* nil "Text ending a row.")
4182 (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
4184 (defsubst orgtbl-get-fmt (fmt i)
4185 "Retrieve the format from FMT corresponding to the Ith column."
4186 (if (and (not (functionp fmt)) (consp fmt))
4190 (defsubst orgtbl-apply-fmt (fmt &rest args)
4191 "Apply format FMT to the arguments. NIL FMTs return the first argument."
4192 (cond ((functionp fmt) (apply fmt args))
4193 (fmt (apply 'format fmt args))
4197 (defsubst orgtbl-eval-str (str)
4198 "If STR is a function, evaluate it with no arguments."
4203 (defun orgtbl-format-line (line)
4204 "Format LINE as a table row."
4205 (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
4211 (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
4212 (f (if (and efmt (string-match orgtbl-exp-regexp f))
4213 (orgtbl-apply-fmt efmt (match-string 1 f)
4216 (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
4217 *orgtbl-default-fmt*)
4220 (push (if *orgtbl-lfmt*
4221 (orgtbl-apply-fmt *orgtbl-lfmt* line)
4222 (concat (orgtbl-eval-str *orgtbl-lstart*)
4223 (mapconcat 'identity line *orgtbl-sep*)
4224 (orgtbl-eval-str *orgtbl-lend*)))
4227 (defun orgtbl-format-section (section-stopper)
4228 "Format lines until the first occurrence of SECTION-STOPPER."
4231 (while (not (eq (car *orgtbl-table*) section-stopper))
4232 (if prevline (orgtbl-format-line prevline))
4233 (setq prevline (pop *orgtbl-table*)))
4234 (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
4235 (*orgtbl-lend* *orgtbl-llend*)
4236 (*orgtbl-lfmt* *orgtbl-llfmt*))
4237 (orgtbl-format-line prevline))))))
4239 (defun orgtbl-to-generic (table params)
4240 "Convert the orgtbl-mode TABLE to some other format.
4241 This generic routine can be used for many standard cases.
4242 TABLE is a list, each entry either the symbol `hline' for a horizontal
4243 separator line, or a list of fields for that line.
4244 PARAMS is a property list of parameters that can influence the conversion.
4245 For the generic converter, some parameters are obligatory: you need to
4246 specify either :lfmt, or all of (:lstart :lend :sep).
4248 Valid parameters are
4250 :splice When set to t, return only table body lines, don't wrap
4251 them into :tstart and :tend. Default is nil. When :splice
4252 is non-nil, this also means that the exporter should not look
4253 for and interpret header and footer sections.
4255 :hline String to be inserted on horizontal separation lines.
4256 May be nil to ignore hlines.
4258 :sep Separator between two fields
4259 :remove-nil-lines Do not include lines that evaluate to nil.
4262 Each in the following group may be either a string or a function
4263 of no arguments returning a string:
4264 :tstart String to start the table. Ignored when :splice is t.
4265 :tend String to end the table. Ignored when :splice is t.
4266 :lstart String to start a new table line.
4267 :llstart String to start the last table line, defaults to :lstart.
4268 :lend String to end a table line
4269 :llend String to end the last table line, defaults to :lend.
4271 Each in the following group may be a string, a function of one
4272 argument (the field or line) returning a string, or a plist
4273 mapping columns to either of the above:
4274 :lfmt Format for entire line, with enough %s to capture all fields.
4275 If this is present, :lstart, :lend, and :sep are ignored.
4276 :llfmt Format for the entire last line, defaults to :lfmt.
4277 :fmt A format to be used to wrap the field, should contain
4278 %s for the original field value. For example, to wrap
4279 everything in dollars, you could use :fmt \"$%s$\".
4280 This may also be a property list with column numbers and
4281 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4283 :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
4284 Same as above, specific for the header lines in the table.
4285 All lines before the first hline are treated as header.
4286 If any of these is not present, the data line value is used.
4288 This may be either a string or a function of two arguments:
4289 :efmt Use this format to print numbers with exponentials.
4290 The format should have %s twice for inserting mantissa
4291 and exponent, for example \"%s\\\\times10^{%s}\". This
4292 may also be a property list with column numbers and
4293 formats. :fmt will still be applied after :efmt.
4295 In addition to this, the parameters :skip and :skipcols are always handled
4296 directly by `orgtbl-send-table'. See manual."
4299 (let* ((splicep (plist-get params :splice))
4300 (hline (plist-get params :hline))
4301 (remove-nil-linesp (plist-get params :remove-nil-lines))
4302 (remove-newlines (plist-get params :remove-newlines))
4303 (*orgtbl-hline* hline)
4304 (*orgtbl-table* table)
4305 (*orgtbl-sep* (plist-get params :sep))
4306 (*orgtbl-efmt* (plist-get params :efmt))
4307 (*orgtbl-lstart* (plist-get params :lstart))
4308 (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
4309 (*orgtbl-lend* (plist-get params :lend))
4310 (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
4311 (*orgtbl-lfmt* (plist-get params :lfmt))
4312 (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
4313 (*orgtbl-fmt* (plist-get params :fmt))
4318 (when (plist-member params :tstart)
4319 (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
4320 (if tstart (push tstart *orgtbl-rtn*)))))
4322 ;; Do we have a heading section? If so, format it and handle the
4324 (if (and (not splicep)
4325 (or (consp (car *orgtbl-table*))
4326 (consp (nth 1 *orgtbl-table*)))
4327 (memq 'hline (cdr *orgtbl-table*)))
4329 (when (eq 'hline (car *orgtbl-table*))
4330 ;; there is a hline before the first data line
4331 (and hline (push hline *orgtbl-rtn*))
4332 (pop *orgtbl-table*))
4333 (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
4335 (*orgtbl-llstart* (or (plist-get params :hllstart)
4337 (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
4338 (*orgtbl-llend* (or (plist-get params :hllend)
4339 (plist-get params :hlend) *orgtbl-llend*))
4340 (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
4341 (*orgtbl-llfmt* (or (plist-get params :hllfmt)
4342 (plist-get params :hlfmt) *orgtbl-llfmt*))
4343 (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
4344 (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
4345 (orgtbl-format-section 'hline))
4346 (if hline (push hline *orgtbl-rtn*))
4347 (pop *orgtbl-table*)))
4349 ;; Now format the main section.
4350 (orgtbl-format-section nil)
4353 (when (plist-member params :tend)
4354 (let ((tend (orgtbl-eval-str (plist-get params :tend))))
4355 (if tend (push tend *orgtbl-rtn*)))))
4357 (mapconcat (if remove-newlines
4359 (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
4361 (nreverse (if remove-nil-linesp
4362 (remq nil *orgtbl-rtn*)
4363 *orgtbl-rtn*)) "\n")))
4365 (defun orgtbl-to-tsv (table params)
4366 "Convert the orgtbl-mode table to TAB separated material."
4367 (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
4368 (defun orgtbl-to-csv (table params)
4369 "Convert the orgtbl-mode table to CSV material.
4370 This does take care of the proper quoting of fields with comma or quotes."
4371 (orgtbl-to-generic table (org-combine-plists
4372 '(:sep "," :fmt org-quote-csv-field)
4375 (defun orgtbl-to-latex (table params)
4376 "Convert the orgtbl-mode TABLE to LaTeX.
4377 TABLE is a list, each entry either the symbol `hline' for a horizontal
4378 separator line, or a list of fields for that line.
4379 PARAMS is a property list of parameters that can influence the conversion.
4380 Supports all parameters from `orgtbl-to-generic'. Most important for
4383 :splice When set to t, return only table body lines, don't wrap
4384 them into a tabular environment. Default is nil.
4386 :fmt A format to be used to wrap the field, should contain %s for the
4387 original field value. For example, to wrap everything in dollars,
4388 use :fmt \"$%s$\". This may also be a property list with column
4389 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
4390 The format may also be a function that formats its one argument.
4392 :efmt Format for transforming numbers with exponentials. The format
4393 should have %s twice for inserting mantissa and exponent, for
4394 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
4395 This may also be a property list with column numbers and formats.
4396 The format may also be a function that formats its two arguments.
4398 :llend If you find too much space below the last line of a table,
4399 pass a value of \"\" for :llend to suppress the final \\\\.
4401 The general parameters :skip and :skipcols have already been applied when
4402 this function is called."
4403 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
4404 org-table-last-alignment ""))
4407 :tstart (concat "\\begin{tabular}{" alignment "}")
4408 :tend "\\end{tabular}"
4409 :lstart "" :lend " \\\\" :sep " & "
4410 :efmt "%s\\,(%s)" :hline "\\hline")))
4411 (orgtbl-to-generic table (org-combine-plists params2 params))))
4413 (defun orgtbl-to-html (table params)
4414 "Convert the orgtbl-mode TABLE to HTML.
4415 TABLE is a list, each entry either the symbol `hline' for a horizontal
4416 separator line, or a list of fields for that line.
4417 PARAMS is a property list of parameters that can influence the conversion.
4418 Currently this function recognizes the following parameters:
4420 :splice When set to t, return only table body lines, don't wrap
4421 them into a <table> environment. Default is nil.
4423 The general parameters :skip and :skipcols have already been applied when
4424 this function is called. The function does *not* use `orgtbl-to-generic',
4425 so you cannot specify parameters for it."
4426 (let* ((splicep (plist-get params :splice))
4427 (html-table-tag org-export-html-table-tag)
4429 ;; Just call the formatter we already have
4430 ;; We need to make text lines for it, so put the fields back together.
4431 (setq html (org-format-org-table-html
4436 (concat "| " (mapconcat 'org-html-expand x " | ") " |")))
4439 (if (string-match "\n+\\'" html)
4440 (setq html (replace-match "" t t html)))
4443 (defun orgtbl-to-texinfo (table params)
4444 "Convert the orgtbl-mode TABLE to TeXInfo.
4445 TABLE is a list, each entry either the symbol `hline' for a horizontal
4446 separator line, or a list of fields for that line.
4447 PARAMS is a property list of parameters that can influence the conversion.
4448 Supports all parameters from `orgtbl-to-generic'. Most important for
4451 :splice nil/t When set to t, return only table body lines, don't wrap
4452 them into a multitable environment. Default is nil.
4454 :fmt fmt A format to be used to wrap the field, should contain
4455 %s for the original field value. For example, to wrap
4456 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
4457 This may also be a property list with column numbers and
4458 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
4459 Each format also may be a function that formats its one
4462 :cf \"f1 f2..\" The column fractions for the table. By default these
4463 are computed automatically from the width of the columns
4466 The general parameters :skip and :skipcols have already been applied when
4467 this function is called."
4468 (let* ((total (float (apply '+ org-table-last-column-widths)))
4469 (colfrac (or (plist-get params :cf)
4471 (lambda (x) (format "%.3f" (/ (float x) total)))
4472 org-table-last-column-widths " ")))
4475 :tstart (concat "@multitable @columnfractions " colfrac)
4476 :tend "@end multitable"
4477 :lstart "@item " :lend "" :sep " @tab "
4478 :hlstart "@headitem ")))
4479 (orgtbl-to-generic table (org-combine-plists params2 params))))
4481 (defun orgtbl-to-orgtbl (table params)
4482 "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
4483 Useful when slicing one table into many. The :hline, :sep,
4484 :lstart, and :lend provide orgtbl framing. The default nil :tstart
4485 and :tend suppress strings without splicing; they can be set to
4486 provide ORGTBL directives for the generated table."
4490 :tstart nil :tend nil
4495 (params (org-combine-plists params2 params)))
4496 (orgtbl-to-generic table params)))
4498 (defun org-table-get-remote-range (name-or-id form)
4499 "Get a field value or a list of values in a range from table at ID.
4501 NAME-OR-ID may be the name of a table in the current file as set by
4502 a \"#+TBLNAME:\" directive. The first table following this line
4503 will then be used. Alternatively, it may be an ID referring to
4504 any entry, also in a different file. In this case, the first table
4505 in that entry will be referenced.
4506 FORM is a field or range descriptor like \"@2$3\" or or \"B3\" or
4507 \"@I$2..@II$2\". All the references must be absolute, not relative.
4509 The return value is either a single string for a single field, or a
4510 list of the fields in the rectangle ."
4513 org-table-column-names org-table-column-name-regexp
4514 org-table-local-parameters org-table-named-field-locations
4515 org-table-current-line-types org-table-current-begin-line
4516 org-table-current-begin-pos org-table-dlines
4517 org-table-current-ncol
4518 org-table-hlines org-table-last-alignment
4519 org-table-last-column-widths org-table-last-alignment
4520 org-table-last-column-widths tbeg
4522 (setq form (org-table-convert-refs-to-rc form))
4527 (goto-char (point-min))
4528 (if (re-search-forward
4529 (concat "^[ \t]*#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
4531 (setq buffer (current-buffer) loc (match-beginning 0))
4532 (setq id-loc (org-id-find name-or-id 'marker))
4533 (unless (and id-loc (markerp id-loc))
4534 (error "Can't find remote table \"%s\"" name-or-id))
4535 (setq buffer (marker-buffer id-loc)
4536 loc (marker-position id-loc))
4537 (move-marker id-loc nil)))
4538 (with-current-buffer buffer
4544 (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
4545 (not (match-beginning 1)))
4546 (error "Cannot find a table at NAME or ID %s" name-or-id))
4547 (setq tbeg (point-at-bol))
4548 (org-table-get-specials)
4549 (setq form (org-table-formula-substitute-names form))
4550 (if (and (string-match org-table-range-regexp form)
4551 (> (length (match-string 0 form)) 1))
4553 (org-table-get-range (match-string 0 form) tbeg 1))
4556 (provide 'org-table)
4558 ;; arch-tag: 4d21cfdd-0268-440a-84b0-09237a0fe0ef
4560 ;;; org-table.el ends here