Commit | Line | Data |
---|---|---|
20908596 CD |
1 | ;;; org-table.el --- The table editor for Org-mode |
2 | ||
95df8112 | 3 | ;; Copyright (C) 2004-2011 Free Software Foundation, Inc. |
20908596 CD |
4 | |
5 | ;; Author: Carsten Dominik <carsten at orgmode dot org> | |
6 | ;; Keywords: outlines, hypermedia, calendar, wp | |
7 | ;; Homepage: http://orgmode.org | |
acedf35c | 8 | ;; Version: 7.4 |
20908596 CD |
9 | ;; |
10 | ;; This file is part of GNU Emacs. | |
11 | ;; | |
b1fc2b50 | 12 | ;; GNU Emacs is free software: you can redistribute it and/or modify |
20908596 | 13 | ;; it under the terms of the GNU General Public License as published by |
b1fc2b50 GM |
14 | ;; the Free Software Foundation, either version 3 of the License, or |
15 | ;; (at your option) any later version. | |
20908596 CD |
16 | |
17 | ;; GNU Emacs is distributed in the hope that it will be useful, | |
18 | ;; but WITHOUT ANY WARRANTY; without even the implied warranty of | |
19 | ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
20 | ;; GNU General Public License for more details. | |
21 | ||
22 | ;; You should have received a copy of the GNU General Public License | |
b1fc2b50 | 23 | ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. |
20908596 CD |
24 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
25 | ;; | |
26 | ;;; Commentary: | |
27 | ||
33306645 | 28 | ;; This file contains the table editor and spreadsheet for Org-mode. |
20908596 CD |
29 | |
30 | ;; Watch out: Here we are talking about two different kind of tables. | |
31 | ;; Most of the code is for the tables created with the Org-mode table editor. | |
32 | ;; Sometimes, we talk about tables created and edited with the table.el | |
33 | ;; Emacs package. We call the former org-type tables, and the latter | |
34 | ;; table.el-type tables. | |
35 | ||
36 | ;;; Code: | |
37 | ||
38 | (eval-when-compile | |
39 | (require 'cl)) | |
40 | (require 'org) | |
41 | ||
6f3e2af6 GM |
42 | (declare-function org-table-clean-before-export "org-exp" |
43 | (lines &optional maybe-quoted)) | |
9d459fc5 | 44 | (declare-function org-format-org-table-html "org-html" (lines &optional splice)) |
20908596 CD |
45 | (defvar orgtbl-mode) ; defined below |
46 | (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized | |
71d35b24 | 47 | (defvar org-export-html-table-tag) ; defined in org-exp.el |
20908596 CD |
48 | (defvar constants-unit-system) |
49 | ||
acedf35c CD |
50 | (defvar orgtbl-after-send-table-hook nil |
51 | "Hook for functions attaching to `C-c C-c', if the table is sent. | |
52 | This can be used to add additional functionality after the table is sent | |
53 | to the receiver position, othewise, if table is not sent, the functions | |
54 | are not run.") | |
55 | ||
20908596 | 56 | (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized) |
ed21c5c8 | 57 | "Non-nil means use the optimized table editor version for `orgtbl-mode'. |
20908596 CD |
58 | In the optimized version, the table editor takes over all simple keys that |
59 | normally just insert a character. In tables, the characters are inserted | |
60 | in a way to minimize disturbing the table structure (i.e. in overwrite mode | |
61 | for empty fields). Outside tables, the correct binding of the keys is | |
62 | restored. | |
63 | ||
64 | The default for this option is t if the optimized version is also used in | |
65 | Org-mode. See the variable `org-enable-table-editor' for details. Changing | |
66 | this variable requires a restart of Emacs to become effective." | |
67 | :group 'org-table | |
68 | :type 'boolean) | |
69 | ||
70 | (defcustom orgtbl-radio-table-templates | |
71 | '((latex-mode "% BEGIN RECEIVE ORGTBL %n | |
72 | % END RECEIVE ORGTBL %n | |
73 | \\begin{comment} | |
74 | #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0 | |
75 | | | | | |
76 | \\end{comment}\n") | |
77 | (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n | |
78 | @c END RECEIVE ORGTBL %n | |
79 | @ignore | |
80 | #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0 | |
81 | | | | | |
82 | @end ignore\n") | |
83 | (html-mode "<!-- BEGIN RECEIVE ORGTBL %n --> | |
84 | <!-- END RECEIVE ORGTBL %n --> | |
85 | <!-- | |
86 | #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0 | |
87 | | | | | |
88 | -->\n")) | |
89 | "Templates for radio tables in different major modes. | |
90 | All occurrences of %n in a template will be replaced with the name of the | |
91 | table, obtained by prompting the user." | |
92 | :group 'org-table | |
93 | :type '(repeat | |
94 | (list (symbol :tag "Major mode") | |
95 | (string :tag "Format")))) | |
96 | ||
97 | (defgroup org-table-settings nil | |
98 | "Settings for tables in Org-mode." | |
99 | :tag "Org Table Settings" | |
100 | :group 'org-table) | |
101 | ||
102 | (defcustom org-table-default-size "5x2" | |
103 | "The default size for newly created tables, Columns x Rows." | |
104 | :group 'org-table-settings | |
105 | :type 'string) | |
106 | ||
107 | (defcustom org-table-number-regexp | |
108 | "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$" | |
109 | "Regular expression for recognizing numbers in table columns. | |
110 | If a table column contains mostly numbers, it will be aligned to the | |
111 | right. If not, it will be aligned to the left. | |
112 | ||
113 | The default value of this option is a regular expression which allows | |
114 | anything which looks remotely like a number as used in scientific | |
115 | context. For example, all of the following will be considered a | |
116 | number: | |
117 | 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5 | |
118 | ||
119 | Other options offered by the customize interface are more restrictive." | |
120 | :group 'org-table-settings | |
121 | :type '(choice | |
122 | (const :tag "Positive Integers" | |
123 | "^[0-9]+$") | |
124 | (const :tag "Integers" | |
125 | "^[-+]?[0-9]+$") | |
126 | (const :tag "Floating Point Numbers" | |
127 | "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$") | |
128 | (const :tag "Floating Point Number or Integer" | |
129 | "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$") | |
130 | (const :tag "Exponential, Floating point, Integer" | |
131 | "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$") | |
132 | (const :tag "Very General Number-Like, including hex" | |
133 | "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$") | |
134 | (string :tag "Regexp:"))) | |
135 | ||
136 | (defcustom org-table-number-fraction 0.5 | |
137 | "Fraction of numbers in a column required to make the column align right. | |
138 | In a column all non-white fields are considered. If at least this | |
139 | fraction of fields is matched by `org-table-number-fraction', | |
140 | alignment to the right border applies." | |
141 | :group 'org-table-settings | |
142 | :type 'number) | |
143 | ||
144 | (defgroup org-table-editing nil | |
145 | "Behavior of tables during editing in Org-mode." | |
146 | :tag "Org Table Editing" | |
147 | :group 'org-table) | |
148 | ||
149 | (defcustom org-table-automatic-realign t | |
ed21c5c8 | 150 | "Non-nil means automatically re-align table when pressing TAB or RETURN. |
20908596 CD |
151 | When nil, aligning is only done with \\[org-table-align], or after column |
152 | removal/insertion." | |
153 | :group 'org-table-editing | |
154 | :type 'boolean) | |
155 | ||
156 | (defcustom org-table-auto-blank-field t | |
ed21c5c8 | 157 | "Non-nil means automatically blank table field when starting to type into it. |
20908596 CD |
158 | This only happens when typing immediately after a field motion |
159 | command (TAB, S-TAB or RET). | |
160 | Only relevant when `org-enable-table-editor' is equal to `optimized'." | |
161 | :group 'org-table-editing | |
162 | :type 'boolean) | |
163 | ||
164 | (defcustom org-table-tab-jumps-over-hlines t | |
ed21c5c8 | 165 | "Non-nil means tab in the last column of a table with jump over a hline. |
20908596 CD |
166 | If a horizontal separator line is following the current line, |
167 | `org-table-next-field' can either create a new row before that line, or jump | |
168 | over the line. When this option is nil, a new line will be created before | |
169 | this line." | |
170 | :group 'org-table-editing | |
171 | :type 'boolean) | |
172 | ||
173 | (defgroup org-table-calculation nil | |
174 | "Options concerning tables in Org-mode." | |
175 | :tag "Org Table Calculation" | |
176 | :group 'org-table) | |
177 | ||
178 | (defcustom org-table-use-standard-references t | |
33306645 | 179 | "Should org-mode work with table references like B3 instead of @3$2? |
20908596 CD |
180 | Possible values are: |
181 | nil never use them | |
182 | from accept as input, do not present for editing | |
183 | t: accept as input and present for editing" | |
184 | :group 'org-table-calculation | |
185 | :type '(choice | |
186 | (const :tag "Never, don't even check user input for them" nil) | |
187 | (const :tag "Always, both as user input, and when editing" t) | |
188 | (const :tag "Convert user input, don't offer during editing" 'from))) | |
189 | ||
190 | (defcustom org-table-copy-increment t | |
ed21c5c8 | 191 | "Non-nil means increment when copying current field with \\[org-table-copy-down]." |
20908596 CD |
192 | :group 'org-table-calculation |
193 | :type 'boolean) | |
194 | ||
195 | (defcustom org-calc-default-modes | |
196 | '(calc-internal-prec 12 | |
b349f79f | 197 | calc-float-format (float 8) |
20908596 CD |
198 | calc-angle-mode deg |
199 | calc-prefer-frac nil | |
200 | calc-symbolic-mode nil | |
621f83e4 | 201 | calc-date-format (YYYY "-" MM "-" DD " " Www (" " hh ":" mm)) |
20908596 CD |
202 | calc-display-working-message t |
203 | ) | |
86fbb8ca | 204 | "List with Calc mode settings for use in `calc-eval' for table formulas. |
20908596 CD |
205 | The list must contain alternating symbols (Calc modes variables and values). |
206 | Don't remove any of the default settings, just change the values. Org-mode | |
207 | relies on the variables to be present in the list." | |
208 | :group 'org-table-calculation | |
209 | :type 'plist) | |
210 | ||
211 | (defcustom org-table-formula-evaluate-inline t | |
ed21c5c8 | 212 | "Non-nil means TAB and RET evaluate a formula in current table field. |
20908596 CD |
213 | If the current field starts with an equal sign, it is assumed to be a formula |
214 | which should be evaluated as described in the manual and in the documentation | |
215 | string of the command `org-table-eval-formula'. This feature requires the | |
216 | Emacs calc package. | |
217 | When this variable is nil, formula calculation is only available through | |
218 | the command \\[org-table-eval-formula]." | |
219 | :group 'org-table-calculation | |
220 | :type 'boolean) | |
221 | ||
222 | (defcustom org-table-formula-use-constants t | |
ed21c5c8 | 223 | "Non-nil means interpret constants in formulas in tables. |
20908596 CD |
224 | A constant looks like `$c' or `$Grav' and will be replaced before evaluation |
225 | by the value given in `org-table-formula-constants', or by a value obtained | |
226 | from the `constants.el' package." | |
227 | :group 'org-table-calculation | |
228 | :type 'boolean) | |
229 | ||
230 | (defcustom org-table-formula-constants nil | |
231 | "Alist with constant names and values, for use in table formulas. | |
232 | The car of each element is a name of a constant, without the `$' before it. | |
233 | The cdr is the value as a string. For example, if you'd like to use the | |
234 | speed of light in a formula, you would configure | |
235 | ||
236 | (setq org-table-formula-constants '((\"c\" . \"299792458.\"))) | |
237 | ||
238 | and then use it in an equation like `$1*$c'. | |
239 | ||
240 | Constants can also be defined on a per-file basis using a line like | |
241 | ||
242 | #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6" | |
243 | :group 'org-table-calculation | |
244 | :type '(repeat | |
245 | (cons (string :tag "name") | |
246 | (string :tag "value")))) | |
247 | ||
248 | (defcustom org-table-allow-automatic-line-recalculation t | |
ed21c5c8 CD |
249 | "Non-nil means lines marked with |#| or |*| will be recomputed automatically. |
250 | Automatically means when TAB or RET or C-c C-c are pressed in the line." | |
20908596 CD |
251 | :group 'org-table-calculation |
252 | :type 'boolean) | |
253 | ||
ff4be292 | 254 | (defcustom org-table-error-on-row-ref-crossing-hline t |
c8d0cf5c | 255 | "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'." |
ff4be292 CD |
256 | :group 'org-table |
257 | :type 'boolean) | |
258 | ||
c8d0cf5c | 259 | (defcustom org-table-relative-ref-may-cross-hline t |
ed21c5c8 | 260 | "Non-nil means relative formula references may cross hlines. |
c8d0cf5c CD |
261 | Here are the allowed values: |
262 | ||
263 | nil Relative references may not cross hlines. They will reference the | |
264 | field next to the hline instead. Coming from below, the reference | |
265 | will be to the field below the hline. Coming from above, it will be | |
266 | to the field above. | |
8bfe682a | 267 | t Relative references may cross hlines. |
c8d0cf5c CD |
268 | error An attempt to cross a hline will throw an error. |
269 | ||
270 | It is probably good to never set this variable to nil, for the sake of | |
271 | portability of tables." | |
272 | :group 'org-table-calculation | |
273 | :type '(choice | |
274 | (const :tag "Allow to cross" t) | |
275 | (const :tag "Stick to hline" nil) | |
276 | (const :tag "Error on attempt to cross" error))) | |
277 | ||
20908596 CD |
278 | (defgroup org-table-import-export nil |
279 | "Options concerning table import and export in Org-mode." | |
280 | :tag "Org Table Import Export" | |
281 | :group 'org-table) | |
282 | ||
b349f79f | 283 | (defcustom org-table-export-default-format "orgtbl-to-tsv" |
86fbb8ca CD |
284 | "Default export parameters for `org-table-export'. |
285 | These can be overridden for a specific table by setting the | |
286 | TABLE_EXPORT_FORMAT property. See the manual section on orgtbl | |
287 | radio tables for the different export transformations and | |
288 | available parameters." | |
20908596 CD |
289 | :group 'org-table-import-export |
290 | :type 'string) | |
291 | ||
292 | (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)" | |
293 | "Detects a table line marked for automatic recalculation.") | |
294 | (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)" | |
295 | "Detects a table line marked for automatic recalculation.") | |
296 | (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)" | |
297 | "Detects a table line marked for automatic recalculation.") | |
298 | (defconst org-table-border-regexp "^[ \t]*[^| \t]" | |
86fbb8ca | 299 | "Searching from within a table (any type) this finds the first line outside the table.") |
20908596 CD |
300 | (defvar org-table-last-highlighted-reference nil) |
301 | (defvar org-table-formula-history nil) | |
302 | ||
303 | (defvar org-table-column-names nil | |
304 | "Alist with column names, derived from the `!' line.") | |
305 | (defvar org-table-column-name-regexp nil | |
306 | "Regular expression matching the current column names.") | |
307 | (defvar org-table-local-parameters nil | |
308 | "Alist with parameter names, derived from the `$' line.") | |
309 | (defvar org-table-named-field-locations nil | |
310 | "Alist with locations of named fields.") | |
311 | ||
312 | (defvar org-table-current-line-types nil | |
86fbb8ca | 313 | "Table row types, non-nil only for the duration of a command.") |
20908596 | 314 | (defvar org-table-current-begin-line nil |
86fbb8ca | 315 | "Table begin line, non-nil only for the duration of a command.") |
20908596 | 316 | (defvar org-table-current-begin-pos nil |
86fbb8ca | 317 | "Table begin position, non-nil only for the duration of a command.") |
20908596 CD |
318 | (defvar org-table-dlines nil |
319 | "Vector of data line line numbers in the current table.") | |
320 | (defvar org-table-hlines nil | |
321 | "Vector of hline line numbers in the current table.") | |
322 | ||
323 | (defconst org-table-range-regexp | |
324 | "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?" | |
325 | ;; 1 2 3 4 5 | |
326 | "Regular expression for matching ranges in formulas.") | |
327 | ||
328 | (defconst org-table-range-regexp2 | |
329 | (concat | |
330 | "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)" | |
331 | "\\.\\." | |
332 | "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)") | |
333 | "Match a range for reference display.") | |
334 | ||
86fbb8ca CD |
335 | (defun org-table-colgroup-line-p (line) |
336 | "Is this a table line colgroup information?" | |
337 | (save-match-data | |
338 | (and (string-match "[<>]\\|&[lg]t;" line) | |
339 | (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'" | |
340 | line) | |
341 | (not (delq | |
342 | nil | |
343 | (mapcar | |
344 | (lambda (s) | |
345 | (not (member s '("" "<" ">" "<>" "<" ">" "<>")))) | |
346 | (org-split-string (match-string 1 line) "[ \t]*|[ \t]*"))))))) | |
347 | ||
348 | (defun org-table-cookie-line-p (line) | |
349 | "Is this a table line with only alignment/width cookies?" | |
86fbb8ca CD |
350 | (save-match-data |
351 | (and (string-match "[<>]\\|&[lg]t;" line) | |
afe98dfa CD |
352 | (or (string-match |
353 | "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line) | |
354 | (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line)) | |
86fbb8ca CD |
355 | (not (delq nil (mapcar |
356 | (lambda (s) | |
357 | (not (or (equal s "") | |
afe98dfa CD |
358 | (string-match |
359 | "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s) | |
360 | (string-match | |
361 | "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" | |
362 | s)))) | |
363 | (org-split-string (match-string 1 line) | |
364 | "[ \t]*|[ \t]*"))))))) | |
86fbb8ca | 365 | |
20908596 CD |
366 | (defconst org-table-translate-regexp |
367 | (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)") | |
368 | "Match a reference that needs translation, for reference display.") | |
369 | ||
370 | (defun org-table-create-with-table.el () | |
371 | "Use the table.el package to insert a new table. | |
372 | If there is already a table at point, convert between Org-mode tables | |
373 | and table.el tables." | |
374 | (interactive) | |
375 | (require 'table) | |
376 | (cond | |
377 | ((org-at-table.el-p) | |
378 | (if (y-or-n-p "Convert table to Org-mode table? ") | |
379 | (org-table-convert))) | |
380 | ((org-at-table-p) | |
afe98dfa CD |
381 | (when (y-or-n-p "Convert table to table.el table? ") |
382 | (org-table-align) | |
383 | (org-table-convert))) | |
20908596 CD |
384 | (t (call-interactively 'table-insert)))) |
385 | ||
386 | (defun org-table-create-or-convert-from-region (arg) | |
387 | "Convert region to table, or create an empty table. | |
388 | If there is an active region, convert it to a table, using the function | |
389 | `org-table-convert-region'. See the documentation of that function | |
390 | to learn how the prefix argument is interpreted to determine the field | |
391 | separator. | |
392 | If there is no such region, create an empty table with `org-table-create'." | |
393 | (interactive "P") | |
394 | (if (org-region-active-p) | |
395 | (org-table-convert-region (region-beginning) (region-end) arg) | |
396 | (org-table-create arg))) | |
397 | ||
398 | (defun org-table-create (&optional size) | |
399 | "Query for a size and insert a table skeleton. | |
400 | SIZE is a string Columns x Rows like for example \"3x2\"." | |
401 | (interactive "P") | |
402 | (unless size | |
403 | (setq size (read-string | |
404 | (concat "Table size Columns x Rows [e.g. " | |
405 | org-table-default-size "]: ") | |
406 | "" nil org-table-default-size))) | |
407 | ||
408 | (let* ((pos (point)) | |
409 | (indent (make-string (current-column) ?\ )) | |
410 | (split (org-split-string size " *x *")) | |
411 | (rows (string-to-number (nth 1 split))) | |
412 | (columns (string-to-number (car split))) | |
413 | (line (concat (apply 'concat indent "|" (make-list columns " |")) | |
414 | "\n"))) | |
415 | (if (string-match "^[ \t]*$" (buffer-substring-no-properties | |
416 | (point-at-bol) (point))) | |
417 | (beginning-of-line 1) | |
418 | (newline)) | |
419 | ;; (mapcar (lambda (x) (insert line)) (make-list rows t)) | |
420 | (dotimes (i rows) (insert line)) | |
421 | (goto-char pos) | |
422 | (if (> rows 1) | |
423 | ;; Insert a hline after the first row. | |
424 | (progn | |
425 | (end-of-line 1) | |
426 | (insert "\n|-") | |
427 | (goto-char pos))) | |
428 | (org-table-align))) | |
429 | ||
430 | (defun org-table-convert-region (beg0 end0 &optional separator) | |
431 | "Convert region to a table. | |
432 | The region goes from BEG0 to END0, but these borders will be moved | |
433 | slightly, to make sure a beginning of line in the first line is included. | |
434 | ||
435 | SEPARATOR specifies the field separator in the lines. It can have the | |
436 | following values: | |
437 | ||
438 | '(4) Use the comma as a field separator | |
439 | '(16) Use a TAB as field separator | |
440 | integer When a number, use that many spaces as field separator | |
441 | nil When nil, the command tries to be smart and figure out the | |
442 | separator in the following way: | |
443 | - when each line contains a TAB, assume TAB-separated material | |
33306645 | 444 | - when each line contains a comma, assume CSV material |
40ac2137 | 445 | - else, assume one or more SPACE characters as separator." |
20908596 CD |
446 | (interactive "rP") |
447 | (let* ((beg (min beg0 end0)) | |
448 | (end (max beg0 end0)) | |
449 | re) | |
450 | (goto-char beg) | |
451 | (beginning-of-line 1) | |
452 | (setq beg (move-marker (make-marker) (point))) | |
453 | (goto-char end) | |
454 | (if (bolp) (backward-char 1) (end-of-line 1)) | |
455 | (setq end (move-marker (make-marker) (point))) | |
456 | ;; Get the right field separator | |
457 | (unless separator | |
458 | (goto-char beg) | |
459 | (setq separator | |
460 | (cond | |
461 | ((not (re-search-forward "^[^\n\t]+$" end t)) '(16)) | |
462 | ((not (re-search-forward "^[^\n,]+$" end t)) '(4)) | |
463 | (t 1)))) | |
20908596 | 464 | (goto-char beg) |
8bfe682a | 465 | (if (equal separator '(4)) |
afe98dfa | 466 | (while (< (point) end) |
8bfe682a CD |
467 | ;; parse the csv stuff |
468 | (cond | |
469 | ((looking-at "^") (insert "| ")) | |
470 | ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2)) | |
471 | ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"") | |
472 | (replace-match "\\1") | |
473 | (if (looking-at "\"") (insert "\""))) | |
474 | ((looking-at "[^,\n]+") (goto-char (match-end 0))) | |
475 | ((looking-at "[ \t]*,") (replace-match " | ")) | |
476 | (t (beginning-of-line 2)))) | |
477 | (setq re (cond | |
478 | ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?") | |
479 | ((equal separator '(16)) "^\\|\t") | |
480 | ((integerp separator) | |
481 | (format "^ *\\| *\t *\\| \\{%d,\\}" separator)) | |
482 | (t (error "This should not happen")))) | |
483 | (while (re-search-forward re end t) | |
484 | (replace-match "| " t t))) | |
20908596 | 485 | (goto-char beg) |
20908596 CD |
486 | (org-table-align))) |
487 | ||
488 | (defun org-table-import (file arg) | |
489 | "Import FILE as a table. | |
490 | The file is assumed to be tab-separated. Such files can be produced by most | |
491 | spreadsheet and database applications. If no tabs (at least one per line) | |
492 | are found, lines will be split on whitespace into fields." | |
493 | (interactive "f\nP") | |
494 | (or (bolp) (newline)) | |
495 | (let ((beg (point)) | |
496 | (pm (point-max))) | |
497 | (insert-file-contents file) | |
498 | (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg))) | |
499 | ||
500 | ||
501 | (defvar org-table-last-alignment) | |
502 | (defvar org-table-last-column-widths) | |
503 | (defun org-table-export (&optional file format) | |
b349f79f | 504 | "Export table to a file, with configurable format. |
20908596 CD |
505 | Such a file can be imported into a spreadsheet program like Excel. |
506 | FILE can be the output file name. If not given, it will be taken from | |
507 | a TABLE_EXPORT_FILE property in the current entry or higher up in the | |
508 | hierarchy, or the user will be prompted for a file name. | |
509 | FORMAT can be an export format, of the same kind as it used when | |
86fbb8ca | 510 | `orgtbl-mode' sends a table in a different format. The default format can |
20908596 CD |
511 | be found in the variable `org-table-export-default-format', but the function |
512 | first checks if there is an export format specified in a TABLE_EXPORT_FORMAT | |
513 | property, locally or anywhere up in the hierarchy." | |
514 | (interactive) | |
b349f79f CD |
515 | (unless (org-at-table-p) |
516 | (error "No table at point")) | |
517 | (require 'org-exp) | |
20908596 CD |
518 | (org-table-align) ;; make sure we have everything we need |
519 | (let* ((beg (org-table-begin)) | |
520 | (end (org-table-end)) | |
521 | (txt (buffer-substring-no-properties beg end)) | |
2c3ad40d CD |
522 | (file (or file |
523 | (condition-case nil | |
524 | (org-entry-get beg "TABLE_EXPORT_FILE" t) | |
525 | (error nil)))) | |
526 | (format (or format | |
527 | (condition-case nil | |
528 | (org-entry-get beg "TABLE_EXPORT_FORMAT" t) | |
529 | (error nil)))) | |
b349f79f CD |
530 | buf deffmt-readable) |
531 | (unless file | |
532 | (setq file (read-file-name "Export table to: ")) | |
533 | (unless (or (not (file-exists-p file)) | |
534 | (y-or-n-p (format "Overwrite file %s? " file))) | |
535 | (error "Abort"))) | |
536 | (if (file-directory-p file) | |
537 | (error "This is a directory path, not a file")) | |
c8d0cf5c CD |
538 | (if (and (buffer-file-name) |
539 | (equal (file-truename file) | |
540 | (file-truename (buffer-file-name)))) | |
b349f79f CD |
541 | (error "Please specify a file name that is different from current")) |
542 | (unless format | |
543 | (setq deffmt-readable org-table-export-default-format) | |
544 | (while (string-match "\t" deffmt-readable) | |
545 | (setq deffmt-readable (replace-match "\\t" t t deffmt-readable))) | |
546 | (while (string-match "\n" deffmt-readable) | |
547 | (setq deffmt-readable (replace-match "\\n" t t deffmt-readable))) | |
2c3ad40d CD |
548 | (setq format (org-completing-read |
549 | "Format: " | |
550 | '("orgtbl-to-tsv" "orgtbl-to-csv" | |
551 | "orgtbl-to-latex" "orgtbl-to-html" | |
552 | "orgtbl-to-generic" "orgtbl-to-texinfo" | |
553 | "orgtbl-to-orgtbl") nil nil | |
554 | deffmt-readable))) | |
20908596 CD |
555 | (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format) |
556 | (let* ((transform (intern (match-string 1 format))) | |
557 | (params (if (match-end 2) | |
558 | (read (concat "(" (match-string 2 format) ")")))) | |
559 | (skip (plist-get params :skip)) | |
560 | (skipcols (plist-get params :skipcols)) | |
561 | (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*"))) | |
562 | (lines (org-table-clean-before-export lines)) | |
563 | (i0 (if org-table-clean-did-remove-column 2 1)) | |
564 | (table (mapcar | |
565 | (lambda (x) | |
566 | (if (string-match org-table-hline-regexp x) | |
567 | 'hline | |
568 | (org-remove-by-index | |
569 | (org-split-string (org-trim x) "\\s-*|\\s-*") | |
570 | skipcols i0))) | |
571 | lines)) | |
572 | (fun (if (= i0 2) 'cdr 'identity)) | |
573 | (org-table-last-alignment | |
574 | (org-remove-by-index (funcall fun org-table-last-alignment) | |
575 | skipcols i0)) | |
576 | (org-table-last-column-widths | |
577 | (org-remove-by-index (funcall fun org-table-last-column-widths) | |
578 | skipcols i0))) | |
579 | ||
580 | (unless (fboundp transform) | |
581 | (error "No such transformation function %s" transform)) | |
582 | (setq txt (funcall transform table params)) | |
583 | ||
584 | (with-current-buffer (find-file-noselect file) | |
585 | (setq buf (current-buffer)) | |
586 | (erase-buffer) | |
587 | (fundamental-mode) | |
588 | (insert txt "\n") | |
589 | (save-buffer)) | |
590 | (kill-buffer buf) | |
591 | (message "Export done.")) | |
592 | (error "TABLE_EXPORT_FORMAT invalid")))) | |
593 | ||
594 | (defvar org-table-aligned-begin-marker (make-marker) | |
595 | "Marker at the beginning of the table last aligned. | |
596 | Used to check if cursor still is in that table, to minimize realignment.") | |
597 | (defvar org-table-aligned-end-marker (make-marker) | |
598 | "Marker at the end of the table last aligned. | |
599 | Used to check if cursor still is in that table, to minimize realignment.") | |
600 | (defvar org-table-last-alignment nil | |
601 | "List of flags for flushright alignment, from the last re-alignment. | |
602 | This is being used to correctly align a single field after TAB or RET.") | |
603 | (defvar org-table-last-column-widths nil | |
604 | "List of max width of fields in each column. | |
605 | This is being used to correctly align a single field after TAB or RET.") | |
606 | (defvar org-table-formula-debug nil | |
ed21c5c8 | 607 | "Non-nil means debug table formulas. |
20908596 CD |
608 | When nil, simply write \"#ERROR\" in corrupted fields.") |
609 | (make-variable-buffer-local 'org-table-formula-debug) | |
610 | (defvar org-table-overlay-coordinates nil | |
611 | "Overlay coordinates after each align of a table.") | |
612 | (make-variable-buffer-local 'org-table-overlay-coordinates) | |
613 | ||
614 | (defvar org-last-recalc-line nil) | |
ed21c5c8 | 615 | (defvar org-table-do-narrow t) ; for dynamic scoping |
20908596 CD |
616 | (defconst org-narrow-column-arrow "=>" |
617 | "Used as display property in narrowed table columns.") | |
618 | ||
619 | (defun org-table-align () | |
620 | "Align the table at point by aligning all vertical bars." | |
621 | (interactive) | |
622 | (let* ( | |
623 | ;; Limits of table | |
624 | (beg (org-table-begin)) | |
625 | (end (org-table-end)) | |
626 | ;; Current cursor position | |
627 | (linepos (org-current-line)) | |
628 | (colpos (org-table-current-column)) | |
629 | (winstart (window-start)) | |
630 | (winstartline (org-current-line (min winstart (1- (point-max))))) | |
631 | lines (new "") lengths l typenums ty fields maxfields i | |
632 | column | |
633 | (indent "") cnt frac | |
634 | rfmt hfmt | |
635 | (spaces '(1 . 1)) | |
636 | (sp1 (car spaces)) | |
637 | (sp2 (cdr spaces)) | |
638 | (rfmt1 (concat | |
639 | (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|")) | |
640 | (hfmt1 (concat | |
641 | (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+")) | |
86fbb8ca CD |
642 | emptystrings links dates emph raise narrow |
643 | falign falign1 fmax f1 len c e space) | |
20908596 CD |
644 | (untabify beg end) |
645 | (remove-text-properties beg end '(org-cwidth t org-dwidth t display t)) | |
646 | ;; Check if we have links or dates | |
647 | (goto-char beg) | |
648 | (setq links (re-search-forward org-bracket-link-regexp end t)) | |
649 | (goto-char beg) | |
650 | (setq emph (and org-hide-emphasis-markers | |
651 | (re-search-forward org-emph-re end t))) | |
652 | (goto-char beg) | |
86fbb8ca CD |
653 | (setq raise (and org-use-sub-superscripts |
654 | (re-search-forward org-match-substring-regexp end t))) | |
655 | (goto-char beg) | |
20908596 CD |
656 | (setq dates (and org-display-custom-times |
657 | (re-search-forward org-ts-regexp-both end t))) | |
658 | ;; Make sure the link properties are right | |
659 | (when links (goto-char beg) (while (org-activate-bracket-links end))) | |
660 | ;; Make sure the date properties are right | |
661 | (when dates (goto-char beg) (while (org-activate-dates end))) | |
662 | (when emph (goto-char beg) (while (org-do-emphasis-faces end))) | |
86fbb8ca | 663 | (when raise (goto-char beg) (while (org-raise-scripts end))) |
20908596 CD |
664 | |
665 | ;; Check if we are narrowing any columns | |
666 | (goto-char beg) | |
ed21c5c8 CD |
667 | (setq narrow (and org-table-do-narrow |
668 | org-format-transports-properties-p | |
afe98dfa | 669 | (re-search-forward "<[lrc]?[0-9]+>" end t))) |
c8d0cf5c | 670 | (goto-char beg) |
afe98dfa | 671 | (setq falign (re-search-forward "<[lrc][0-9]*>" end t)) |
8d642074 | 672 | (goto-char beg) |
20908596 CD |
673 | ;; Get the rows |
674 | (setq lines (org-split-string | |
675 | (buffer-substring beg end) "\n")) | |
676 | ;; Store the indentation of the first line | |
677 | (if (string-match "^ *" (car lines)) | |
678 | (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ ))) | |
679 | ;; Mark the hlines by setting the corresponding element to nil | |
680 | ;; At the same time, we remove trailing space. | |
681 | (setq lines (mapcar (lambda (l) | |
682 | (if (string-match "^ *|-" l) | |
683 | nil | |
684 | (if (string-match "[ \t]+$" l) | |
685 | (substring l 0 (match-beginning 0)) | |
686 | l))) | |
687 | lines)) | |
688 | ;; Get the data fields by splitting the lines. | |
689 | (setq fields (mapcar | |
690 | (lambda (l) | |
691 | (org-split-string l " *| *")) | |
692 | (delq nil (copy-sequence lines)))) | |
693 | ;; How many fields in the longest line? | |
694 | (condition-case nil | |
695 | (setq maxfields (apply 'max (mapcar 'length fields))) | |
696 | (error | |
697 | (kill-region beg end) | |
698 | (org-table-create org-table-default-size) | |
699 | (error "Empty table - created default table"))) | |
700 | ;; A list of empty strings to fill any short rows on output | |
701 | (setq emptystrings (make-list maxfields "")) | |
702 | ;; Check for special formatting. | |
703 | (setq i -1) | |
704 | (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns | |
705 | (setq column (mapcar (lambda (x) (or (nth i x) "")) fields)) | |
706 | ;; Check if there is an explicit width specified | |
ed21c5c8 | 707 | (setq fmax nil) |
c8d0cf5c CD |
708 | (when (or narrow falign) |
709 | (setq c column fmax nil falign1 nil) | |
20908596 CD |
710 | (while c |
711 | (setq e (pop c)) | |
afe98dfa | 712 | (when (and (stringp e) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e)) |
c8d0cf5c | 713 | (if (match-end 1) (setq falign1 (match-string 1 e))) |
ed21c5c8 | 714 | (if (and org-table-do-narrow (match-end 2)) |
c8d0cf5c | 715 | (setq fmax (string-to-number (match-string 2 e)) c nil)))) |
20908596 CD |
716 | ;; Find fields that are wider than fmax, and shorten them |
717 | (when fmax | |
718 | (loop for xx in column do | |
719 | (when (and (stringp xx) | |
720 | (> (org-string-width xx) fmax)) | |
721 | (org-add-props xx nil | |
722 | 'help-echo | |
723 | (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx)))) | |
724 | (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax))) | |
725 | (unless (> f1 1) | |
726 | (error "Cannot narrow field starting with wide link \"%s\"" | |
727 | (match-string 0 xx))) | |
728 | (add-text-properties f1 (length xx) (list 'org-cwidth t) xx) | |
729 | (add-text-properties (- f1 2) f1 | |
730 | (list 'display org-narrow-column-arrow) | |
731 | xx))))) | |
732 | ;; Get the maximum width for each column | |
ed21c5c8 CD |
733 | (push (apply 'max (or fmax 1) 1 (mapcar 'org-string-width column)) |
734 | lengths) | |
20908596 | 735 | ;; Get the fraction of numbers, to decide about alignment of the column |
c8d0cf5c CD |
736 | (if falign1 |
737 | (push (equal (downcase falign1) "r") typenums) | |
738 | (setq cnt 0 frac 0.0) | |
739 | (loop for x in column do | |
740 | (if (equal x "") | |
741 | nil | |
742 | (setq frac ( / (+ (* frac cnt) | |
743 | (if (string-match org-table-number-regexp x) 1 0)) | |
744 | (setq cnt (1+ cnt)))))) | |
745 | (push (>= frac org-table-number-fraction) typenums))) | |
20908596 CD |
746 | (setq lengths (nreverse lengths) typenums (nreverse typenums)) |
747 | ||
748 | ;; Store the alignment of this table, for later editing of single fields | |
749 | (setq org-table-last-alignment typenums | |
750 | org-table-last-column-widths lengths) | |
751 | ||
752 | ;; With invisible characters, `format' does not get the field width right | |
753 | ;; So we need to make these fields wide by hand. | |
86fbb8ca | 754 | (when (or links emph raise) |
20908596 CD |
755 | (loop for i from 0 upto (1- maxfields) do |
756 | (setq len (nth i lengths)) | |
757 | (loop for j from 0 upto (1- (length fields)) do | |
758 | (setq c (nthcdr i (car (nthcdr j fields)))) | |
759 | (if (and (stringp (car c)) | |
86fbb8ca CD |
760 | (or (text-property-any 0 (length (car c)) |
761 | 'invisible 'org-link (car c)) | |
762 | (text-property-any 0 (length (car c)) | |
763 | 'org-dwidth t (car c))) | |
20908596 | 764 | (< (org-string-width (car c)) len)) |
86fbb8ca CD |
765 | (progn |
766 | (setq space (make-string (- len (org-string-width (car c))) ?\ )) | |
767 | (setcar c (if (nth i typenums) | |
768 | (concat space (car c)) | |
769 | (concat (car c) space)))))))) | |
20908596 CD |
770 | |
771 | ;; Compute the formats needed for output of the table | |
772 | (setq rfmt (concat indent "|") hfmt (concat indent "|")) | |
773 | (while (setq l (pop lengths)) | |
774 | (setq ty (if (pop typenums) "" "-")) ; number types flushright | |
775 | (setq rfmt (concat rfmt (format rfmt1 ty l)) | |
776 | hfmt (concat hfmt (format hfmt1 (make-string l ?-))))) | |
777 | (setq rfmt (concat rfmt "\n") | |
778 | hfmt (concat (substring hfmt 0 -1) "|\n")) | |
779 | ||
780 | (setq new (mapconcat | |
781 | (lambda (l) | |
782 | (if l (apply 'format rfmt | |
783 | (append (pop fields) emptystrings)) | |
784 | hfmt)) | |
785 | lines "")) | |
c8d0cf5c CD |
786 | (if (equal (char-before) ?\n) |
787 | ;; This hack is for org-indent, to force redisplay of the | |
788 | ;; line prefix of the first line. Apparently the redisplay | |
789 | ;; is tied to the newline, which is, I think, a bug. | |
790 | ;; To force this redisplay, we remove and re-insert the | |
791 | ;; newline, so that the redisplay engine thinks it belongs | |
792 | ;; to the changed text. | |
793 | (progn | |
794 | (backward-delete-char 1) | |
795 | (insert "\n"))) | |
20908596 CD |
796 | (move-marker org-table-aligned-begin-marker (point)) |
797 | (insert new) | |
54a0dee5 CD |
798 | ;; Replace the old one |
799 | (delete-region (point) end) | |
800 | (move-marker end nil) | |
20908596 CD |
801 | (move-marker org-table-aligned-end-marker (point)) |
802 | (when (and orgtbl-mode (not (org-mode-p))) | |
803 | (goto-char org-table-aligned-begin-marker) | |
804 | (while (org-hide-wide-columns org-table-aligned-end-marker))) | |
805 | ;; Try to move to the old location | |
54a0dee5 | 806 | (org-goto-line winstartline) |
20908596 | 807 | (setq winstart (point-at-bol)) |
54a0dee5 | 808 | (org-goto-line linepos) |
20908596 CD |
809 | (set-window-start (selected-window) winstart 'noforce) |
810 | (org-table-goto-column colpos) | |
811 | (and org-table-overlay-coordinates (org-table-overlay-coordinates)) | |
812 | (setq org-table-may-need-update nil) | |
813 | )) | |
814 | ||
20908596 CD |
815 | (defun org-table-begin (&optional table-type) |
816 | "Find the beginning of the table and return its position. | |
817 | With argument TABLE-TYPE, go to the beginning of a table.el-type table." | |
818 | (save-excursion | |
819 | (if (not (re-search-backward | |
820 | (if table-type org-table-any-border-regexp | |
821 | org-table-border-regexp) | |
822 | nil t)) | |
823 | (progn (goto-char (point-min)) (point)) | |
824 | (goto-char (match-beginning 0)) | |
825 | (beginning-of-line 2) | |
826 | (point)))) | |
827 | ||
828 | (defun org-table-end (&optional table-type) | |
829 | "Find the end of the table and return its position. | |
830 | With argument TABLE-TYPE, go to the end of a table.el-type table." | |
831 | (save-excursion | |
832 | (if (not (re-search-forward | |
833 | (if table-type org-table-any-border-regexp | |
834 | org-table-border-regexp) | |
835 | nil t)) | |
836 | (goto-char (point-max)) | |
837 | (goto-char (match-beginning 0))) | |
838 | (point-marker))) | |
839 | ||
840 | (defun org-table-justify-field-maybe (&optional new) | |
841 | "Justify the current field, text to left, number to right. | |
842 | Optional argument NEW may specify text to replace the current field content." | |
843 | (cond | |
844 | ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway | |
845 | ((org-at-table-hline-p)) | |
846 | ((and (not new) | |
847 | (or (not (equal (marker-buffer org-table-aligned-begin-marker) | |
848 | (current-buffer))) | |
849 | (< (point) org-table-aligned-begin-marker) | |
850 | (>= (point) org-table-aligned-end-marker))) | |
851 | ;; This is not the same table, force a full re-align | |
852 | (setq org-table-may-need-update t)) | |
853 | (t ;; realign the current field, based on previous full realign | |
854 | (let* ((pos (point)) s | |
855 | (col (org-table-current-column)) | |
856 | (num (if (> col 0) (nth (1- col) org-table-last-alignment))) | |
857 | l f n o e) | |
858 | (when (> col 0) | |
859 | (skip-chars-backward "^|\n") | |
860 | (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)") | |
861 | (progn | |
862 | (setq s (match-string 1) | |
863 | o (match-string 0) | |
864 | l (max 1 (- (match-end 0) (match-beginning 0) 3)) | |
865 | e (not (= (match-beginning 2) (match-end 2)))) | |
866 | (setq f (format (if num " %%%ds %s" " %%-%ds %s") | |
867 | l (if e "|" (setq org-table-may-need-update t) "")) | |
868 | n (format f s)) | |
869 | (if new | |
870 | (if (<= (length new) l) ;; FIXME: length -> str-width? | |
871 | (setq n (format f new)) | |
872 | (setq n (concat new "|") org-table-may-need-update t))) | |
86fbb8ca | 873 | (if (equal (string-to-char n) ?-) (setq n (concat " " n))) |
20908596 CD |
874 | (or (equal n o) |
875 | (let (org-table-may-need-update) | |
876 | (replace-match n t t)))) | |
877 | (setq org-table-may-need-update t)) | |
878 | (goto-char pos)))))) | |
879 | ||
880 | (defun org-table-next-field () | |
881 | "Go to the next field in the current table, creating new lines as needed. | |
882 | Before doing so, re-align the table if necessary." | |
883 | (interactive) | |
884 | (org-table-maybe-eval-formula) | |
885 | (org-table-maybe-recalculate-line) | |
886 | (if (and org-table-automatic-realign | |
887 | org-table-may-need-update) | |
888 | (org-table-align)) | |
889 | (let ((end (org-table-end))) | |
890 | (if (org-at-table-hline-p) | |
891 | (end-of-line 1)) | |
892 | (condition-case nil | |
893 | (progn | |
894 | (re-search-forward "|" end) | |
895 | (if (looking-at "[ \t]*$") | |
896 | (re-search-forward "|" end)) | |
897 | (if (and (looking-at "-") | |
898 | org-table-tab-jumps-over-hlines | |
899 | (re-search-forward "^[ \t]*|\\([^-]\\)" end t)) | |
900 | (goto-char (match-beginning 1))) | |
901 | (if (looking-at "-") | |
902 | (progn | |
903 | (beginning-of-line 0) | |
904 | (org-table-insert-row 'below)) | |
905 | (if (looking-at " ") (forward-char 1)))) | |
906 | (error | |
907 | (org-table-insert-row 'below))))) | |
908 | ||
909 | (defun org-table-previous-field () | |
910 | "Go to the previous field in the table. | |
911 | Before doing so, re-align the table if necessary." | |
912 | (interactive) | |
913 | (org-table-justify-field-maybe) | |
914 | (org-table-maybe-recalculate-line) | |
915 | (if (and org-table-automatic-realign | |
916 | org-table-may-need-update) | |
917 | (org-table-align)) | |
918 | (if (org-at-table-hline-p) | |
919 | (end-of-line 1)) | |
c8d0cf5c CD |
920 | (condition-case nil |
921 | (progn | |
922 | (re-search-backward "|" (org-table-begin)) | |
923 | (re-search-backward "|" (org-table-begin))) | |
924 | (error (error "Cannot move to previous table field"))) | |
20908596 CD |
925 | (while (looking-at "|\\(-\\|[ \t]*$\\)") |
926 | (re-search-backward "|" (org-table-begin))) | |
927 | (if (looking-at "| ?") | |
928 | (goto-char (match-end 0)))) | |
929 | ||
c8d0cf5c CD |
930 | (defun org-table-beginning-of-field (&optional n) |
931 | "Move to the end of the current table field. | |
932 | If already at or after the end, move to the end of the next table field. | |
933 | With numeric argument N, move N-1 fields forward first." | |
934 | (interactive "p") | |
935 | (let ((pos (point))) | |
936 | (while (> n 1) | |
937 | (setq n (1- n)) | |
938 | (org-table-previous-field)) | |
939 | (if (not (re-search-backward "|" (point-at-bol 0) t)) | |
940 | (error "No more table fields before the current") | |
941 | (goto-char (match-end 0)) | |
942 | (and (looking-at " ") (forward-char 1))) | |
943 | (if (>= (point) pos) (org-table-beginning-of-field 2)))) | |
944 | ||
945 | (defun org-table-end-of-field (&optional n) | |
946 | "Move to the beginning of the current table field. | |
947 | If already at or before the beginning, move to the beginning of the | |
948 | previous field. | |
949 | With numeric argument N, move N-1 fields backward first." | |
950 | (interactive "p") | |
951 | (let ((pos (point))) | |
952 | (while (> n 1) | |
953 | (setq n (1- n)) | |
954 | (org-table-next-field)) | |
955 | (when (re-search-forward "|" (point-at-eol 1) t) | |
956 | (backward-char 1) | |
957 | (skip-chars-backward " ") | |
958 | (if (and (equal (char-before (point)) ?|) (looking-at " ")) | |
959 | (forward-char 1))) | |
960 | (if (<= (point) pos) (org-table-end-of-field 2)))) | |
961 | ||
20908596 CD |
962 | (defun org-table-next-row () |
963 | "Go to the next row (same column) in the current table. | |
964 | Before doing so, re-align the table if necessary." | |
965 | (interactive) | |
966 | (org-table-maybe-eval-formula) | |
967 | (org-table-maybe-recalculate-line) | |
968 | (if (or (looking-at "[ \t]*$") | |
969 | (save-excursion (skip-chars-backward " \t") (bolp))) | |
970 | (newline) | |
971 | (if (and org-table-automatic-realign | |
972 | org-table-may-need-update) | |
973 | (org-table-align)) | |
974 | (let ((col (org-table-current-column))) | |
975 | (beginning-of-line 2) | |
976 | (if (or (not (org-at-table-p)) | |
977 | (org-at-table-hline-p)) | |
978 | (progn | |
979 | (beginning-of-line 0) | |
980 | (org-table-insert-row 'below))) | |
981 | (org-table-goto-column col) | |
982 | (skip-chars-backward "^|\n\r") | |
983 | (if (looking-at " ") (forward-char 1))))) | |
984 | ||
985 | (defun org-table-copy-down (n) | |
986 | "Copy a field down in the current column. | |
987 | If the field at the cursor is empty, copy into it the content of the nearest | |
988 | non-empty field above. With argument N, use the Nth non-empty field. | |
989 | If the current field is not empty, it is copied down to the next row, and | |
990 | the cursor is moved with it. Therefore, repeating this command causes the | |
991 | column to be filled row-by-row. | |
992 | If the variable `org-table-copy-increment' is non-nil and the field is an | |
993 | integer or a timestamp, it will be incremented while copying. In the case of | |
994 | a timestamp, if the cursor is on the year, change the year. If it is on the | |
995 | month or the day, change that. Point will stay on the current date field | |
996 | in order to easily repeat the interval." | |
997 | (interactive "p") | |
998 | (let* ((colpos (org-table-current-column)) | |
999 | (col (current-column)) | |
1000 | (field (org-table-get-field)) | |
1001 | (non-empty (string-match "[^ \t]" field)) | |
1002 | (beg (org-table-begin)) | |
621f83e4 | 1003 | (orig-n n) |
20908596 CD |
1004 | txt) |
1005 | (org-table-check-inside-data-field) | |
1006 | (if non-empty | |
1007 | (progn | |
1008 | (setq txt (org-trim field)) | |
1009 | (org-table-next-row) | |
1010 | (org-table-blank-field)) | |
1011 | (save-excursion | |
1012 | (setq txt | |
1013 | (catch 'exit | |
1014 | (while (progn (beginning-of-line 1) | |
1015 | (re-search-backward org-table-dataline-regexp | |
1016 | beg t)) | |
1017 | (org-table-goto-column colpos t) | |
1018 | (if (and (looking-at | |
1019 | "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|") | |
621f83e4 | 1020 | (<= (setq n (1- n)) 0)) |
20908596 CD |
1021 | (throw 'exit (match-string 1)))))))) |
1022 | (if txt | |
1023 | (progn | |
1024 | (if (and org-table-copy-increment | |
621f83e4 CD |
1025 | (not (equal orig-n 0)) |
1026 | (string-match "^[0-9]+$" txt) | |
1027 | (< (string-to-number txt) 100000000)) | |
20908596 CD |
1028 | (setq txt (format "%d" (+ (string-to-number txt) 1)))) |
1029 | (insert txt) | |
1030 | (org-move-to-column col) | |
1031 | (if (and org-table-copy-increment (org-at-timestamp-p t)) | |
71d35b24 | 1032 | (org-timestamp-up-day) |
20908596 CD |
1033 | (org-table-maybe-recalculate-line)) |
1034 | (org-table-align) | |
1035 | (org-move-to-column col)) | |
1036 | (error "No non-empty field found")))) | |
1037 | ||
1038 | (defun org-table-check-inside-data-field () | |
1039 | "Is point inside a table data field? | |
1040 | I.e. not on a hline or before the first or after the last column? | |
1041 | This actually throws an error, so it aborts the current command." | |
1042 | (if (or (not (org-at-table-p)) | |
1043 | (= (org-table-current-column) 0) | |
1044 | (org-at-table-hline-p) | |
1045 | (looking-at "[ \t]*$")) | |
1046 | (error "Not in table data field"))) | |
1047 | ||
1048 | (defvar org-table-clip nil | |
1049 | "Clipboard for table regions.") | |
1050 | ||
ed21c5c8 CD |
1051 | (defun org-table-get (line column) |
1052 | "Get the field in table line LINE, column COLUMN. | |
1053 | If LINE is larger than the number of data lines in the table, the function | |
1054 | returns nil. However, if COLUMN is too large, we will simply return an | |
1055 | empty string. | |
1056 | If LINE is nil, use the current line. | |
1057 | If column is nil, use the current column." | |
1058 | (setq column (or column (org-table-current-column))) | |
1059 | (save-excursion | |
1060 | (and (or (not line) (org-table-goto-line line)) | |
1061 | (org-trim (org-table-get-field column))))) | |
1062 | ||
1063 | (defun org-table-put (line column value &optional align) | |
1064 | "Put VALUE into line LINE, column COLUMN. | |
86fbb8ca | 1065 | When ALIGN is set, also realign the table." |
ed21c5c8 CD |
1066 | (setq column (or column (org-table-current-column))) |
1067 | (prog1 (save-excursion | |
1068 | (and (or (not line) (org-table-goto-line line)) | |
1069 | (progn (org-table-goto-column column nil 'force) t) | |
1070 | (org-table-get-field column value))) | |
1071 | (and align (org-table-align)))) | |
1072 | ||
1073 | (defun org-table-current-line () | |
1074 | "Return the index of the current data line." | |
1075 | (let ((pos (point)) (end (org-table-end)) (cnt 0)) | |
1076 | (save-excursion | |
1077 | (goto-char (org-table-begin)) | |
1078 | (while (and (re-search-forward org-table-dataline-regexp end t) | |
1079 | (setq cnt (1+ cnt)) | |
1080 | (< (point-at-eol) pos)))) | |
1081 | cnt)) | |
1082 | ||
1083 | (defun org-table-goto-line (N) | |
1084 | "Go to the Nth data line in the current table. | |
1085 | Return t when the line exists, nil if it does not exist." | |
1086 | (goto-char (org-table-begin)) | |
1087 | (let ((end (org-table-end)) (cnt 0)) | |
1088 | (while (and (re-search-forward org-table-dataline-regexp end t) | |
1089 | (< (setq cnt (1+ cnt)) N))) | |
1090 | (= cnt N))) | |
1091 | ||
20908596 CD |
1092 | (defun org-table-blank-field () |
1093 | "Blank the current table field or active region." | |
1094 | (interactive) | |
1095 | (org-table-check-inside-data-field) | |
1096 | (if (and (interactive-p) (org-region-active-p)) | |
1097 | (let (org-table-clip) | |
1098 | (org-table-cut-region (region-beginning) (region-end))) | |
1099 | (skip-chars-backward "^|") | |
1100 | (backward-char 1) | |
1101 | (if (looking-at "|[^|\n]+") | |
1102 | (let* ((pos (match-beginning 0)) | |
1103 | (match (match-string 0)) | |
1104 | (len (org-string-width match))) | |
1105 | (replace-match (concat "|" (make-string (1- len) ?\ ))) | |
1106 | (goto-char (+ 2 pos)) | |
1107 | (substring match 1))))) | |
1108 | ||
1109 | (defun org-table-get-field (&optional n replace) | |
1110 | "Return the value of the field in column N of current row. | |
1111 | N defaults to current field. | |
1112 | If REPLACE is a string, replace field with this value. The return value | |
1113 | is always the old value." | |
1114 | (and n (org-table-goto-column n)) | |
1115 | (skip-chars-backward "^|\n") | |
1116 | (backward-char 1) | |
1117 | (if (looking-at "|[^|\r\n]*") | |
1118 | (let* ((pos (match-beginning 0)) | |
1119 | (val (buffer-substring (1+ pos) (match-end 0)))) | |
1120 | (if replace | |
1121 | (replace-match (concat "|" replace) t t)) | |
1122 | (goto-char (min (point-at-eol) (+ 2 pos))) | |
1123 | val) | |
1124 | (forward-char 1) "")) | |
1125 | ||
1126 | (defun org-table-field-info (arg) | |
1127 | "Show info about the current field, and highlight any reference at point." | |
1128 | (interactive "P") | |
1129 | (org-table-get-specials) | |
1130 | (save-excursion | |
1131 | (let* ((pos (point)) | |
1132 | (col (org-table-current-column)) | |
1133 | (cname (car (rassoc (int-to-string col) org-table-column-names))) | |
1134 | (name (car (rassoc (list (org-current-line) col) | |
1135 | org-table-named-field-locations))) | |
1136 | (eql (org-table-get-stored-formulas)) | |
1137 | (dline (org-table-current-dline)) | |
1138 | (ref (format "@%d$%d" dline col)) | |
1139 | (ref1 (org-table-convert-refs-to-an ref)) | |
1140 | (fequation (or (assoc name eql) (assoc ref eql))) | |
1141 | (cequation (assoc (int-to-string col) eql)) | |
1142 | (eqn (or fequation cequation))) | |
1143 | (goto-char pos) | |
1144 | (condition-case nil | |
1145 | (org-table-show-reference 'local) | |
1146 | (error nil)) | |
1147 | (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s" | |
1148 | dline col | |
1149 | (if cname (concat " or $" cname) "") | |
1150 | dline col ref1 | |
1151 | (if name (concat " or $" name) "") | |
1152 | ;; FIXME: formula info not correct if special table line | |
1153 | (if eqn | |
1154 | (concat ", formula: " | |
1155 | (org-table-formula-to-user | |
1156 | (concat | |
1157 | (if (string-match "^[$@]"(car eqn)) "" "$") | |
1158 | (car eqn) "=" (cdr eqn)))) | |
1159 | ""))))) | |
1160 | ||
1161 | (defun org-table-current-column () | |
1162 | "Find out which column we are in." | |
afe98dfa CD |
1163 | (interactive) |
1164 | (if (interactive-p) (org-table-check-inside-data-field)) | |
20908596 CD |
1165 | (save-excursion |
1166 | (let ((cnt 0) (pos (point))) | |
1167 | (beginning-of-line 1) | |
1168 | (while (search-forward "|" pos t) | |
1169 | (setq cnt (1+ cnt))) | |
afe98dfa | 1170 | (if (interactive-p) (message "In table column %d" cnt)) |
20908596 CD |
1171 | cnt))) |
1172 | ||
1173 | (defun org-table-current-dline () | |
1174 | "Find out what table data line we are in. | |
86fbb8ca | 1175 | Only data lines count for this." |
20908596 CD |
1176 | (interactive) |
1177 | (if (interactive-p) (org-table-check-inside-data-field)) | |
1178 | (save-excursion | |
1179 | (let ((cnt 0) (pos (point))) | |
1180 | (goto-char (org-table-begin)) | |
1181 | (while (<= (point) pos) | |
1182 | (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt))) | |
1183 | (beginning-of-line 2)) | |
1184 | (if (interactive-p) (message "This is table line %d" cnt)) | |
1185 | cnt))) | |
1186 | ||
1187 | (defun org-table-goto-column (n &optional on-delim force) | |
1188 | "Move the cursor to the Nth column in the current table line. | |
1189 | With optional argument ON-DELIM, stop with point before the left delimiter | |
1190 | of the field. | |
1191 | If there are less than N fields, just go to after the last delimiter. | |
1192 | However, when FORCE is non-nil, create new columns if necessary." | |
1193 | (interactive "p") | |
ed21c5c8 CD |
1194 | (beginning-of-line 1) |
1195 | (when (> n 0) | |
1196 | (while (and (> (setq n (1- n)) -1) | |
1197 | (or (search-forward "|" (point-at-eol) t) | |
1198 | (and force | |
1199 | (progn (end-of-line 1) | |
1200 | (skip-chars-backward "^|") | |
1201 | (insert " | ") | |
1202 | t))))) | |
1203 | (when (and force (not (looking-at ".*|"))) | |
1204 | (save-excursion (end-of-line 1) (insert " | "))) | |
1205 | (if on-delim | |
1206 | (backward-char 1) | |
1207 | (if (looking-at " ") (forward-char 1))))) | |
20908596 CD |
1208 | |
1209 | (defun org-table-insert-column () | |
1210 | "Insert a new column into the table." | |
1211 | (interactive) | |
1212 | (if (not (org-at-table-p)) | |
1213 | (error "Not at a table")) | |
1214 | (org-table-find-dataline) | |
1215 | (let* ((col (max 1 (org-table-current-column))) | |
1216 | (beg (org-table-begin)) | |
1217 | (end (org-table-end)) | |
1218 | ;; Current cursor position | |
1219 | (linepos (org-current-line)) | |
1220 | (colpos col)) | |
1221 | (goto-char beg) | |
1222 | (while (< (point) end) | |
1223 | (if (org-at-table-hline-p) | |
1224 | nil | |
1225 | (org-table-goto-column col t) | |
1226 | (insert "| ")) | |
1227 | (beginning-of-line 2)) | |
1228 | (move-marker end nil) | |
54a0dee5 | 1229 | (org-goto-line linepos) |
20908596 CD |
1230 | (org-table-goto-column colpos) |
1231 | (org-table-align) | |
fdf730ed CD |
1232 | (org-table-fix-formulas "$" nil (1- col) 1) |
1233 | (org-table-fix-formulas "$LR" nil (1- col) 1))) | |
20908596 CD |
1234 | |
1235 | (defun org-table-find-dataline () | |
86fbb8ca | 1236 | "Find a data line in the current table, which is needed for column commands." |
20908596 CD |
1237 | (if (and (org-at-table-p) |
1238 | (not (org-at-table-hline-p))) | |
1239 | t | |
1240 | (let ((col (current-column)) | |
1241 | (end (org-table-end))) | |
1242 | (org-move-to-column col) | |
1243 | (while (and (< (point) end) | |
1244 | (or (not (= (current-column) col)) | |
1245 | (org-at-table-hline-p))) | |
1246 | (beginning-of-line 2) | |
1247 | (org-move-to-column col)) | |
1248 | (if (and (org-at-table-p) | |
1249 | (not (org-at-table-hline-p))) | |
1250 | t | |
1251 | (error | |
1252 | "Please position cursor in a data line for column operations"))))) | |
1253 | ||
1254 | (defun org-table-delete-column () | |
1255 | "Delete a column from the table." | |
1256 | (interactive) | |
1257 | (if (not (org-at-table-p)) | |
1258 | (error "Not at a table")) | |
1259 | (org-table-find-dataline) | |
1260 | (org-table-check-inside-data-field) | |
1261 | (let* ((col (org-table-current-column)) | |
1262 | (beg (org-table-begin)) | |
1263 | (end (org-table-end)) | |
1264 | ;; Current cursor position | |
1265 | (linepos (org-current-line)) | |
1266 | (colpos col)) | |
1267 | (goto-char beg) | |
1268 | (while (< (point) end) | |
1269 | (if (org-at-table-hline-p) | |
1270 | nil | |
1271 | (org-table-goto-column col t) | |
1272 | (and (looking-at "|[^|\n]+|") | |
1273 | (replace-match "|"))) | |
1274 | (beginning-of-line 2)) | |
1275 | (move-marker end nil) | |
54a0dee5 | 1276 | (org-goto-line linepos) |
20908596 CD |
1277 | (org-table-goto-column colpos) |
1278 | (org-table-align) | |
1279 | (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID")) | |
fdf730ed CD |
1280 | col -1 col) |
1281 | (org-table-fix-formulas "$LR" (list (cons (number-to-string col) "INVALID")) | |
20908596 CD |
1282 | col -1 col))) |
1283 | ||
1284 | (defun org-table-move-column-right () | |
1285 | "Move column to the right." | |
1286 | (interactive) | |
1287 | (org-table-move-column nil)) | |
1288 | (defun org-table-move-column-left () | |
1289 | "Move column to the left." | |
1290 | (interactive) | |
1291 | (org-table-move-column 'left)) | |
1292 | ||
1293 | (defun org-table-move-column (&optional left) | |
1294 | "Move the current column to the right. With arg LEFT, move to the left." | |
1295 | (interactive "P") | |
1296 | (if (not (org-at-table-p)) | |
1297 | (error "Not at a table")) | |
1298 | (org-table-find-dataline) | |
1299 | (org-table-check-inside-data-field) | |
1300 | (let* ((col (org-table-current-column)) | |
1301 | (col1 (if left (1- col) col)) | |
1302 | (beg (org-table-begin)) | |
1303 | (end (org-table-end)) | |
1304 | ;; Current cursor position | |
1305 | (linepos (org-current-line)) | |
1306 | (colpos (if left (1- col) (1+ col)))) | |
1307 | (if (and left (= col 1)) | |
1308 | (error "Cannot move column further left")) | |
1309 | (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$")) | |
1310 | (error "Cannot move column further right")) | |
1311 | (goto-char beg) | |
1312 | (while (< (point) end) | |
1313 | (if (org-at-table-hline-p) | |
1314 | nil | |
1315 | (org-table-goto-column col1 t) | |
1316 | (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|") | |
1317 | (replace-match "|\\2|\\1|"))) | |
1318 | (beginning-of-line 2)) | |
1319 | (move-marker end nil) | |
54a0dee5 | 1320 | (org-goto-line linepos) |
20908596 CD |
1321 | (org-table-goto-column colpos) |
1322 | (org-table-align) | |
1323 | (org-table-fix-formulas | |
1324 | "$" (list (cons (number-to-string col) (number-to-string colpos)) | |
fdf730ed CD |
1325 | (cons (number-to-string colpos) (number-to-string col)))) |
1326 | (org-table-fix-formulas | |
1327 | "$LR" (list (cons (number-to-string col) (number-to-string colpos)) | |
1328 | (cons (number-to-string colpos) (number-to-string col)))))) | |
20908596 CD |
1329 | |
1330 | (defun org-table-move-row-down () | |
1331 | "Move table row down." | |
1332 | (interactive) | |
1333 | (org-table-move-row nil)) | |
1334 | (defun org-table-move-row-up () | |
1335 | "Move table row up." | |
1336 | (interactive) | |
1337 | (org-table-move-row 'up)) | |
1338 | ||
1339 | (defun org-table-move-row (&optional up) | |
1340 | "Move the current table line down. With arg UP, move it up." | |
1341 | (interactive "P") | |
1342 | (let* ((col (current-column)) | |
1343 | (pos (point)) | |
1344 | (hline1p (save-excursion (beginning-of-line 1) | |
1345 | (looking-at org-table-hline-regexp))) | |
1346 | (dline1 (org-table-current-dline)) | |
1347 | (dline2 (+ dline1 (if up -1 1))) | |
1348 | (tonew (if up 0 2)) | |
1349 | txt hline2p) | |
1350 | (beginning-of-line tonew) | |
1351 | (unless (org-at-table-p) | |
1352 | (goto-char pos) | |
1353 | (error "Cannot move row further")) | |
1354 | (setq hline2p (looking-at org-table-hline-regexp)) | |
1355 | (goto-char pos) | |
1356 | (beginning-of-line 1) | |
1357 | (setq pos (point)) | |
1358 | (setq txt (buffer-substring (point) (1+ (point-at-eol)))) | |
1359 | (delete-region (point) (1+ (point-at-eol))) | |
1360 | (beginning-of-line tonew) | |
1361 | (insert txt) | |
1362 | (beginning-of-line 0) | |
1363 | (org-move-to-column col) | |
1364 | (unless (or hline1p hline2p) | |
1365 | (org-table-fix-formulas | |
1366 | "@" (list (cons (number-to-string dline1) (number-to-string dline2)) | |
1367 | (cons (number-to-string dline2) (number-to-string dline1))))))) | |
1368 | ||
1369 | (defun org-table-insert-row (&optional arg) | |
1370 | "Insert a new row above the current line into the table. | |
1371 | With prefix ARG, insert below the current line." | |
1372 | (interactive "P") | |
1373 | (if (not (org-at-table-p)) | |
1374 | (error "Not at a table")) | |
1375 | (let* ((line (buffer-substring (point-at-bol) (point-at-eol))) | |
1376 | (new (org-table-clean-line line))) | |
1377 | ;; Fix the first field if necessary | |
1378 | (if (string-match "^[ \t]*| *[#$] *|" line) | |
1379 | (setq new (replace-match (match-string 0 line) t t new))) | |
1380 | (beginning-of-line (if arg 2 1)) | |
1381 | (let (org-table-may-need-update) (insert-before-markers new "\n")) | |
1382 | (beginning-of-line 0) | |
1383 | (re-search-forward "| ?" (point-at-eol) t) | |
1384 | (and (or org-table-may-need-update org-table-overlay-coordinates) | |
1385 | (org-table-align)) | |
1386 | (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1))) | |
1387 | ||
1388 | (defun org-table-insert-hline (&optional above) | |
1389 | "Insert a horizontal-line below the current line into the table. | |
1390 | With prefix ABOVE, insert above the current line." | |
1391 | (interactive "P") | |
1392 | (if (not (org-at-table-p)) | |
1393 | (error "Not at a table")) | |
0bd48b37 CD |
1394 | (when (eobp) (insert "\n") (backward-char 1)) |
1395 | (if (not (string-match "|[ \t]*$" (org-current-line-string))) | |
1396 | (org-table-align)) | |
20908596 CD |
1397 | (let ((line (org-table-clean-line |
1398 | (buffer-substring (point-at-bol) (point-at-eol)))) | |
1399 | (col (current-column))) | |
1400 | (while (string-match "|\\( +\\)|" line) | |
1401 | (setq line (replace-match | |
1402 | (concat "+" (make-string (- (match-end 1) (match-beginning 1)) | |
1403 | ?-) "|") t t line))) | |
1404 | (and (string-match "\\+" line) (setq line (replace-match "|" t t line))) | |
1405 | (beginning-of-line (if above 1 2)) | |
1406 | (insert line "\n") | |
1407 | (beginning-of-line (if above 1 -1)) | |
1408 | (org-move-to-column col) | |
1409 | (and org-table-overlay-coordinates (org-table-align)))) | |
1410 | ||
1411 | (defun org-table-hline-and-move (&optional same-column) | |
1412 | "Insert a hline and move to the row below that line." | |
1413 | (interactive "P") | |
1414 | (let ((col (org-table-current-column))) | |
1415 | (org-table-maybe-eval-formula) | |
1416 | (org-table-maybe-recalculate-line) | |
1417 | (org-table-insert-hline) | |
1418 | (end-of-line 2) | |
1419 | (if (looking-at "\n[ \t]*|-") | |
1420 | (progn (insert "\n|") (org-table-align)) | |
1421 | (org-table-next-field)) | |
1422 | (if same-column (org-table-goto-column col)))) | |
1423 | ||
1424 | (defun org-table-clean-line (s) | |
1425 | "Convert a table line S into a string with only \"|\" and space. | |
1426 | In particular, this does handle wide and invisible characters." | |
1427 | (if (string-match "^[ \t]*|-" s) | |
1428 | ;; It's a hline, just map the characters | |
1429 | (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s "")) | |
1430 | (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s) | |
1431 | (setq s (replace-match | |
1432 | (concat "|" (make-string (org-string-width (match-string 1 s)) | |
1433 | ?\ ) "|") | |
1434 | t t s))) | |
1435 | s)) | |
1436 | ||
1437 | (defun org-table-kill-row () | |
1438 | "Delete the current row or horizontal line from the table." | |
1439 | (interactive) | |
1440 | (if (not (org-at-table-p)) | |
1441 | (error "Not at a table")) | |
1442 | (let ((col (current-column)) | |
1443 | (dline (org-table-current-dline))) | |
1444 | (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max))) | |
1445 | (if (not (org-at-table-p)) (beginning-of-line 0)) | |
1446 | (org-move-to-column col) | |
1447 | (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID")) | |
1448 | dline -1 dline))) | |
1449 | ||
1450 | (defun org-table-sort-lines (with-case &optional sorting-type) | |
1451 | "Sort table lines according to the column at point. | |
1452 | ||
1453 | The position of point indicates the column to be used for | |
1454 | sorting, and the range of lines is the range between the nearest | |
1455 | horizontal separator lines, or the entire table of no such lines | |
1456 | exist. If point is before the first column, you will be prompted | |
1457 | for the sorting column. If there is an active region, the mark | |
1458 | specifies the first line and the sorting column, while point | |
1459 | should be in the last line to be included into the sorting. | |
1460 | ||
1461 | The command then prompts for the sorting type which can be | |
1462 | alphabetically, numerically, or by time (as given in a time stamp | |
1463 | in the field). Sorting in reverse order is also possible. | |
1464 | ||
1465 | With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive. | |
1466 | ||
1467 | If SORTING-TYPE is specified when this function is called from a Lisp | |
1468 | program, no prompting will take place. SORTING-TYPE must be a character, | |
1469 | any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting | |
1470 | should be done in reverse order." | |
1471 | (interactive "P") | |
1472 | (let* ((thisline (org-current-line)) | |
1473 | (thiscol (org-table-current-column)) | |
1474 | beg end bcol ecol tend tbeg column lns pos) | |
1475 | (when (equal thiscol 0) | |
1476 | (if (interactive-p) | |
1477 | (setq thiscol | |
1478 | (string-to-number | |
1479 | (read-string "Use column N for sorting: "))) | |
1480 | (setq thiscol 1)) | |
1481 | (org-table-goto-column thiscol)) | |
1482 | (org-table-check-inside-data-field) | |
1483 | (if (org-region-active-p) | |
1484 | (progn | |
1485 | (setq beg (region-beginning) end (region-end)) | |
1486 | (goto-char beg) | |
1487 | (setq column (org-table-current-column) | |
1488 | beg (point-at-bol)) | |
1489 | (goto-char end) | |
1490 | (setq end (point-at-bol 2))) | |
1491 | (setq column (org-table-current-column) | |
1492 | pos (point) | |
1493 | tbeg (org-table-begin) | |
1494 | tend (org-table-end)) | |
1495 | (if (re-search-backward org-table-hline-regexp tbeg t) | |
1496 | (setq beg (point-at-bol 2)) | |
1497 | (goto-char tbeg) | |
1498 | (setq beg (point-at-bol 1))) | |
1499 | (goto-char pos) | |
1500 | (if (re-search-forward org-table-hline-regexp tend t) | |
1501 | (setq end (point-at-bol 1)) | |
1502 | (goto-char tend) | |
1503 | (setq end (point-at-bol)))) | |
1504 | (setq beg (move-marker (make-marker) beg) | |
1505 | end (move-marker (make-marker) end)) | |
1506 | (untabify beg end) | |
1507 | (goto-char beg) | |
1508 | (org-table-goto-column column) | |
1509 | (skip-chars-backward "^|") | |
1510 | (setq bcol (current-column)) | |
1511 | (org-table-goto-column (1+ column)) | |
1512 | (skip-chars-backward "^|") | |
1513 | (setq ecol (1- (current-column))) | |
1514 | (org-table-goto-column column) | |
1515 | (setq lns (mapcar (lambda(x) (cons | |
1516 | (org-sort-remove-invisible | |
1517 | (nth (1- column) | |
1518 | (org-split-string x "[ \t]*|[ \t]*"))) | |
1519 | x)) | |
1520 | (org-split-string (buffer-substring beg end) "\n"))) | |
1521 | (setq lns (org-do-sort lns "Table" with-case sorting-type)) | |
1522 | (delete-region beg end) | |
1523 | (move-marker beg nil) | |
1524 | (move-marker end nil) | |
1525 | (insert (mapconcat 'cdr lns "\n") "\n") | |
54a0dee5 | 1526 | (org-goto-line thisline) |
20908596 CD |
1527 | (org-table-goto-column thiscol) |
1528 | (message "%d lines sorted, based on column %d" (length lns) column))) | |
1529 | ||
1530 | ||
1531 | (defun org-table-cut-region (beg end) | |
c8d0cf5c CD |
1532 | "Copy region in table to the clipboard and blank all relevant fields. |
1533 | If there is no active region, use just the field at point." | |
1534 | (interactive (list | |
1535 | (if (org-region-active-p) (region-beginning) (point)) | |
1536 | (if (org-region-active-p) (region-end) (point)))) | |
20908596 CD |
1537 | (org-table-copy-region beg end 'cut)) |
1538 | ||
1539 | (defun org-table-copy-region (beg end &optional cut) | |
1540 | "Copy rectangular region in table to clipboard. | |
1541 | A special clipboard is used which can only be accessed | |
1542 | with `org-table-paste-rectangle'." | |
c8d0cf5c CD |
1543 | (interactive (list |
1544 | (if (org-region-active-p) (region-beginning) (point)) | |
1545 | (if (org-region-active-p) (region-end) (point)) | |
1546 | current-prefix-arg)) | |
20908596 CD |
1547 | (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2 |
1548 | region cols | |
1549 | (rpl (if cut " " nil))) | |
1550 | (goto-char beg) | |
1551 | (org-table-check-inside-data-field) | |
1552 | (setq l01 (org-current-line) | |
1553 | c01 (org-table-current-column)) | |
1554 | (goto-char end) | |
1555 | (org-table-check-inside-data-field) | |
1556 | (setq l02 (org-current-line) | |
1557 | c02 (org-table-current-column)) | |
1558 | (setq l1 (min l01 l02) l2 (max l01 l02) | |
1559 | c1 (min c01 c02) c2 (max c01 c02)) | |
1560 | (catch 'exit | |
1561 | (while t | |
1562 | (catch 'nextline | |
1563 | (if (> l1 l2) (throw 'exit t)) | |
54a0dee5 | 1564 | (org-goto-line l1) |
20908596 CD |
1565 | (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1)))) |
1566 | (setq cols nil ic1 c1 ic2 c2) | |
1567 | (while (< ic1 (1+ ic2)) | |
1568 | (push (org-table-get-field ic1 rpl) cols) | |
1569 | (setq ic1 (1+ ic1))) | |
1570 | (push (nreverse cols) region) | |
1571 | (setq l1 (1+ l1))))) | |
1572 | (setq org-table-clip (nreverse region)) | |
1573 | (if cut (org-table-align)) | |
1574 | org-table-clip)) | |
1575 | ||
1576 | (defun org-table-paste-rectangle () | |
1577 | "Paste a rectangular region into a table. | |
1578 | The upper right corner ends up in the current field. All involved fields | |
1579 | will be overwritten. If the rectangle does not fit into the present table, | |
1580 | the table is enlarged as needed. The process ignores horizontal separator | |
1581 | lines." | |
1582 | (interactive) | |
1583 | (unless (and org-table-clip (listp org-table-clip)) | |
1584 | (error "First cut/copy a region to paste!")) | |
1585 | (org-table-check-inside-data-field) | |
1586 | (let* ((clip org-table-clip) | |
1587 | (line (org-current-line)) | |
1588 | (col (org-table-current-column)) | |
1589 | (org-enable-table-editor t) | |
1590 | (org-table-automatic-realign nil) | |
1591 | c cols field) | |
1592 | (while (setq cols (pop clip)) | |
1593 | (while (org-at-table-hline-p) (beginning-of-line 2)) | |
1594 | (if (not (org-at-table-p)) | |
1595 | (progn (end-of-line 0) (org-table-next-field))) | |
1596 | (setq c col) | |
1597 | (while (setq field (pop cols)) | |
1598 | (org-table-goto-column c nil 'force) | |
1599 | (org-table-get-field nil field) | |
1600 | (setq c (1+ c))) | |
1601 | (beginning-of-line 2)) | |
54a0dee5 | 1602 | (org-goto-line line) |
20908596 CD |
1603 | (org-table-goto-column col) |
1604 | (org-table-align))) | |
1605 | ||
1606 | (defun org-table-convert () | |
1607 | "Convert from `org-mode' table to table.el and back. | |
1608 | Obviously, this only works within limits. When an Org-mode table is | |
1609 | converted to table.el, all horizontal separator lines get lost, because | |
1610 | table.el uses these as cell boundaries and has no notion of horizontal lines. | |
1611 | A table.el table can be converted to an Org-mode table only if it does not | |
1612 | do row or column spanning. Multiline cells will become multiple cells. | |
1613 | Beware, Org-mode does not test if the table can be successfully converted - it | |
1614 | blindly applies a recipe that works for simple tables." | |
1615 | (interactive) | |
1616 | (require 'table) | |
1617 | (if (org-at-table.el-p) | |
1618 | ;; convert to Org-mode table | |
1619 | (let ((beg (move-marker (make-marker) (org-table-begin t))) | |
1620 | (end (move-marker (make-marker) (org-table-end t)))) | |
1621 | (table-unrecognize-region beg end) | |
1622 | (goto-char beg) | |
1623 | (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t) | |
1624 | (replace-match "")) | |
1625 | (goto-char beg)) | |
1626 | (if (org-at-table-p) | |
1627 | ;; convert to table.el table | |
1628 | (let ((beg (move-marker (make-marker) (org-table-begin))) | |
1629 | (end (move-marker (make-marker) (org-table-end)))) | |
1630 | ;; first, get rid of all horizontal lines | |
1631 | (goto-char beg) | |
1632 | (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t) | |
1633 | (replace-match "")) | |
1634 | ;; insert a hline before first | |
1635 | (goto-char beg) | |
1636 | (org-table-insert-hline 'above) | |
1637 | (beginning-of-line -1) | |
1638 | ;; insert a hline after each line | |
1639 | (while (progn (beginning-of-line 3) (< (point) end)) | |
1640 | (org-table-insert-hline)) | |
1641 | (goto-char beg) | |
1642 | (setq end (move-marker end (org-table-end))) | |
1643 | ;; replace "+" at beginning and ending of hlines | |
1644 | (while (re-search-forward "^\\([ \t]*\\)|-" end t) | |
1645 | (replace-match "\\1+-")) | |
1646 | (goto-char beg) | |
1647 | (while (re-search-forward "-|[ \t]*$" end t) | |
1648 | (replace-match "-+")) | |
1649 | (goto-char beg))))) | |
1650 | ||
1651 | (defun org-table-wrap-region (arg) | |
1652 | "Wrap several fields in a column like a paragraph. | |
1653 | This is useful if you'd like to spread the contents of a field over several | |
1654 | lines, in order to keep the table compact. | |
1655 | ||
1656 | If there is an active region, and both point and mark are in the same column, | |
1657 | the text in the column is wrapped to minimum width for the given number of | |
1658 | lines. Generally, this makes the table more compact. A prefix ARG may be | |
1659 | used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]' | |
1660 | formats the selected text to two lines. If the region was longer than two | |
1661 | lines, the remaining lines remain empty. A negative prefix argument reduces | |
1662 | the current number of lines by that amount. The wrapped text is pasted back | |
1663 | into the table. If you formatted it to more lines than it was before, fields | |
1664 | further down in the table get overwritten - so you might need to make space in | |
1665 | the table first. | |
1666 | ||
1667 | If there is no region, the current field is split at the cursor position and | |
1668 | the text fragment to the right of the cursor is prepended to the field one | |
1669 | line down. | |
1670 | ||
1671 | If there is no region, but you specify a prefix ARG, the current field gets | |
1672 | blank, and the content is appended to the field above." | |
1673 | (interactive "P") | |
1674 | (org-table-check-inside-data-field) | |
1675 | (if (org-region-active-p) | |
1676 | ;; There is a region: fill as a paragraph | |
1677 | (let* ((beg (region-beginning)) | |
1678 | (cline (save-excursion (goto-char beg) (org-current-line))) | |
1679 | (ccol (save-excursion (goto-char beg) (org-table-current-column))) | |
1680 | nlines) | |
1681 | (org-table-cut-region (region-beginning) (region-end)) | |
1682 | (if (> (length (car org-table-clip)) 1) | |
1683 | (error "Region must be limited to single column")) | |
1684 | (setq nlines (if arg | |
1685 | (if (< arg 1) | |
1686 | (+ (length org-table-clip) arg) | |
1687 | arg) | |
1688 | (length org-table-clip))) | |
1689 | (setq org-table-clip | |
1690 | (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ") | |
1691 | nil nlines))) | |
54a0dee5 | 1692 | (org-goto-line cline) |
20908596 CD |
1693 | (org-table-goto-column ccol) |
1694 | (org-table-paste-rectangle)) | |
1695 | ;; No region, split the current field at point | |
1696 | (unless (org-get-alist-option org-M-RET-may-split-line 'table) | |
1697 | (skip-chars-forward "^\r\n|")) | |
1698 | (if arg | |
1699 | ;; combine with field above | |
1700 | (let ((s (org-table-blank-field)) | |
1701 | (col (org-table-current-column))) | |
1702 | (beginning-of-line 0) | |
1703 | (while (org-at-table-hline-p) (beginning-of-line 0)) | |
1704 | (org-table-goto-column col) | |
1705 | (skip-chars-forward "^|") | |
1706 | (skip-chars-backward " ") | |
1707 | (insert " " (org-trim s)) | |
1708 | (org-table-align)) | |
1709 | ;; split field | |
1710 | (if (looking-at "\\([^|]+\\)+|") | |
1711 | (let ((s (match-string 1))) | |
1712 | (replace-match " |") | |
1713 | (goto-char (match-beginning 0)) | |
1714 | (org-table-next-row) | |
1715 | (insert (org-trim s) " ") | |
1716 | (org-table-align)) | |
1717 | (org-table-next-row))))) | |
1718 | ||
1719 | (defvar org-field-marker nil) | |
1720 | ||
1721 | (defun org-table-edit-field (arg) | |
1722 | "Edit table field in a different window. | |
1723 | This is mainly useful for fields that contain hidden parts. | |
1724 | When called with a \\[universal-argument] prefix, just make the full field visible so that | |
1725 | it can be edited in place." | |
1726 | (interactive "P") | |
1727 | (if arg | |
1728 | (let ((b (save-excursion (skip-chars-backward "^|") (point))) | |
1729 | (e (save-excursion (skip-chars-forward "^|\r\n") (point)))) | |
1730 | (remove-text-properties b e '(org-cwidth t invisible t | |
1731 | display t intangible t)) | |
1732 | (if (and (boundp 'font-lock-mode) font-lock-mode) | |
1733 | (font-lock-fontify-block))) | |
1734 | (let ((pos (move-marker (make-marker) (point))) | |
1735 | (field (org-table-get-field)) | |
1736 | (cw (current-window-configuration)) | |
1737 | p) | |
1738 | (org-switch-to-buffer-other-window "*Org tmp*") | |
1739 | (erase-buffer) | |
1740 | (insert "#\n# Edit field and finish with C-c C-c\n#\n") | |
1741 | (let ((org-inhibit-startup t)) (org-mode)) | |
1742 | (goto-char (setq p (point-max))) | |
1743 | (insert (org-trim field)) | |
1744 | (remove-text-properties p (point-max) | |
1745 | '(invisible t org-cwidth t display t | |
1746 | intangible t)) | |
1747 | (goto-char p) | |
1748 | (org-set-local 'org-finish-function 'org-table-finish-edit-field) | |
1749 | (org-set-local 'org-window-configuration cw) | |
1750 | (org-set-local 'org-field-marker pos) | |
1751 | (message "Edit and finish with C-c C-c")))) | |
1752 | ||
1753 | (defun org-table-finish-edit-field () | |
1754 | "Finish editing a table data field. | |
1755 | Remove all newline characters, insert the result into the table, realign | |
1756 | the table and kill the editing buffer." | |
1757 | (let ((pos org-field-marker) | |
1758 | (cw org-window-configuration) | |
1759 | (cb (current-buffer)) | |
1760 | text) | |
1761 | (goto-char (point-min)) | |
1762 | (while (re-search-forward "^#.*\n?" nil t) (replace-match "")) | |
1763 | (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t) | |
1764 | (replace-match " ")) | |
1765 | (setq text (org-trim (buffer-string))) | |
1766 | (set-window-configuration cw) | |
1767 | (kill-buffer cb) | |
1768 | (select-window (get-buffer-window (marker-buffer pos))) | |
1769 | (goto-char pos) | |
1770 | (move-marker pos nil) | |
1771 | (org-table-check-inside-data-field) | |
1772 | (org-table-get-field nil text) | |
1773 | (org-table-align) | |
1774 | (message "New field value inserted"))) | |
1775 | ||
20908596 CD |
1776 | (defvar org-timecnt) ; dynamically scoped parameter |
1777 | ||
1778 | (defun org-table-sum (&optional beg end nlast) | |
1779 | "Sum numbers in region of current table column. | |
1780 | The result will be displayed in the echo area, and will be available | |
1781 | as kill to be inserted with \\[yank]. | |
1782 | ||
1783 | If there is an active region, it is interpreted as a rectangle and all | |
1784 | numbers in that rectangle will be summed. If there is no active | |
1785 | region and point is located in a table column, sum all numbers in that | |
1786 | column. | |
1787 | ||
1788 | If at least one number looks like a time HH:MM or HH:MM:SS, all other | |
1789 | numbers are assumed to be times as well (in decimal hours) and the | |
1790 | numbers are added as such. | |
1791 | ||
1792 | If NLAST is a number, only the NLAST fields will actually be summed." | |
1793 | (interactive) | |
1794 | (save-excursion | |
1795 | (let (col (org-timecnt 0) diff h m s org-table-clip) | |
1796 | (cond | |
1797 | ((and beg end)) ; beg and end given explicitly | |
1798 | ((org-region-active-p) | |
1799 | (setq beg (region-beginning) end (region-end))) | |
1800 | (t | |
1801 | (setq col (org-table-current-column)) | |
1802 | (goto-char (org-table-begin)) | |
1803 | (unless (re-search-forward "^[ \t]*|[^-]" nil t) | |
1804 | (error "No table data")) | |
1805 | (org-table-goto-column col) | |
1806 | (setq beg (point)) | |
1807 | (goto-char (org-table-end)) | |
1808 | (unless (re-search-backward "^[ \t]*|[^-]" nil t) | |
1809 | (error "No table data")) | |
1810 | (org-table-goto-column col) | |
1811 | (setq end (point)))) | |
1812 | (let* ((items (apply 'append (org-table-copy-region beg end))) | |
1813 | (items1 (cond ((not nlast) items) | |
1814 | ((>= nlast (length items)) items) | |
1815 | (t (setq items (reverse items)) | |
1816 | (setcdr (nthcdr (1- nlast) items) nil) | |
1817 | (nreverse items)))) | |
1818 | (numbers (delq nil (mapcar 'org-table-get-number-for-summing | |
1819 | items1))) | |
1820 | (res (apply '+ numbers)) | |
1821 | (sres (if (= org-timecnt 0) | |
621f83e4 | 1822 | (number-to-string res) |
20908596 CD |
1823 | (setq diff (* 3600 res) |
1824 | h (floor (/ diff 3600)) diff (mod diff 3600) | |
1825 | m (floor (/ diff 60)) diff (mod diff 60) | |
1826 | s diff) | |
1827 | (format "%d:%02d:%02d" h m s)))) | |
1828 | (kill-new sres) | |
1829 | (if (interactive-p) | |
1830 | (message "%s" | |
1831 | (substitute-command-keys | |
1832 | (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)" | |
1833 | (length numbers) sres)))) | |
1834 | sres)))) | |
1835 | ||
1836 | (defun org-table-get-number-for-summing (s) | |
1837 | (let (n) | |
1838 | (if (string-match "^ *|? *" s) | |
1839 | (setq s (replace-match "" nil nil s))) | |
1840 | (if (string-match " *|? *$" s) | |
1841 | (setq s (replace-match "" nil nil s))) | |
1842 | (setq n (string-to-number s)) | |
1843 | (cond | |
1844 | ((and (string-match "0" s) | |
1845 | (string-match "\\`[-+ \t0.edED]+\\'" s)) 0) | |
33306645 | 1846 | ((string-match "\\`[ \t]+\\'" s) nil) |
20908596 CD |
1847 | ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s) |
1848 | (let ((h (string-to-number (or (match-string 1 s) "0"))) | |
1849 | (m (string-to-number (or (match-string 2 s) "0"))) | |
1850 | (s (string-to-number (or (match-string 4 s) "0")))) | |
1851 | (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt))) | |
1852 | (* 1.0 (+ h (/ m 60.0) (/ s 3600.0))))) | |
33306645 | 1853 | ((equal n 0) nil) |
20908596 CD |
1854 | (t n)))) |
1855 | ||
1856 | (defun org-table-current-field-formula (&optional key noerror) | |
1857 | "Return the formula active for the current field. | |
1858 | Assumes that specials are in place. | |
1859 | If KEY is given, return the key to this formula. | |
86fbb8ca | 1860 | Otherwise return the formula preceded with \"=\" or \":=\"." |
20908596 CD |
1861 | (let* ((name (car (rassoc (list (org-current-line) |
1862 | (org-table-current-column)) | |
1863 | org-table-named-field-locations))) | |
1864 | (col (org-table-current-column)) | |
1865 | (scol (int-to-string col)) | |
1866 | (ref (format "@%d$%d" (org-table-current-dline) col)) | |
1867 | (stored-list (org-table-get-stored-formulas noerror)) | |
1868 | (ass (or (assoc name stored-list) | |
1869 | (assoc ref stored-list) | |
1870 | (assoc scol stored-list)))) | |
1871 | (if key | |
1872 | (car ass) | |
1873 | (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=") | |
1874 | (cdr ass)))))) | |
1875 | ||
1876 | (defun org-table-get-formula (&optional equation named) | |
1877 | "Read a formula from the minibuffer, offer stored formula as default. | |
1878 | When NAMED is non-nil, look for a named equation." | |
1879 | (let* ((stored-list (org-table-get-stored-formulas)) | |
1880 | (name (car (rassoc (list (org-current-line) | |
1881 | (org-table-current-column)) | |
1882 | org-table-named-field-locations))) | |
1883 | (ref (format "@%d$%d" (org-table-current-dline) | |
1884 | (org-table-current-column))) | |
1885 | (refass (assoc ref stored-list)) | |
cff4f506 | 1886 | (nameass (assoc name stored-list)) |
20908596 | 1887 | (scol (if named |
fdf730ed CD |
1888 | (if (and name (not (string-match "^LR[0-9]+$" name))) |
1889 | name | |
1890 | ref) | |
20908596 | 1891 | (int-to-string (org-table-current-column)))) |
cff4f506 | 1892 | (dummy (and (or nameass refass) (not named) |
0bd48b37 | 1893 | (not (y-or-n-p "Replace existing field formula with column formula? " )) |
20908596 CD |
1894 | (error "Abort"))) |
1895 | (name (or name ref)) | |
1896 | (org-table-may-need-update nil) | |
1897 | (stored (cdr (assoc scol stored-list))) | |
1898 | (eq (cond | |
1899 | ((and stored equation (string-match "^ *=? *$" equation)) | |
1900 | stored) | |
1901 | ((stringp equation) | |
1902 | equation) | |
1903 | (t (org-table-formula-from-user | |
1904 | (read-string | |
1905 | (org-table-formula-to-user | |
1906 | (format "%s formula %s%s=" | |
1907 | (if named "Field" "Column") | |
1908 | (if (member (string-to-char scol) '(?$ ?@)) "" "$") | |
1909 | scol)) | |
1910 | (if stored (org-table-formula-to-user stored) "") | |
1911 | 'org-table-formula-history | |
1912 | ))))) | |
1913 | mustsave) | |
1914 | (when (not (string-match "\\S-" eq)) | |
1915 | ;; remove formula | |
1916 | (setq stored-list (delq (assoc scol stored-list) stored-list)) | |
1917 | (org-table-store-formulas stored-list) | |
1918 | (error "Formula removed")) | |
1919 | (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq))) | |
1920 | (if (string-match " *$" eq) (setq eq (replace-match "" t t eq))) | |
1921 | (if (and name (not named)) | |
1922 | ;; We set the column equation, delete the named one. | |
1923 | (setq stored-list (delq (assoc name stored-list) stored-list) | |
1924 | mustsave t)) | |
1925 | (if stored | |
1926 | (setcdr (assoc scol stored-list) eq) | |
1927 | (setq stored-list (cons (cons scol eq) stored-list))) | |
1928 | (if (or mustsave (not (equal stored eq))) | |
1929 | (org-table-store-formulas stored-list)) | |
1930 | eq)) | |
1931 | ||
1932 | (defun org-table-store-formulas (alist) | |
1933 | "Store the list of formulas below the current table." | |
1934 | (setq alist (sort alist 'org-table-formula-less-p)) | |
1935 | (save-excursion | |
1936 | (goto-char (org-table-end)) | |
c8d0cf5c | 1937 | (if (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM:\\(.*\n?\\)") |
20908596 CD |
1938 | (progn |
1939 | ;; don't overwrite TBLFM, we might use text properties to store stuff | |
1940 | (goto-char (match-beginning 2)) | |
1941 | (delete-region (match-beginning 2) (match-end 0))) | |
c8d0cf5c | 1942 | (org-indent-line-function) |
20908596 CD |
1943 | (insert "#+TBLFM:")) |
1944 | (insert " " | |
1945 | (mapconcat (lambda (x) | |
1946 | (concat | |
1947 | (if (equal (string-to-char (car x)) ?@) "" "$") | |
1948 | (car x) "=" (cdr x))) | |
1949 | alist "::") | |
1950 | "\n"))) | |
1951 | ||
1952 | (defsubst org-table-formula-make-cmp-string (a) | |
1953 | (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a) | |
1954 | (concat | |
1955 | (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "") | |
1956 | (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "") | |
1957 | (if (match-end 5) (concat "@@" (match-string 5 a)))))) | |
1958 | ||
1959 | (defun org-table-formula-less-p (a b) | |
1960 | "Compare two formulas for sorting." | |
1961 | (let ((as (org-table-formula-make-cmp-string (car a))) | |
1962 | (bs (org-table-formula-make-cmp-string (car b)))) | |
1963 | (and as bs (string< as bs)))) | |
1964 | ||
1965 | (defun org-table-get-stored-formulas (&optional noerror) | |
1966 | "Return an alist with the stored formulas directly after current table." | |
1967 | (interactive) | |
1968 | (let (scol eq eq-alist strings string seen) | |
1969 | (save-excursion | |
1970 | (goto-char (org-table-end)) | |
c8d0cf5c | 1971 | (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)") |
20908596 CD |
1972 | (setq strings (org-split-string (match-string 2) " *:: *")) |
1973 | (while (setq string (pop strings)) | |
1974 | (when (string-match "\\`\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string) | |
1975 | (setq scol (if (match-end 2) | |
1976 | (match-string 2 string) | |
1977 | (match-string 1 string)) | |
1978 | eq (match-string 3 string) | |
1979 | eq-alist (cons (cons scol eq) eq-alist)) | |
1980 | (if (member scol seen) | |
33306645 CD |
1981 | (if noerror |
1982 | (progn | |
1983 | (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol) | |
1984 | (ding) | |
1985 | (sit-for 2)) | |
1986 | (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)) | |
20908596 CD |
1987 | (push scol seen)))))) |
1988 | (nreverse eq-alist))) | |
1989 | ||
1990 | (defun org-table-fix-formulas (key replace &optional limit delta remove) | |
1991 | "Modify the equations after the table structure has been edited. | |
1992 | KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace. | |
1993 | For all numbers larger than LIMIT, shift them by DELTA." | |
1994 | (save-excursion | |
1995 | (goto-char (org-table-end)) | |
c8d0cf5c | 1996 | (when (looking-at "[ \t]*#\\+TBLFM:") |
20908596 CD |
1997 | (let ((re (concat key "\\([0-9]+\\)")) |
1998 | (re2 | |
1999 | (when remove | |
fdf730ed CD |
2000 | (if (or (equal key "$") (equal key "$LR")) |
2001 | (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)" | |
2002 | (regexp-quote key) remove) | |
20908596 CD |
2003 | (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove)))) |
2004 | s n a) | |
2005 | (when remove | |
2006 | (while (re-search-forward re2 (point-at-eol) t) | |
c8d0cf5c CD |
2007 | (unless (save-match-data (org-in-regexp "remote([^)]+?)")) |
2008 | (replace-match "")))) | |
20908596 | 2009 | (while (re-search-forward re (point-at-eol) t) |
c8d0cf5c CD |
2010 | (unless (save-match-data (org-in-regexp "remote([^)]+?)")) |
2011 | (setq s (match-string 1) n (string-to-number s)) | |
2012 | (cond | |
2013 | ((setq a (assoc s replace)) | |
2014 | (replace-match (concat key (cdr a)) t t)) | |
2015 | ((and limit (> n limit)) | |
2016 | (replace-match (concat key (int-to-string (+ n delta))) | |
2017 | t t))))))))) | |
20908596 CD |
2018 | |
2019 | (defun org-table-get-specials () | |
2020 | "Get the column names and local parameters for this table." | |
2021 | (save-excursion | |
2022 | (let ((beg (org-table-begin)) (end (org-table-end)) | |
2023 | names name fields fields1 field cnt | |
fdf730ed | 2024 | c v l line col types dlines hlines last-dline) |
20908596 CD |
2025 | (setq org-table-column-names nil |
2026 | org-table-local-parameters nil | |
2027 | org-table-named-field-locations nil | |
2028 | org-table-current-begin-line nil | |
2029 | org-table-current-begin-pos nil | |
2030 | org-table-current-line-types nil) | |
2031 | (goto-char beg) | |
2032 | (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t) | |
2033 | (setq names (org-split-string (match-string 1) " *| *") | |
2034 | cnt 1) | |
2035 | (while (setq name (pop names)) | |
2036 | (setq cnt (1+ cnt)) | |
2037 | (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name) | |
2038 | (push (cons name (int-to-string cnt)) org-table-column-names)))) | |
2039 | (setq org-table-column-names (nreverse org-table-column-names)) | |
2040 | (setq org-table-column-name-regexp | |
2041 | (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>")) | |
2042 | (goto-char beg) | |
2043 | (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t) | |
2044 | (setq fields (org-split-string (match-string 1) " *| *")) | |
2045 | (while (setq field (pop fields)) | |
2046 | (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field) | |
2047 | (push (cons (match-string 1 field) (match-string 2 field)) | |
2048 | org-table-local-parameters)))) | |
2049 | (goto-char beg) | |
2050 | (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t) | |
2051 | (setq c (match-string 1) | |
2052 | fields (org-split-string (match-string 2) " *| *")) | |
2053 | (save-excursion | |
2054 | (beginning-of-line (if (equal c "_") 2 0)) | |
2055 | (setq line (org-current-line) col 1) | |
2056 | (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)") | |
2057 | (setq fields1 (org-split-string (match-string 1) " *| *")))) | |
2058 | (while (and fields1 (setq field (pop fields))) | |
2059 | (setq v (pop fields1) col (1+ col)) | |
2060 | (when (and (stringp field) (stringp v) | |
2061 | (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field)) | |
2062 | (push (cons field v) org-table-local-parameters) | |
2063 | (push (list field line col) org-table-named-field-locations)))) | |
2c3ad40d | 2064 | ;; Analyse the line types |
20908596 CD |
2065 | (goto-char beg) |
2066 | (setq org-table-current-begin-line (org-current-line) | |
2067 | org-table-current-begin-pos (point) | |
2068 | l org-table-current-begin-line) | |
2069 | (while (looking-at "[ \t]*|\\(-\\)?") | |
2070 | (push (if (match-end 1) 'hline 'dline) types) | |
2071 | (if (match-end 1) (push l hlines) (push l dlines)) | |
2072 | (beginning-of-line 2) | |
2073 | (setq l (1+ l))) | |
0bd48b37 | 2074 | (push 'hline types) ;; add an imaginary extra hline to the end |
20908596 | 2075 | (setq org-table-current-line-types (apply 'vector (nreverse types)) |
fdf730ed | 2076 | last-dline (car dlines) |
17a0aa82 | 2077 | org-table-dlines (apply 'vector (cons nil (nreverse dlines))) |
fdf730ed | 2078 | org-table-hlines (apply 'vector (cons nil (nreverse hlines)))) |
54a0dee5 | 2079 | (org-goto-line last-dline) |
fdf730ed CD |
2080 | (let* ((l last-dline) |
2081 | (fields (org-split-string | |
2082 | (buffer-substring (point-at-bol) (point-at-eol)) | |
0bd48b37 | 2083 | "[ \t]*|[ \t]*")) |
fdf730ed CD |
2084 | (nfields (length fields)) |
2085 | al al2) | |
2086 | (loop for i from 1 to nfields do | |
2087 | (push (list (format "LR%d" i) l i) al) | |
2088 | (push (cons (format "LR%d" i) (nth (1- i) fields)) al2)) | |
2089 | (setq org-table-named-field-locations | |
2090 | (append org-table-named-field-locations al)) | |
2091 | (setq org-table-local-parameters | |
2092 | (append org-table-local-parameters al2)))))) | |
2093 | ||
20908596 CD |
2094 | |
2095 | (defun org-table-maybe-eval-formula () | |
2096 | "Check if the current field starts with \"=\" or \":=\". | |
2097 | If yes, store the formula and apply it." | |
2098 | ;; We already know we are in a table. Get field will only return a formula | |
2099 | ;; when appropriate. It might return a separator line, but no problem. | |
2100 | (when org-table-formula-evaluate-inline | |
2101 | (let* ((field (org-trim (or (org-table-get-field) ""))) | |
2102 | named eq) | |
2103 | (when (string-match "^:?=\\(.*\\)" field) | |
2104 | (setq named (equal (string-to-char field) ?:) | |
2105 | eq (match-string 1 field)) | |
2106 | (if (or (fboundp 'calc-eval) | |
2107 | (equal (substring eq 0 (min 2 (length eq))) "'(")) | |
2108 | (org-table-eval-formula (if named '(4) nil) | |
2109 | (org-table-formula-from-user eq)) | |
2110 | (error "Calc does not seem to be installed, and is needed to evaluate the formula")))))) | |
2111 | ||
2112 | (defvar org-recalc-commands nil | |
2113 | "List of commands triggering the recalculation of a line. | |
2114 | Will be filled automatically during use.") | |
2115 | ||
2116 | (defvar org-recalc-marks | |
2117 | '((" " . "Unmarked: no special line, no automatic recalculation") | |
2118 | ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line") | |
2119 | ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'") | |
2120 | ("!" . "Column name definition line. Reference in formula as $name.") | |
2121 | ("$" . "Parameter definition line name=value. Reference in formula as $name.") | |
2122 | ("_" . "Names for values in row below this one.") | |
2123 | ("^" . "Names for values in row above this one."))) | |
2124 | ||
2125 | (defun org-table-rotate-recalc-marks (&optional newchar) | |
2126 | "Rotate the recalculation mark in the first column. | |
2127 | If in any row, the first field is not consistent with a mark, | |
2128 | insert a new column for the markers. | |
2129 | When there is an active region, change all the lines in the region, | |
2130 | after prompting for the marking character. | |
2131 | After each change, a message will be displayed indicating the meaning | |
2132 | of the new mark." | |
2133 | (interactive) | |
2134 | (unless (org-at-table-p) (error "Not at a table")) | |
2135 | (let* ((marks (append (mapcar 'car org-recalc-marks) '(" "))) | |
2136 | (beg (org-table-begin)) | |
2137 | (end (org-table-end)) | |
2138 | (l (org-current-line)) | |
2139 | (l1 (if (org-region-active-p) (org-current-line (region-beginning)))) | |
2140 | (l2 (if (org-region-active-p) (org-current-line (region-end)))) | |
2141 | (have-col | |
2142 | (save-excursion | |
2143 | (goto-char beg) | |
2144 | (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t)))) | |
2145 | (col (org-table-current-column)) | |
2146 | (forcenew (car (assoc newchar org-recalc-marks))) | |
2147 | epos new) | |
2148 | (when l1 | |
2149 | (message "Change region to what mark? Type # * ! $ or SPC: ") | |
2150 | (setq newchar (char-to-string (read-char-exclusive)) | |
2151 | forcenew (car (assoc newchar org-recalc-marks)))) | |
2152 | (if (and newchar (not forcenew)) | |
2153 | (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'" | |
2154 | newchar)) | |
54a0dee5 | 2155 | (if l1 (org-goto-line l1)) |
20908596 CD |
2156 | (save-excursion |
2157 | (beginning-of-line 1) | |
2158 | (unless (looking-at org-table-dataline-regexp) | |
2159 | (error "Not at a table data line"))) | |
2160 | (unless have-col | |
2161 | (org-table-goto-column 1) | |
2162 | (org-table-insert-column) | |
2163 | (org-table-goto-column (1+ col))) | |
2164 | (setq epos (point-at-eol)) | |
2165 | (save-excursion | |
2166 | (beginning-of-line 1) | |
2167 | (org-table-get-field | |
2168 | 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|") | |
2169 | (concat " " | |
2170 | (setq new (or forcenew | |
2171 | (cadr (member (match-string 1) marks)))) | |
2172 | " ") | |
2173 | " # "))) | |
2174 | (if (and l1 l2) | |
2175 | (progn | |
54a0dee5 | 2176 | (org-goto-line l1) |
20908596 CD |
2177 | (while (progn (beginning-of-line 2) (not (= (org-current-line) l2))) |
2178 | (and (looking-at org-table-dataline-regexp) | |
2179 | (org-table-get-field 1 (concat " " new " ")))) | |
54a0dee5 | 2180 | (org-goto-line l1))) |
20908596 | 2181 | (if (not (= epos (point-at-eol))) (org-table-align)) |
54a0dee5 | 2182 | (org-goto-line l) |
20908596 CD |
2183 | (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks)))))) |
2184 | ||
2185 | (defun org-table-maybe-recalculate-line () | |
2186 | "Recompute the current line if marked for it, and if we haven't just done it." | |
2187 | (interactive) | |
2188 | (and org-table-allow-automatic-line-recalculation | |
2189 | (not (and (memq last-command org-recalc-commands) | |
2190 | (equal org-last-recalc-line (org-current-line)))) | |
2191 | (save-excursion (beginning-of-line 1) | |
2192 | (looking-at org-table-auto-recalculate-regexp)) | |
2193 | (org-table-recalculate) t)) | |
2194 | ||
2195 | (defvar modes) | |
2196 | (defsubst org-set-calc-mode (var &optional value) | |
2197 | (if (stringp var) | |
2198 | (setq var (assoc var '(("D" calc-angle-mode deg) | |
2199 | ("R" calc-angle-mode rad) | |
2200 | ("F" calc-prefer-frac t) | |
2201 | ("S" calc-symbolic-mode t))) | |
2202 | value (nth 2 var) var (nth 1 var))) | |
2203 | (if (memq var modes) | |
2204 | (setcar (cdr (memq var modes)) value) | |
2205 | (cons var (cons value modes))) | |
2206 | modes) | |
2207 | ||
2208 | (defun org-table-eval-formula (&optional arg equation | |
2209 | suppress-align suppress-const | |
2210 | suppress-store suppress-analysis) | |
2211 | "Replace the table field value at the cursor by the result of a calculation. | |
2212 | ||
2213 | This function makes use of Dave Gillespie's Calc package, in my view the | |
2214 | most exciting program ever written for GNU Emacs. So you need to have Calc | |
2215 | installed in order to use this function. | |
2216 | ||
2217 | In a table, this command replaces the value in the current field with the | |
2218 | result of a formula. It also installs the formula as the \"current\" column | |
2219 | formula, by storing it in a special line below the table. When called | |
8bfe682a | 2220 | with a `C-u' prefix, the current field must be a named field, and the |
20908596 CD |
2221 | formula is installed as valid in only this specific field. |
2222 | ||
2223 | When called with two `C-u' prefixes, insert the active equation | |
2224 | for the field back into the current field, so that it can be | |
2225 | edited there. This is useful in order to use \\[org-table-show-reference] | |
2226 | to check the referenced fields. | |
2227 | ||
2228 | When called, the command first prompts for a formula, which is read in | |
2229 | the minibuffer. Previously entered formulas are available through the | |
2230 | history list, and the last used formula is offered as a default. | |
2231 | These stored formulas are adapted correctly when moving, inserting, or | |
2232 | deleting columns with the corresponding commands. | |
2233 | ||
2234 | The formula can be any algebraic expression understood by the Calc package. | |
2235 | For details, see the Org-mode manual. | |
2236 | ||
2237 | This function can also be called from Lisp programs and offers | |
2238 | additional arguments: EQUATION can be the formula to apply. If this | |
2239 | argument is given, the user will not be prompted. SUPPRESS-ALIGN is | |
2240 | used to speed-up recursive calls by by-passing unnecessary aligns. | |
2241 | SUPPRESS-CONST suppresses the interpretation of constants in the | |
2242 | formula, assuming that this has been done already outside the function. | |
2243 | SUPPRESS-STORE means the formula should not be stored, either because | |
2244 | it is already stored, or because it is a modified equation that should | |
2245 | not overwrite the stored one." | |
2246 | (interactive "P") | |
2247 | (org-table-check-inside-data-field) | |
2248 | (or suppress-analysis (org-table-get-specials)) | |
2249 | (if (equal arg '(16)) | |
2250 | (let ((eq (org-table-current-field-formula))) | |
2251 | (or eq (error "No equation active for current field")) | |
2252 | (org-table-get-field nil eq) | |
2253 | (org-table-align) | |
2254 | (setq org-table-may-need-update t)) | |
2255 | (let* (fields | |
2256 | (ndown (if (integerp arg) arg 1)) | |
2257 | (org-table-automatic-realign nil) | |
2258 | (case-fold-search nil) | |
2259 | (down (> ndown 1)) | |
2260 | (formula (if (and equation suppress-store) | |
2261 | equation | |
2262 | (org-table-get-formula equation (equal arg '(4))))) | |
2263 | (n0 (org-table-current-column)) | |
2264 | (modes (copy-sequence org-calc-default-modes)) | |
2265 | (numbers nil) ; was a variable, now fixed default | |
2266 | (keep-empty nil) | |
2267 | n form form0 bw fmt x ev orig c lispp literal) | |
2268 | ;; Parse the format string. Since we have a lot of modes, this is | |
2269 | ;; a lot of work. However, I think calc still uses most of the time. | |
2270 | (if (string-match ";" formula) | |
2271 | (let ((tmp (org-split-string formula ";"))) | |
2272 | (setq formula (car tmp) | |
2273 | fmt (concat (cdr (assoc "%" org-table-local-parameters)) | |
2274 | (nth 1 tmp))) | |
2275 | (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt) | |
2276 | (setq c (string-to-char (match-string 1 fmt)) | |
2277 | n (string-to-number (match-string 2 fmt))) | |
2278 | (if (= c ?p) | |
2279 | (setq modes (org-set-calc-mode 'calc-internal-prec n)) | |
2280 | (setq modes (org-set-calc-mode | |
2281 | 'calc-float-format | |
2282 | (list (cdr (assoc c '((?n . float) (?f . fix) | |
2283 | (?s . sci) (?e . eng)))) | |
2284 | n)))) | |
2285 | (setq fmt (replace-match "" t t fmt))) | |
2286 | (if (string-match "[NT]" fmt) | |
2287 | (setq numbers (equal (match-string 0 fmt) "N") | |
2288 | fmt (replace-match "" t t fmt))) | |
2289 | (if (string-match "L" fmt) | |
2290 | (setq literal t | |
2291 | fmt (replace-match "" t t fmt))) | |
2292 | (if (string-match "E" fmt) | |
2293 | (setq keep-empty t | |
2294 | fmt (replace-match "" t t fmt))) | |
2295 | (while (string-match "[DRFS]" fmt) | |
2296 | (setq modes (org-set-calc-mode (match-string 0 fmt))) | |
2297 | (setq fmt (replace-match "" t t fmt))) | |
2298 | (unless (string-match "\\S-" fmt) | |
2299 | (setq fmt nil)))) | |
2300 | (if (and (not suppress-const) org-table-formula-use-constants) | |
2301 | (setq formula (org-table-formula-substitute-names formula))) | |
2302 | (setq orig (or (get-text-property 1 :orig-formula formula) "?")) | |
2303 | (while (> ndown 0) | |
2304 | (setq fields (org-split-string | |
2305 | (org-no-properties | |
2306 | (buffer-substring (point-at-bol) (point-at-eol))) | |
2307 | " *| *")) | |
2308 | (if (eq numbers t) | |
2309 | (setq fields (mapcar | |
2310 | (lambda (x) (number-to-string (string-to-number x))) | |
2311 | fields))) | |
2312 | (setq ndown (1- ndown)) | |
2313 | (setq form (copy-sequence formula) | |
2314 | lispp (and (> (length form) 2)(equal (substring form 0 2) "'("))) | |
2315 | (if (and lispp literal) (setq lispp 'literal)) | |
ed21c5c8 CD |
2316 | |
2317 | ;; Insert row and column number of formula result field | |
2318 | (while (string-match "[@$]#" form) | |
2319 | (setq form | |
2320 | (replace-match | |
2321 | (format "%d" | |
2322 | (save-match-data | |
2323 | (if (equal (substring form (match-beginning 0) | |
2324 | (1+ (match-beginning 0))) | |
2325 | "@") | |
2326 | (org-table-current-dline) | |
2327 | (org-table-current-column)))) | |
2328 | t t form))) | |
2329 | ||
20908596 | 2330 | ;; Check for old vertical references |
ff4be292 | 2331 | (setq form (org-table-rewrite-old-row-references form)) |
0bd48b37 CD |
2332 | ;; Insert remote references |
2333 | (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form) | |
2334 | (setq form | |
2335 | (replace-match | |
2336 | (save-match-data | |
2337 | (org-table-make-reference | |
2338 | (org-table-get-remote-range | |
2339 | (match-string 1 form) (match-string 2 form)) | |
2340 | keep-empty numbers lispp)) | |
2341 | t t form))) | |
20908596 | 2342 | ;; Insert complex ranges |
71d35b24 CD |
2343 | (while (and (string-match org-table-range-regexp form) |
2344 | (> (length (match-string 0 form)) 1)) | |
20908596 CD |
2345 | (setq form |
2346 | (replace-match | |
2347 | (save-match-data | |
2348 | (org-table-make-reference | |
2349 | (org-table-get-range (match-string 0 form) nil n0) | |
2350 | keep-empty numbers lispp)) | |
2351 | t t form))) | |
2352 | ;; Insert simple ranges | |
2353 | (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form) | |
2354 | (setq form | |
2355 | (replace-match | |
2356 | (save-match-data | |
2357 | (org-table-make-reference | |
2358 | (org-sublist | |
2359 | fields (string-to-number (match-string 1 form)) | |
2360 | (string-to-number (match-string 2 form))) | |
2361 | keep-empty numbers lispp)) | |
2362 | t t form))) | |
2363 | (setq form0 form) | |
2364 | ;; Insert the references to fields in same row | |
2365 | (while (string-match "\\$\\([0-9]+\\)" form) | |
2366 | (setq n (string-to-number (match-string 1 form)) | |
2367 | x (nth (1- (if (= n 0) n0 n)) fields)) | |
2368 | (unless x (error "Invalid field specifier \"%s\"" | |
2369 | (match-string 0 form))) | |
2370 | (setq form (replace-match | |
2371 | (save-match-data | |
2372 | (org-table-make-reference x nil numbers lispp)) | |
2373 | t t form))) | |
2374 | ||
2375 | (if lispp | |
2376 | (setq ev (condition-case nil | |
2377 | (eval (eval (read form))) | |
2378 | (error "#ERROR")) | |
2379 | ev (if (numberp ev) (number-to-string ev) ev)) | |
2380 | (or (fboundp 'calc-eval) | |
2381 | (error "Calc does not seem to be installed, and is needed to evaluate the formula")) | |
2382 | (setq ev (calc-eval (cons form modes) | |
2383 | (if numbers 'num)))) | |
2384 | ||
2385 | (when org-table-formula-debug | |
2386 | (with-output-to-temp-buffer "*Substitution History*" | |
2387 | (princ (format "Substitution history of formula | |
2388 | Orig: %s | |
2389 | $xyz-> %s | |
2390 | @r$c-> %s | |
2391 | $1-> %s\n" orig formula form0 form)) | |
2392 | (if (listp ev) | |
2393 | (princ (format " %s^\nError: %s" | |
2394 | (make-string (car ev) ?\-) (nth 1 ev))) | |
2395 | (princ (format "Result: %s\nFormat: %s\nFinal: %s" | |
2396 | ev (or fmt "NONE") | |
2397 | (if fmt (format fmt (string-to-number ev)) ev))))) | |
2398 | (setq bw (get-buffer-window "*Substitution History*")) | |
93b62de8 | 2399 | (org-fit-window-to-buffer bw) |
20908596 CD |
2400 | (unless (and (interactive-p) (not ndown)) |
2401 | (unless (let (inhibit-redisplay) | |
86fbb8ca | 2402 | (y-or-n-p "Debugging Formula. Continue to next? ")) |
20908596 CD |
2403 | (org-table-align) |
2404 | (error "Abort")) | |
2405 | (delete-window bw) | |
2406 | (message ""))) | |
2407 | (if (listp ev) (setq fmt nil ev "#ERROR")) | |
2408 | (org-table-justify-field-maybe | |
2409 | (if fmt (format fmt (string-to-number ev)) ev)) | |
2410 | (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]")) | |
2411 | (call-interactively 'org-return) | |
2412 | (setq ndown 0))) | |
2413 | (and down (org-table-maybe-recalculate-line)) | |
2414 | (or suppress-align (and org-table-may-need-update | |
2415 | (org-table-align)))))) | |
2416 | ||
2417 | (defun org-table-put-field-property (prop value) | |
2418 | (save-excursion | |
2419 | (put-text-property (progn (skip-chars-backward "^|") (point)) | |
2420 | (progn (skip-chars-forward "^|") (point)) | |
2421 | prop value))) | |
2422 | ||
2423 | (defun org-table-get-range (desc &optional tbeg col highlight) | |
33306645 | 2424 | "Get a calc vector from a column, according to descriptor DESC. |
20908596 CD |
2425 | Optional arguments TBEG and COL can give the beginning of the table and |
2426 | the current column, to avoid unnecessary parsing. | |
ed21c5c8 | 2427 | HIGHLIGHT means just highlight the range." |
20908596 CD |
2428 | (if (not (equal (string-to-char desc) ?@)) |
2429 | (setq desc (concat "@" desc))) | |
2430 | (save-excursion | |
2431 | (or tbeg (setq tbeg (org-table-begin))) | |
2432 | (or col (setq col (org-table-current-column))) | |
2433 | (let ((thisline (org-current-line)) | |
2434 | beg end c1 c2 r1 r2 rangep tmp) | |
2435 | (unless (string-match org-table-range-regexp desc) | |
2436 | (error "Invalid table range specifier `%s'" desc)) | |
2437 | (setq rangep (match-end 3) | |
2438 | r1 (and (match-end 1) (match-string 1 desc)) | |
2439 | r2 (and (match-end 4) (match-string 4 desc)) | |
2440 | c1 (and (match-end 2) (substring (match-string 2 desc) 1)) | |
2441 | c2 (and (match-end 5) (substring (match-string 5 desc) 1))) | |
2442 | ||
2443 | (and c1 (setq c1 (+ (string-to-number c1) | |
2444 | (if (memq (string-to-char c1) '(?- ?+)) col 0)))) | |
2445 | (and c2 (setq c2 (+ (string-to-number c2) | |
2446 | (if (memq (string-to-char c2) '(?- ?+)) col 0)))) | |
2447 | (if (equal r1 "") (setq r1 nil)) | |
2448 | (if (equal r2 "") (setq r2 nil)) | |
2449 | (if r1 (setq r1 (org-table-get-descriptor-line r1))) | |
2450 | (if r2 (setq r2 (org-table-get-descriptor-line r2))) | |
2451 | ; (setq r2 (or r2 r1) c2 (or c2 c1)) | |
2452 | (if (not r1) (setq r1 thisline)) | |
2453 | (if (not r2) (setq r2 thisline)) | |
2454 | (if (not c1) (setq c1 col)) | |
2455 | (if (not c2) (setq c2 col)) | |
2456 | (if (or (not rangep) (and (= r1 r2) (= c1 c2))) | |
2457 | ;; just one field | |
2458 | (progn | |
54a0dee5 | 2459 | (org-goto-line r1) |
20908596 CD |
2460 | (while (not (looking-at org-table-dataline-regexp)) |
2461 | (beginning-of-line 2)) | |
2462 | (prog1 (org-trim (org-table-get-field c1)) | |
2463 | (if highlight (org-table-highlight-rectangle (point) (point))))) | |
2464 | ;; A range, return a vector | |
2465 | ;; First sort the numbers to get a regular ractangle | |
2466 | (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp)) | |
2467 | (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp)) | |
54a0dee5 | 2468 | (org-goto-line r1) |
20908596 CD |
2469 | (while (not (looking-at org-table-dataline-regexp)) |
2470 | (beginning-of-line 2)) | |
2471 | (org-table-goto-column c1) | |
2472 | (setq beg (point)) | |
54a0dee5 | 2473 | (org-goto-line r2) |
20908596 CD |
2474 | (while (not (looking-at org-table-dataline-regexp)) |
2475 | (beginning-of-line 0)) | |
2476 | (org-table-goto-column c2) | |
2477 | (setq end (point)) | |
2478 | (if highlight | |
2479 | (org-table-highlight-rectangle | |
2480 | beg (progn (skip-chars-forward "^|\n") (point)))) | |
2481 | ;; return string representation of calc vector | |
2482 | (mapcar 'org-trim | |
2483 | (apply 'append (org-table-copy-region beg end))))))) | |
2484 | ||
2485 | (defun org-table-get-descriptor-line (desc &optional cline bline table) | |
2486 | "Analyze descriptor DESC and retrieve the corresponding line number. | |
2487 | The cursor is currently in line CLINE, the table begins in line BLINE, | |
2488 | and TABLE is a vector with line types." | |
2489 | (if (string-match "^[0-9]+$" desc) | |
2490 | (aref org-table-dlines (string-to-number desc)) | |
2491 | (setq cline (or cline (org-current-line)) | |
2492 | bline (or bline org-table-current-begin-line) | |
2493 | table (or table org-table-current-line-types)) | |
2494 | (if (or | |
2495 | (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc)) | |
2496 | ;; 1 2 3 4 5 6 | |
2497 | (and (not (match-end 3)) (not (match-end 6))) | |
2498 | (and (match-end 3) (match-end 6) (not (match-end 5)))) | |
86fbb8ca | 2499 | (error "Invalid row descriptor `%s'" desc)) |
20908596 CD |
2500 | (let* ((hdir (and (match-end 2) (match-string 2 desc))) |
2501 | (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil)) | |
2502 | (odir (and (match-end 5) (match-string 5 desc))) | |
2503 | (on (if (match-end 6) (string-to-number (match-string 6 desc)))) | |
2504 | (i (- cline bline)) | |
2505 | (rel (and (match-end 6) | |
2506 | (or (and (match-end 1) (not (match-end 3))) | |
2507 | (match-end 5))))) | |
2508 | (if (and hn (not hdir)) | |
2509 | (progn | |
2510 | (setq i 0 hdir "+") | |
2511 | (if (eq (aref table 0) 'hline) (setq hn (1- hn))))) | |
2512 | (if (and (not hn) on (not odir)) | |
86fbb8ca | 2513 | (error "Should never happen");;(aref org-table-dlines on) |
20908596 | 2514 | (if (and hn (> hn 0)) |
ff4be292 CD |
2515 | (setq i (org-table-find-row-type table i 'hline (equal hdir "-") |
2516 | nil hn cline desc))) | |
20908596 | 2517 | (if on |
ff4be292 CD |
2518 | (setq i (org-table-find-row-type table i 'dline (equal odir "-") |
2519 | rel on cline desc))) | |
20908596 CD |
2520 | (+ bline i))))) |
2521 | ||
ff4be292 CD |
2522 | (defun org-table-find-row-type (table i type backwards relative n cline desc) |
2523 | "FIXME: Needs more documentation." | |
20908596 CD |
2524 | (let ((l (length table))) |
2525 | (while (> n 0) | |
2526 | (while (and (setq i (+ i (if backwards -1 1))) | |
2527 | (>= i 0) (< i l) | |
2528 | (not (eq (aref table i) type)) | |
2529 | (if (and relative (eq (aref table i) 'hline)) | |
c8d0cf5c CD |
2530 | (cond |
2531 | ((eq org-table-relative-ref-may-cross-hline t) t) | |
2532 | ((eq org-table-relative-ref-may-cross-hline 'error) | |
2533 | (error "Row descriptor %s used in line %d crosses hline" desc cline)) | |
2534 | (t (setq i (- i (if backwards -1 1)) | |
2535 | n 1) | |
2536 | nil)) | |
20908596 CD |
2537 | t))) |
2538 | (setq n (1- n))) | |
2539 | (if (or (< i 0) (>= i l)) | |
ff4be292 CD |
2540 | (error "Row descriptor %s used in line %d leads outside table" |
2541 | desc cline) | |
20908596 CD |
2542 | i))) |
2543 | ||
ff4be292 | 2544 | (defun org-table-rewrite-old-row-references (s) |
20908596 CD |
2545 | (if (string-match "&[-+0-9I]" s) |
2546 | (error "Formula contains old &row reference, please rewrite using @-syntax") | |
2547 | s)) | |
2548 | ||
2549 | (defun org-table-make-reference (elements keep-empty numbers lispp) | |
2550 | "Convert list ELEMENTS to something appropriate to insert into formula. | |
2551 | KEEP-EMPTY indicated to keep empty fields, default is to skip them. | |
2552 | NUMBERS indicates that everything should be converted to numbers. | |
2553 | LISPP means to return something appropriate for a Lisp list." | |
2554 | (if (stringp elements) ; just a single val | |
2555 | (if lispp | |
2556 | (if (eq lispp 'literal) | |
2557 | elements | |
2558 | (prin1-to-string (if numbers (string-to-number elements) elements))) | |
2559 | (if (equal elements "") (setq elements "0")) | |
2560 | (if numbers (setq elements (number-to-string (string-to-number elements)))) | |
2561 | (concat "(" elements ")")) | |
2562 | (unless keep-empty | |
2563 | (setq elements | |
2564 | (delq nil | |
2565 | (mapcar (lambda (x) (if (string-match "\\S-" x) x nil)) | |
2566 | elements)))) | |
2567 | (setq elements (or elements '("0"))) | |
2568 | (if lispp | |
2569 | (mapconcat | |
2570 | (lambda (x) | |
2571 | (if (eq lispp 'literal) | |
2572 | x | |
2573 | (prin1-to-string (if numbers (string-to-number x) x)))) | |
2574 | elements " ") | |
2575 | (concat "[" (mapconcat | |
2576 | (lambda (x) | |
2577 | (if numbers (number-to-string (string-to-number x)) x)) | |
2578 | elements | |
2579 | ",") "]")))) | |
2580 | ||
2581 | (defun org-table-recalculate (&optional all noalign) | |
2582 | "Recalculate the current table line by applying all stored formulas. | |
db55f368 | 2583 | With prefix arg ALL, do this for all lines in the table. |
86fbb8ca CD |
2584 | With the prefix argument ALL is `(16)' \ |
2585 | \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if | |
db55f368 CD |
2586 | it is the symbol `iterate', recompute the table until it no longer changes. |
2587 | If NOALIGN is not nil, do not re-align the table after the computations | |
2588 | are done. This is typically used internally to save time, if it is | |
2589 | known that the table will be realigned a little later anyway." | |
20908596 CD |
2590 | (interactive "P") |
2591 | (or (memq this-command org-recalc-commands) | |
2592 | (setq org-recalc-commands (cons this-command org-recalc-commands))) | |
2593 | (unless (org-at-table-p) (error "Not at a table")) | |
db55f368 | 2594 | (if (or (eq all 'iterate) (equal all '(16))) |
20908596 CD |
2595 | (org-table-iterate) |
2596 | (org-table-get-specials) | |
2597 | (let* ((eqlist (sort (org-table-get-stored-formulas) | |
2598 | (lambda (a b) (string< (car a) (car b))))) | |
2599 | (inhibit-redisplay (not debug-on-error)) | |
2600 | (line-re org-table-dataline-regexp) | |
2601 | (thisline (org-current-line)) | |
2602 | (thiscol (org-table-current-column)) | |
2603 | beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name) | |
2604 | ;; Insert constants in all formulas | |
2605 | (setq eqlist | |
2606 | (mapcar (lambda (x) | |
2607 | (setcdr x (org-table-formula-substitute-names (cdr x))) | |
2608 | x) | |
2609 | eqlist)) | |
2610 | ;; Split the equation list | |
2611 | (while (setq eq (pop eqlist)) | |
2612 | (if (<= (string-to-char (car eq)) ?9) | |
2613 | (push eq eqlnum) | |
2614 | (push eq eqlname))) | |
2615 | (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname)) | |
2616 | (if all | |
2617 | (progn | |
2618 | (setq end (move-marker (make-marker) (1+ (org-table-end)))) | |
2619 | (goto-char (setq beg (org-table-begin))) | |
2620 | (if (re-search-forward org-table-calculate-mark-regexp end t) | |
2621 | ;; This is a table with marked lines, compute selected lines | |
2622 | (setq line-re org-table-recalculate-regexp) | |
2623 | ;; Move forward to the first non-header line | |
2624 | (if (and (re-search-forward org-table-dataline-regexp end t) | |
2625 | (re-search-forward org-table-hline-regexp end t) | |
2626 | (re-search-forward org-table-dataline-regexp end t)) | |
2627 | (setq beg (match-beginning 0)) | |
2628 | nil))) ;; just leave beg where it is | |
2629 | (setq beg (point-at-bol) | |
2630 | end (move-marker (make-marker) (1+ (point-at-eol))))) | |
2631 | (goto-char beg) | |
2632 | (and all (message "Re-applying formulas to full table...")) | |
2633 | ||
b349f79f | 2634 | ;; First find the named fields, and mark them untouchable |
20908596 CD |
2635 | (remove-text-properties beg end '(org-untouchable t)) |
2636 | (while (setq eq (pop eqlname)) | |
2637 | (setq name (car eq) | |
2638 | a (assoc name org-table-named-field-locations)) | |
2639 | (and (not a) | |
2640 | (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name) | |
2641 | (setq a (list name | |
b349f79f CD |
2642 | (condition-case nil |
2643 | (aref org-table-dlines | |
2644 | (string-to-number (match-string 1 name))) | |
2645 | (error (error "Invalid row number in %s" | |
2646 | name))) | |
20908596 CD |
2647 | (string-to-number (match-string 2 name))))) |
2648 | (when (and a (or all (equal (nth 1 a) thisline))) | |
2649 | (message "Re-applying formula to field: %s" name) | |
54a0dee5 | 2650 | (org-goto-line (nth 1 a)) |
20908596 CD |
2651 | (org-table-goto-column (nth 2 a)) |
2652 | (push (append a (list (cdr eq))) eqlname1) | |
2653 | (org-table-put-field-property :org-untouchable t))) | |
2654 | ||
8bfe682a | 2655 | ;; Now evaluate the column formulas, but skip fields covered by |
20908596 CD |
2656 | ;; field formulas |
2657 | (goto-char beg) | |
2658 | (while (re-search-forward line-re end t) | |
2659 | (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1)) | |
2660 | ;; Unprotected line, recalculate | |
2661 | (and all (message "Re-applying formulas to full table...(line %d)" | |
2662 | (setq cnt (1+ cnt)))) | |
2663 | (setq org-last-recalc-line (org-current-line)) | |
2664 | (setq eql eqlnum) | |
2665 | (while (setq entry (pop eql)) | |
54a0dee5 | 2666 | (org-goto-line org-last-recalc-line) |
20908596 CD |
2667 | (org-table-goto-column (string-to-number (car entry)) nil 'force) |
2668 | (unless (get-text-property (point) :org-untouchable) | |
2669 | (org-table-eval-formula nil (cdr entry) | |
2670 | 'noalign 'nocst 'nostore 'noanalysis))))) | |
2671 | ||
2672 | ;; Now evaluate the field formulas | |
2673 | (while (setq eq (pop eqlname1)) | |
2674 | (message "Re-applying formula to field: %s" (car eq)) | |
54a0dee5 | 2675 | (org-goto-line (nth 1 eq)) |
20908596 CD |
2676 | (org-table-goto-column (nth 2 eq)) |
2677 | (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst | |
2678 | 'nostore 'noanalysis)) | |
2679 | ||
54a0dee5 | 2680 | (org-goto-line thisline) |
20908596 CD |
2681 | (org-table-goto-column thiscol) |
2682 | (remove-text-properties (point-min) (point-max) '(org-untouchable t)) | |
2683 | (or noalign (and org-table-may-need-update (org-table-align)) | |
2684 | (and all (message "Re-applying formulas to %d lines...done" cnt))) | |
2685 | ||
2686 | ;; back to initial position | |
2687 | (message "Re-applying formulas...done") | |
54a0dee5 | 2688 | (org-goto-line thisline) |
20908596 CD |
2689 | (org-table-goto-column thiscol) |
2690 | (or noalign (and org-table-may-need-update (org-table-align)) | |
2691 | (and all (message "Re-applying formulas...done")))))) | |
2692 | ||
2693 | (defun org-table-iterate (&optional arg) | |
2694 | "Recalculate the table until it does not change anymore." | |
2695 | (interactive "P") | |
2696 | (let ((imax (if arg (prefix-numeric-value arg) 10)) | |
2697 | (i 0) | |
2698 | (lasttbl (buffer-substring (org-table-begin) (org-table-end))) | |
2699 | thistbl) | |
2700 | (catch 'exit | |
2701 | (while (< i imax) | |
2702 | (setq i (1+ i)) | |
2703 | (org-table-recalculate 'all) | |
2704 | (setq thistbl (buffer-substring (org-table-begin) (org-table-end))) | |
2705 | (if (not (string= lasttbl thistbl)) | |
2706 | (setq lasttbl thistbl) | |
2707 | (if (> i 1) | |
2708 | (message "Convergence after %d iterations" i) | |
2709 | (message "Table was already stable")) | |
2710 | (throw 'exit t))) | |
2711 | (error "No convergence after %d iterations" i)))) | |
2712 | ||
86fbb8ca CD |
2713 | (defun org-table-recalculate-buffer-tables () |
2714 | "Recalculate all tables in the current buffer." | |
2715 | (interactive) | |
2716 | (save-excursion | |
2717 | (save-restriction | |
2718 | (widen) | |
2719 | (org-table-map-tables (lambda () (org-table-recalculate t)) t)))) | |
2720 | ||
2721 | (defun org-table-iterate-buffer-tables () | |
2722 | "Iterate all tables in the buffer, to converge inter-table dependencies." | |
2723 | (interactive) | |
2724 | (let* ((imax 10) | |
2725 | (checksum (md5 (buffer-string))) | |
2726 | ||
2727 | c1 | |
2728 | (i imax)) | |
2729 | (save-excursion | |
2730 | (save-restriction | |
2731 | (widen) | |
2732 | (catch 'exit | |
2733 | (while (> i 0) | |
2734 | (setq i (1- i)) | |
2735 | (org-table-map-tables (lambda () (org-table-recalculate t)) t) | |
2736 | (if (equal checksum (setq c1 (md5 (buffer-string)))) | |
2737 | (progn | |
2738 | (message "Convergence after %d iterations" (- imax i)) | |
2739 | (throw 'exit t)) | |
2740 | (setq checksum c1))) | |
2741 | (error "No convergence after %d iterations" imax)))))) | |
2742 | ||
20908596 CD |
2743 | (defun org-table-formula-substitute-names (f) |
2744 | "Replace $const with values in string F." | |
2745 | (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?'))) | |
2746 | ;; First, check for column names | |
2747 | (while (setq start (string-match org-table-column-name-regexp f start)) | |
2748 | (setq start (1+ start)) | |
2749 | (setq a (assoc (match-string 1 f) org-table-column-names)) | |
2750 | (setq f (replace-match (concat "$" (cdr a)) t t f))) | |
2751 | ;; Parameters and constants | |
2752 | (setq start 0) | |
0bd48b37 CD |
2753 | (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start)) |
2754 | (if (match-end 2) | |
2755 | (setq start (match-end 2)) | |
2756 | (setq start (1+ start)) | |
2757 | (if (setq a (save-match-data | |
2758 | (org-table-get-constant (match-string 1 f)))) | |
2759 | (setq f (replace-match | |
2760 | (concat (if pp "(") a (if pp ")")) t t f))))) | |
20908596 CD |
2761 | (if org-table-formula-debug |
2762 | (put-text-property 0 (length f) :orig-formula f1 f)) | |
2763 | f)) | |
2764 | ||
2765 | (defun org-table-get-constant (const) | |
2766 | "Find the value for a parameter or constant in a formula. | |
2767 | Parameters get priority." | |
2768 | (or (cdr (assoc const org-table-local-parameters)) | |
2769 | (cdr (assoc const org-table-formula-constants-local)) | |
2770 | (cdr (assoc const org-table-formula-constants)) | |
2771 | (and (fboundp 'constants-get) (constants-get const)) | |
2772 | (and (string= (substring const 0 (min 5 (length const))) "PROP_") | |
2773 | (org-entry-get nil (substring const 5) 'inherit)) | |
2774 | "#UNDEFINED_NAME")) | |
2775 | ||
2776 | (defvar org-table-fedit-map | |
2777 | (let ((map (make-sparse-keymap))) | |
2778 | (org-defkey map "\C-x\C-s" 'org-table-fedit-finish) | |
2779 | (org-defkey map "\C-c\C-s" 'org-table-fedit-finish) | |
2780 | (org-defkey map "\C-c\C-c" 'org-table-fedit-finish) | |
86fbb8ca | 2781 | (org-defkey map "\C-c'" 'org-table-fedit-finish) |
20908596 | 2782 | (org-defkey map "\C-c\C-q" 'org-table-fedit-abort) |
33306645 | 2783 | (org-defkey map "\C-c?" 'org-table-show-reference) |
20908596 CD |
2784 | (org-defkey map [(meta shift up)] 'org-table-fedit-line-up) |
2785 | (org-defkey map [(meta shift down)] 'org-table-fedit-line-down) | |
2786 | (org-defkey map [(shift up)] 'org-table-fedit-ref-up) | |
2787 | (org-defkey map [(shift down)] 'org-table-fedit-ref-down) | |
2788 | (org-defkey map [(shift left)] 'org-table-fedit-ref-left) | |
2789 | (org-defkey map [(shift right)] 'org-table-fedit-ref-right) | |
2790 | (org-defkey map [(meta up)] 'org-table-fedit-scroll-down) | |
2791 | (org-defkey map [(meta down)] 'org-table-fedit-scroll) | |
2792 | (org-defkey map [(meta tab)] 'lisp-complete-symbol) | |
2793 | (org-defkey map "\M-\C-i" 'lisp-complete-symbol) | |
33306645 CD |
2794 | (org-defkey map [(tab)] 'org-table-fedit-lisp-indent) |
2795 | (org-defkey map "\C-i" 'org-table-fedit-lisp-indent) | |
20908596 CD |
2796 | (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type) |
2797 | (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates) | |
2798 | map)) | |
2799 | ||
2800 | (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu" | |
2801 | '("Edit-Formulas" | |
2802 | ["Finish and Install" org-table-fedit-finish t] | |
2803 | ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"] | |
2804 | ["Abort" org-table-fedit-abort t] | |
2805 | "--" | |
2806 | ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t] | |
2807 | ["Complete Lisp Symbol" lisp-complete-symbol t] | |
2808 | "--" | |
2809 | "Shift Reference at Point" | |
2810 | ["Up" org-table-fedit-ref-up t] | |
2811 | ["Down" org-table-fedit-ref-down t] | |
2812 | ["Left" org-table-fedit-ref-left t] | |
2813 | ["Right" org-table-fedit-ref-right t] | |
2814 | "-" | |
2815 | "Change Test Row for Column Formulas" | |
2816 | ["Up" org-table-fedit-line-up t] | |
2817 | ["Down" org-table-fedit-line-down t] | |
2818 | "--" | |
2819 | ["Scroll Table Window" org-table-fedit-scroll t] | |
2820 | ["Scroll Table Window down" org-table-fedit-scroll-down t] | |
2821 | ["Show Table Grid" org-table-fedit-toggle-coordinates | |
2822 | :style toggle :selected (with-current-buffer (marker-buffer org-pos) | |
2823 | org-table-overlay-coordinates)] | |
2824 | "--" | |
2825 | ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type | |
2826 | :style toggle :selected org-table-buffer-is-an])) | |
2827 | ||
2828 | (defvar org-pos) | |
2829 | ||
2830 | (defun org-table-edit-formulas () | |
2831 | "Edit the formulas of the current table in a separate buffer." | |
2832 | (interactive) | |
c8d0cf5c | 2833 | (when (save-excursion (beginning-of-line 1) (looking-at "[ \t]*#\\+TBLFM")) |
20908596 CD |
2834 | (beginning-of-line 0)) |
2835 | (unless (org-at-table-p) (error "Not at a table")) | |
2836 | (org-table-get-specials) | |
2837 | (let ((key (org-table-current-field-formula 'key 'noerror)) | |
2838 | (eql (sort (org-table-get-stored-formulas 'noerror) | |
33306645 | 2839 | 'org-table-formula-less-p)) |
20908596 CD |
2840 | (pos (move-marker (make-marker) (point))) |
2841 | (startline 1) | |
2842 | (wc (current-window-configuration)) | |
8d642074 | 2843 | (sel-win (selected-window)) |
20908596 CD |
2844 | (titles '((column . "# Column Formulas\n") |
2845 | (field . "# Field Formulas\n") | |
2846 | (named . "# Named Field Formulas\n"))) | |
2847 | entry s type title) | |
2848 | (org-switch-to-buffer-other-window "*Edit Formulas*") | |
2849 | (erase-buffer) | |
2850 | ;; Keep global-font-lock-mode from turning on font-lock-mode | |
2851 | (let ((font-lock-global-modes '(not fundamental-mode))) | |
2852 | (fundamental-mode)) | |
2853 | (org-set-local 'font-lock-global-modes (list 'not major-mode)) | |
2854 | (org-set-local 'org-pos pos) | |
2855 | (org-set-local 'org-window-configuration wc) | |
8d642074 | 2856 | (org-set-local 'org-selected-window sel-win) |
20908596 CD |
2857 | (use-local-map org-table-fedit-map) |
2858 | (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t) | |
2859 | (easy-menu-add org-table-fedit-menu) | |
2860 | (setq startline (org-current-line)) | |
2861 | (while (setq entry (pop eql)) | |
2862 | (setq type (cond | |
2863 | ((equal (string-to-char (car entry)) ?@) 'field) | |
2864 | ((string-match "^[0-9]" (car entry)) 'column) | |
2865 | (t 'named))) | |
2866 | (when (setq title (assq type titles)) | |
2867 | (or (bobp) (insert "\n")) | |
2868 | (insert (org-add-props (cdr title) nil 'face font-lock-comment-face)) | |
2869 | (setq titles (delq title titles))) | |
2870 | (if (equal key (car entry)) (setq startline (org-current-line))) | |
2871 | (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$") | |
2872 | (car entry) " = " (cdr entry) "\n")) | |
2873 | (remove-text-properties 0 (length s) '(face nil) s) | |
2874 | (insert s)) | |
2875 | (if (eq org-table-use-standard-references t) | |
2876 | (org-table-fedit-toggle-ref-type)) | |
54a0dee5 | 2877 | (org-goto-line startline) |
86fbb8ca | 2878 | (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands."))) |
20908596 CD |
2879 | |
2880 | (defun org-table-fedit-post-command () | |
2881 | (when (not (memq this-command '(lisp-complete-symbol))) | |
2882 | (let ((win (selected-window))) | |
2883 | (save-excursion | |
2884 | (condition-case nil | |
2885 | (org-table-show-reference) | |
2886 | (error nil)) | |
2887 | (select-window win))))) | |
2888 | ||
2889 | (defun org-table-formula-to-user (s) | |
2890 | "Convert a formula from internal to user representation." | |
2891 | (if (eq org-table-use-standard-references t) | |
2892 | (org-table-convert-refs-to-an s) | |
2893 | s)) | |
2894 | ||
2895 | (defun org-table-formula-from-user (s) | |
2896 | "Convert a formula from user to internal representation." | |
2897 | (if org-table-use-standard-references | |
2898 | (org-table-convert-refs-to-rc s) | |
2899 | s)) | |
2900 | ||
2901 | (defun org-table-convert-refs-to-rc (s) | |
2902 | "Convert spreadsheet references from AB7 to @7$28. | |
2903 | Works for single references, but also for entire formulas and even the | |
2904 | full TBLFM line." | |
2905 | (let ((start 0)) | |
0bd48b37 | 2906 | (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^)]*)\\)" s start) |
20908596 CD |
2907 | (cond |
2908 | ((match-end 3) | |
2909 | ;; format match, just advance | |
2910 | (setq start (match-end 0))) | |
2911 | ((and (> (match-beginning 0) 0) | |
2912 | (equal ?. (aref s (max (1- (match-beginning 0)) 0))) | |
2913 | (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0))))) | |
2914 | ;; 3.e5 or something like this. | |
2915 | (setq start (match-end 0))) | |
ed21c5c8 CD |
2916 | ((or (> (- (match-end 1) (match-beginning 1)) 2) |
2917 | ;; (member (match-string 1 s) | |
2918 | ;; '("arctan" "exp" "expm" "lnp" "log" "stir")) | |
2919 | ) | |
2920 | ;; function name, just advance | |
2921 | (setq start (match-end 0))) | |
20908596 CD |
2922 | (t |
2923 | (setq start (match-beginning 0) | |
2924 | s (replace-match | |
2925 | (if (equal (match-string 2 s) "&") | |
2926 | (format "$%d" (org-letters-to-number (match-string 1 s))) | |
2927 | (format "@%d$%d" | |
2928 | (string-to-number (match-string 2 s)) | |
2929 | (org-letters-to-number (match-string 1 s)))) | |
2930 | t t s))))) | |
2931 | s)) | |
2932 | ||
2933 | (defun org-table-convert-refs-to-an (s) | |
2934 | "Convert spreadsheet references from to @7$28 to AB7. | |
2935 | Works for single references, but also for entire formulas and even the | |
2936 | full TBLFM line." | |
2937 | (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s) | |
2938 | (setq s (replace-match | |
2939 | (format "%s%d" | |
2940 | (org-number-to-letters | |
2941 | (string-to-number (match-string 2 s))) | |
2942 | (string-to-number (match-string 1 s))) | |
2943 | t t s))) | |
2944 | (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s) | |
2945 | (setq s (replace-match (concat "\\1" | |
2946 | (org-number-to-letters | |
2947 | (string-to-number (match-string 2 s))) "&") | |
2948 | t nil s))) | |
2949 | s) | |
2950 | ||
2951 | (defun org-letters-to-number (s) | |
2952 | "Convert a base 26 number represented by letters into an integer. | |
2953 | For example: AB -> 28." | |
2954 | (let ((n 0)) | |
2955 | (setq s (upcase s)) | |
2956 | (while (> (length s) 0) | |
2957 | (setq n (+ (* n 26) (string-to-char s) (- ?A) 1) | |
2958 | s (substring s 1))) | |
2959 | n)) | |
2960 | ||
2961 | (defun org-number-to-letters (n) | |
2962 | "Convert an integer into a base 26 number represented by letters. | |
2963 | For example: 28 -> AB." | |
2964 | (let ((s "")) | |
2965 | (while (> n 0) | |
2966 | (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s) | |
2967 | n (/ (1- n) 26))) | |
2968 | s)) | |
2969 | ||
2970 | (defun org-table-fedit-convert-buffer (function) | |
33306645 | 2971 | "Convert all references in this buffer, using FUNCTION." |
20908596 CD |
2972 | (let ((line (org-current-line))) |
2973 | (goto-char (point-min)) | |
2974 | (while (not (eobp)) | |
2975 | (insert (funcall function (buffer-substring (point) (point-at-eol)))) | |
2976 | (delete-region (point) (point-at-eol)) | |
2977 | (or (eobp) (forward-char 1))) | |
54a0dee5 | 2978 | (org-goto-line line))) |
20908596 CD |
2979 | |
2980 | (defun org-table-fedit-toggle-ref-type () | |
2981 | "Convert all references in the buffer from B3 to @3$2 and back." | |
2982 | (interactive) | |
2983 | (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an)) | |
2984 | (org-table-fedit-convert-buffer | |
2985 | (if org-table-buffer-is-an | |
2986 | 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc)) | |
2987 | (message "Reference type switched to %s" | |
2988 | (if org-table-buffer-is-an "A1 etc" "@row$column"))) | |
2989 | ||
2990 | (defun org-table-fedit-ref-up () | |
2991 | "Shift the reference at point one row/hline up." | |
2992 | (interactive) | |
2993 | (org-table-fedit-shift-reference 'up)) | |
2994 | (defun org-table-fedit-ref-down () | |
2995 | "Shift the reference at point one row/hline down." | |
2996 | (interactive) | |
2997 | (org-table-fedit-shift-reference 'down)) | |
2998 | (defun org-table-fedit-ref-left () | |
2999 | "Shift the reference at point one field to the left." | |
3000 | (interactive) | |
3001 | (org-table-fedit-shift-reference 'left)) | |
3002 | (defun org-table-fedit-ref-right () | |
3003 | "Shift the reference at point one field to the right." | |
3004 | (interactive) | |
3005 | (org-table-fedit-shift-reference 'right)) | |
3006 | ||
3007 | (defun org-table-fedit-shift-reference (dir) | |
3008 | (cond | |
3009 | ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&") | |
3010 | (if (memq dir '(left right)) | |
3011 | (org-rematch-and-replace 1 (eq dir 'left)) | |
3012 | (error "Cannot shift reference in this direction"))) | |
3013 | ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)") | |
3014 | ;; A B3-like reference | |
3015 | (if (memq dir '(up down)) | |
3016 | (org-rematch-and-replace 2 (eq dir 'up)) | |
3017 | (org-rematch-and-replace 1 (eq dir 'left)))) | |
3018 | ((org-at-regexp-p | |
3019 | "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?") | |
3020 | ;; An internal reference | |
3021 | (if (memq dir '(up down)) | |
3022 | (org-rematch-and-replace 2 (eq dir 'up) (match-end 3)) | |
3023 | (org-rematch-and-replace 5 (eq dir 'left)))))) | |
3024 | ||
3025 | (defun org-rematch-and-replace (n &optional decr hline) | |
86fbb8ca | 3026 | "Re-match the group N, and replace it with the shifted reference." |
20908596 CD |
3027 | (or (match-end n) (error "Cannot shift reference in this direction")) |
3028 | (goto-char (match-beginning n)) | |
3029 | (and (looking-at (regexp-quote (match-string n))) | |
ff4be292 | 3030 | (replace-match (org-table-shift-refpart (match-string 0) decr hline) |
20908596 CD |
3031 | t t))) |
3032 | ||
ff4be292 | 3033 | (defun org-table-shift-refpart (ref &optional decr hline) |
86fbb8ca | 3034 | "Shift a reference part REF. |
20908596 CD |
3035 | If DECR is set, decrease the references row/column, else increase. |
3036 | If HLINE is set, this may be a hline reference, it certainly is not | |
3037 | a translation reference." | |
3038 | (save-match-data | |
3039 | (let* ((sign (string-match "^[-+]" ref)) n) | |
3040 | ||
3041 | (if sign (setq sign (substring ref 0 1) ref (substring ref 1))) | |
3042 | (cond | |
3043 | ((and hline (string-match "^I+" ref)) | |
3044 | (setq n (string-to-number (concat sign (number-to-string (length ref))))) | |
3045 | (setq n (+ n (if decr -1 1))) | |
3046 | (if (= n 0) (setq n (+ n (if decr -1 1)))) | |
3047 | (if sign | |
3048 | (setq sign (if (< n 0) "-" "+") n (abs n)) | |
3049 | (setq n (max 1 n))) | |
3050 | (concat sign (make-string n ?I))) | |
3051 | ||
3052 | ((string-match "^[0-9]+" ref) | |
3053 | (setq n (string-to-number (concat sign ref))) | |
3054 | (setq n (+ n (if decr -1 1))) | |
3055 | (if sign | |
3056 | (concat (if (< n 0) "-" "+") (number-to-string (abs n))) | |
3057 | (number-to-string (max 1 n)))) | |
3058 | ||
3059 | ((string-match "^[a-zA-Z]+" ref) | |
3060 | (org-number-to-letters | |
3061 | (max 1 (+ (org-letters-to-number ref) (if decr -1 1))))) | |
3062 | ||
3063 | (t (error "Cannot shift reference")))))) | |
3064 | ||
3065 | (defun org-table-fedit-toggle-coordinates () | |
33306645 | 3066 | "Toggle the display of coordinates in the referenced table." |
20908596 CD |
3067 | (interactive) |
3068 | (let ((pos (marker-position org-pos))) | |
3069 | (with-current-buffer (marker-buffer org-pos) | |
3070 | (save-excursion | |
3071 | (goto-char pos) | |
3072 | (org-table-toggle-coordinate-overlays))))) | |
3073 | ||
3074 | (defun org-table-fedit-finish (&optional arg) | |
3075 | "Parse the buffer for formula definitions and install them. | |
3076 | With prefix ARG, apply the new formulas to the table." | |
3077 | (interactive "P") | |
3078 | (org-table-remove-rectangle-highlight) | |
3079 | (if org-table-use-standard-references | |
3080 | (progn | |
3081 | (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc) | |
3082 | (setq org-table-buffer-is-an nil))) | |
8d642074 | 3083 | (let ((pos org-pos) (sel-win org-selected-window) eql var form) |
20908596 CD |
3084 | (goto-char (point-min)) |
3085 | (while (re-search-forward | |
3086 | "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)" | |
3087 | nil t) | |
3088 | (setq var (if (match-end 2) (match-string 2) (match-string 1)) | |
3089 | form (match-string 3)) | |
3090 | (setq form (org-trim form)) | |
3091 | (when (not (equal form "")) | |
3092 | (while (string-match "[ \t]*\n[ \t]*" form) | |
3093 | (setq form (replace-match " " t t form))) | |
3094 | (when (assoc var eql) | |
3095 | (error "Double formulas for %s" var)) | |
3096 | (push (cons var form) eql))) | |
3097 | (setq org-pos nil) | |
3098 | (set-window-configuration org-window-configuration) | |
8d642074 | 3099 | (select-window sel-win) |
20908596 CD |
3100 | (goto-char pos) |
3101 | (unless (org-at-table-p) | |
86fbb8ca | 3102 | (error "Lost table position - cannot install formulas")) |
20908596 CD |
3103 | (org-table-store-formulas eql) |
3104 | (move-marker pos nil) | |
3105 | (kill-buffer "*Edit Formulas*") | |
3106 | (if arg | |
3107 | (org-table-recalculate 'all) | |
3108 | (message "New formulas installed - press C-u C-c C-c to apply.")))) | |
3109 | ||
3110 | (defun org-table-fedit-abort () | |
3111 | "Abort editing formulas, without installing the changes." | |
3112 | (interactive) | |
3113 | (org-table-remove-rectangle-highlight) | |
8d642074 | 3114 | (let ((pos org-pos) (sel-win org-selected-window)) |
20908596 | 3115 | (set-window-configuration org-window-configuration) |
8d642074 | 3116 | (select-window sel-win) |
20908596 CD |
3117 | (goto-char pos) |
3118 | (move-marker pos nil) | |
3119 | (message "Formula editing aborted without installing changes"))) | |
3120 | ||
3121 | (defun org-table-fedit-lisp-indent () | |
3122 | "Pretty-print and re-indent Lisp expressions in the Formula Editor." | |
3123 | (interactive) | |
3124 | (let ((pos (point)) beg end ind) | |
3125 | (beginning-of-line 1) | |
3126 | (cond | |
3127 | ((looking-at "[ \t]") | |
3128 | (goto-char pos) | |
3129 | (call-interactively 'lisp-indent-line)) | |
3130 | ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos)) | |
3131 | ((not (fboundp 'pp-buffer)) | |
f924a367 | 3132 | (error "Cannot pretty-print. Command `pp-buffer' is not available")) |
20908596 CD |
3133 | ((looking-at "[$&@0-9a-zA-Z]+ *= *'(") |
3134 | (goto-char (- (match-end 0) 2)) | |
3135 | (setq beg (point)) | |
3136 | (setq ind (make-string (current-column) ?\ )) | |
3137 | (condition-case nil (forward-sexp 1) | |
3138 | (error | |
3139 | (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis"))) | |
3140 | (setq end (point)) | |
3141 | (save-restriction | |
3142 | (narrow-to-region beg end) | |
3143 | (if (eq last-command this-command) | |
3144 | (progn | |
3145 | (goto-char (point-min)) | |
3146 | (setq this-command nil) | |
3147 | (while (re-search-forward "[ \t]*\n[ \t]*" nil t) | |
3148 | (replace-match " "))) | |
3149 | (pp-buffer) | |
3150 | (untabify (point-min) (point-max)) | |
3151 | (goto-char (1+ (point-min))) | |
3152 | (while (re-search-forward "^." nil t) | |
3153 | (beginning-of-line 1) | |
3154 | (insert ind)) | |
3155 | (goto-char (point-max)) | |
3156 | (backward-delete-char 1))) | |
3157 | (goto-char beg)) | |
3158 | (t nil)))) | |
3159 | ||
3160 | (defvar org-show-positions nil) | |
3161 | ||
3162 | (defun org-table-show-reference (&optional local) | |
3163 | "Show the location/value of the $ expression at point." | |
3164 | (interactive) | |
3165 | (org-table-remove-rectangle-highlight) | |
3166 | (catch 'exit | |
3167 | (let ((pos (if local (point) org-pos)) | |
33306645 CD |
3168 | (face2 'highlight) |
3169 | (org-inhibit-highlight-removal t) | |
20908596 CD |
3170 | (win (selected-window)) |
3171 | (org-show-positions nil) | |
3172 | var name e what match dest) | |
3173 | (if local (org-table-get-specials)) | |
3174 | (setq what (cond | |
3175 | ((or (org-at-regexp-p org-table-range-regexp2) | |
3176 | (org-at-regexp-p org-table-translate-regexp) | |
3177 | (org-at-regexp-p org-table-range-regexp)) | |
3178 | (setq match | |
3179 | (save-match-data | |
3180 | (org-table-convert-refs-to-rc (match-string 0)))) | |
3181 | 'range) | |
3182 | ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name) | |
3183 | ((org-at-regexp-p "\\$[0-9]+") 'column) | |
3184 | ((not local) nil) | |
3185 | (t (error "No reference at point"))) | |
3186 | match (and what (or match (match-string 0)))) | |
3187 | (when (and match (not (equal (match-beginning 0) (point-at-bol)))) | |
3188 | (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0) | |
3189 | 'secondary-selection)) | |
3190 | (org-add-hook 'before-change-functions | |
3191 | 'org-table-remove-rectangle-highlight) | |
3192 | (if (eq what 'name) (setq var (substring match 1))) | |
3193 | (when (eq what 'range) | |
3194 | (or (equal (string-to-char match) ?@) (setq match (concat "@" match))) | |
3195 | (setq match (org-table-formula-substitute-names match))) | |
3196 | (unless local | |
3197 | (save-excursion | |
3198 | (end-of-line 1) | |
3199 | (re-search-backward "^\\S-" nil t) | |
3200 | (beginning-of-line 1) | |
3201 | (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=") | |
3202 | (setq dest | |
3203 | (save-match-data | |
3204 | (org-table-convert-refs-to-rc (match-string 1)))) | |
3205 | (org-table-add-rectangle-overlay | |
3206 | (match-beginning 1) (match-end 1) face2)))) | |
3207 | (if (and (markerp pos) (marker-buffer pos)) | |
3208 | (if (get-buffer-window (marker-buffer pos)) | |
3209 | (select-window (get-buffer-window (marker-buffer pos))) | |
3210 | (org-switch-to-buffer-other-window (get-buffer-window | |
3211 | (marker-buffer pos))))) | |
3212 | (goto-char pos) | |
3213 | (org-table-force-dataline) | |
3214 | (when dest | |
3215 | (setq name (substring dest 1)) | |
3216 | (cond | |
3217 | ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest) | |
3218 | (setq e (assoc name org-table-named-field-locations)) | |
54a0dee5 | 3219 | (org-goto-line (nth 1 e)) |
20908596 CD |
3220 | (org-table-goto-column (nth 2 e))) |
3221 | ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest) | |
3222 | (let ((l (string-to-number (match-string 1 dest))) | |
3223 | (c (string-to-number (match-string 2 dest)))) | |
54a0dee5 | 3224 | (org-goto-line (aref org-table-dlines l)) |
20908596 CD |
3225 | (org-table-goto-column c))) |
3226 | (t (org-table-goto-column (string-to-number name)))) | |
3227 | (move-marker pos (point)) | |
3228 | (org-table-highlight-rectangle nil nil face2)) | |
3229 | (cond | |
3230 | ((equal dest match)) | |
3231 | ((not match)) | |
3232 | ((eq what 'range) | |
3233 | (condition-case nil | |
3234 | (save-excursion | |
3235 | (org-table-get-range match nil nil 'highlight)) | |
3236 | (error nil))) | |
3237 | ((setq e (assoc var org-table-named-field-locations)) | |
54a0dee5 | 3238 | (org-goto-line (nth 1 e)) |
20908596 CD |
3239 | (org-table-goto-column (nth 2 e)) |
3240 | (org-table-highlight-rectangle (point) (point)) | |
3241 | (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e))) | |
3242 | ((setq e (assoc var org-table-column-names)) | |
3243 | (org-table-goto-column (string-to-number (cdr e))) | |
3244 | (org-table-highlight-rectangle (point) (point)) | |
3245 | (goto-char (org-table-begin)) | |
3246 | (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|") | |
3247 | (org-table-end) t) | |
3248 | (progn | |
3249 | (goto-char (match-beginning 1)) | |
3250 | (org-table-highlight-rectangle) | |
3251 | (message "Named column (column %s)" (cdr e))) | |
3252 | (error "Column name not found"))) | |
3253 | ((eq what 'column) | |
3254 | ;; column number | |
3255 | (org-table-goto-column (string-to-number (substring match 1))) | |
3256 | (org-table-highlight-rectangle (point) (point)) | |
3257 | (message "Column %s" (substring match 1))) | |
3258 | ((setq e (assoc var org-table-local-parameters)) | |
3259 | (goto-char (org-table-begin)) | |
3260 | (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t) | |
3261 | (progn | |
3262 | (goto-char (match-beginning 1)) | |
3263 | (org-table-highlight-rectangle) | |
3264 | (message "Local parameter.")) | |
3265 | (error "Parameter not found"))) | |
3266 | (t | |
3267 | (cond | |
3268 | ((not var) (error "No reference at point")) | |
3269 | ((setq e (assoc var org-table-formula-constants-local)) | |
3270 | (message "Local Constant: $%s=%s in #+CONSTANTS line." | |
3271 | var (cdr e))) | |
3272 | ((setq e (assoc var org-table-formula-constants)) | |
3273 | (message "Constant: $%s=%s in `org-table-formula-constants'." | |
3274 | var (cdr e))) | |
3275 | ((setq e (and (fboundp 'constants-get) (constants-get var))) | |
3276 | (message "Constant: $%s=%s, from `constants.el'%s." | |
3277 | var e (format " (%s units)" constants-unit-system))) | |
3278 | (t (error "Undefined name $%s" var))))) | |
3279 | (goto-char pos) | |
3280 | (when (and org-show-positions | |
33306645 CD |
3281 | (not (memq this-command '(org-table-fedit-scroll |
3282 | org-table-fedit-scroll-down)))) | |
20908596 CD |
3283 | (push pos org-show-positions) |
3284 | (push org-table-current-begin-pos org-show-positions) | |
3285 | (let ((min (apply 'min org-show-positions)) | |
3286 | (max (apply 'max org-show-positions))) | |
33306645 CD |
3287 | (goto-char min) (recenter 0) |
3288 | (goto-char max) | |
3289 | (or (pos-visible-in-window-p max) (recenter -1)))) | |
20908596 CD |
3290 | (select-window win)))) |
3291 | ||
3292 | (defun org-table-force-dataline () | |
3293 | "Make sure the cursor is in a dataline in a table." | |
3294 | (unless (save-excursion | |
3295 | (beginning-of-line 1) | |
3296 | (looking-at org-table-dataline-regexp)) | |
3297 | (let* ((re org-table-dataline-regexp) | |
3298 | (p1 (save-excursion (re-search-forward re nil 'move))) | |
3299 | (p2 (save-excursion (re-search-backward re nil 'move)))) | |
3300 | (cond ((and p1 p2) | |
3301 | (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point)))) | |
3302 | p1 p2))) | |
3303 | ((or p1 p2) (goto-char (or p1 p2))) | |
3304 | (t (error "No table dataline around here")))))) | |
3305 | ||
3306 | (defun org-table-fedit-line-up () | |
3307 | "Move cursor one line up in the window showing the table." | |
3308 | (interactive) | |
3309 | (org-table-fedit-move 'previous-line)) | |
3310 | ||
3311 | (defun org-table-fedit-line-down () | |
3312 | "Move cursor one line down in the window showing the table." | |
3313 | (interactive) | |
3314 | (org-table-fedit-move 'next-line)) | |
3315 | ||
3316 | (defun org-table-fedit-move (command) | |
33306645 | 3317 | "Move the cursor in the window showing the table. |
20908596 CD |
3318 | Use COMMAND to do the motion, repeat if necessary to end up in a data line." |
3319 | (let ((org-table-allow-automatic-line-recalculation nil) | |
3320 | (pos org-pos) (win (selected-window)) p) | |
3321 | (select-window (get-buffer-window (marker-buffer org-pos))) | |
3322 | (setq p (point)) | |
3323 | (call-interactively command) | |
3324 | (while (and (org-at-table-p) | |
3325 | (org-at-table-hline-p)) | |
3326 | (call-interactively command)) | |
3327 | (or (org-at-table-p) (goto-char p)) | |
3328 | (move-marker pos (point)) | |
3329 | (select-window win))) | |
3330 | ||
3331 | (defun org-table-fedit-scroll (N) | |
3332 | (interactive "p") | |
3333 | (let ((other-window-scroll-buffer (marker-buffer org-pos))) | |
3334 | (scroll-other-window N))) | |
3335 | ||
3336 | (defun org-table-fedit-scroll-down (N) | |
3337 | (interactive "p") | |
3338 | (org-table-fedit-scroll (- N))) | |
3339 | ||
3340 | (defvar org-table-rectangle-overlays nil) | |
3341 | ||
3342 | (defun org-table-add-rectangle-overlay (beg end &optional face) | |
3343 | "Add a new overlay." | |
86fbb8ca CD |
3344 | (let ((ov (make-overlay beg end))) |
3345 | (overlay-put ov 'face (or face 'secondary-selection)) | |
20908596 CD |
3346 | (push ov org-table-rectangle-overlays))) |
3347 | ||
3348 | (defun org-table-highlight-rectangle (&optional beg end face) | |
3349 | "Highlight rectangular region in a table." | |
3350 | (setq beg (or beg (point)) end (or end (point))) | |
3351 | (let ((b (min beg end)) | |
3352 | (e (max beg end)) | |
3353 | l1 c1 l2 c2 tmp) | |
3354 | (and (boundp 'org-show-positions) | |
3355 | (setq org-show-positions (cons b (cons e org-show-positions)))) | |
3356 | (goto-char (min beg end)) | |
3357 | (setq l1 (org-current-line) | |
3358 | c1 (org-table-current-column)) | |
3359 | (goto-char (max beg end)) | |
3360 | (setq l2 (org-current-line) | |
3361 | c2 (org-table-current-column)) | |
3362 | (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp)) | |
54a0dee5 | 3363 | (org-goto-line l1) |
20908596 CD |
3364 | (beginning-of-line 1) |
3365 | (loop for line from l1 to l2 do | |
3366 | (when (looking-at org-table-dataline-regexp) | |
3367 | (org-table-goto-column c1) | |
3368 | (skip-chars-backward "^|\n") (setq beg (point)) | |
3369 | (org-table-goto-column c2) | |
3370 | (skip-chars-forward "^|\n") (setq end (point)) | |
3371 | (org-table-add-rectangle-overlay beg end face)) | |
3372 | (beginning-of-line 2)) | |
3373 | (goto-char b)) | |
3374 | (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight)) | |
3375 | ||
3376 | (defun org-table-remove-rectangle-highlight (&rest ignore) | |
3377 | "Remove the rectangle overlays." | |
3378 | (unless org-inhibit-highlight-removal | |
3379 | (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight) | |
86fbb8ca | 3380 | (mapc 'delete-overlay org-table-rectangle-overlays) |
20908596 CD |
3381 | (setq org-table-rectangle-overlays nil))) |
3382 | ||
3383 | (defvar org-table-coordinate-overlays nil | |
33306645 | 3384 | "Collects the coordinate grid overlays, so that they can be removed.") |
20908596 CD |
3385 | (make-variable-buffer-local 'org-table-coordinate-overlays) |
3386 | ||
3387 | (defun org-table-overlay-coordinates () | |
3388 | "Add overlays to the table at point, to show row/column coordinates." | |
3389 | (interactive) | |
86fbb8ca | 3390 | (mapc 'delete-overlay org-table-coordinate-overlays) |
20908596 CD |
3391 | (setq org-table-coordinate-overlays nil) |
3392 | (save-excursion | |
3393 | (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg) | |
3394 | (goto-char (org-table-begin)) | |
3395 | (while (org-at-table-p) | |
3396 | (setq eol (point-at-eol)) | |
86fbb8ca | 3397 | (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol)))) |
20908596 CD |
3398 | (push ov org-table-coordinate-overlays) |
3399 | (setq hline (looking-at org-table-hline-regexp)) | |
3400 | (setq str (if hline (format "I*%-2d" (setq ih (1+ ih))) | |
3401 | (format "%4d" (setq id (1+ id))))) | |
3402 | (org-overlay-before-string ov str 'org-special-keyword 'evaporate) | |
3403 | (when hline | |
3404 | (setq ic 0) | |
3405 | (while (re-search-forward "[+|]\\(-+\\)" eol t) | |
3406 | (setq beg (1+ (match-beginning 0)) | |
3407 | ic (1+ ic) | |
3408 | s1 (concat "$" (int-to-string ic)) | |
3409 | s2 (org-number-to-letters ic) | |
3410 | str (if (eq org-table-use-standard-references t) s2 s1)) | |
86fbb8ca | 3411 | (setq ov (make-overlay beg (+ beg (length str)))) |
20908596 CD |
3412 | (push ov org-table-coordinate-overlays) |
3413 | (org-overlay-display ov str 'org-special-keyword 'evaporate))) | |
3414 | (beginning-of-line 2))))) | |
3415 | ||
3416 | (defun org-table-toggle-coordinate-overlays () | |
3417 | "Toggle the display of Row/Column numbers in tables." | |
3418 | (interactive) | |
3419 | (setq org-table-overlay-coordinates (not org-table-overlay-coordinates)) | |
3420 | (message "Row/Column number display turned %s" | |
3421 | (if org-table-overlay-coordinates "on" "off")) | |
3422 | (if (and (org-at-table-p) org-table-overlay-coordinates) | |
3423 | (org-table-align)) | |
3424 | (unless org-table-overlay-coordinates | |
86fbb8ca | 3425 | (mapc 'delete-overlay org-table-coordinate-overlays) |
20908596 CD |
3426 | (setq org-table-coordinate-overlays nil))) |
3427 | ||
3428 | (defun org-table-toggle-formula-debugger () | |
3429 | "Toggle the formula debugger in tables." | |
3430 | (interactive) | |
3431 | (setq org-table-formula-debug (not org-table-formula-debug)) | |
3432 | (message "Formula debugging has been turned %s" | |
3433 | (if org-table-formula-debug "on" "off"))) | |
3434 | ||
3435 | ;;; The orgtbl minor mode | |
3436 | ||
3437 | ;; Define a minor mode which can be used in other modes in order to | |
3438 | ;; integrate the org-mode table editor. | |
3439 | ||
3440 | ;; This is really a hack, because the org-mode table editor uses several | |
3441 | ;; keys which normally belong to the major mode, for example the TAB and | |
3442 | ;; RET keys. Here is how it works: The minor mode defines all the keys | |
3443 | ;; necessary to operate the table editor, but wraps the commands into a | |
3444 | ;; function which tests if the cursor is currently inside a table. If that | |
3445 | ;; is the case, the table editor command is executed. However, when any of | |
3446 | ;; those keys is used outside a table, the function uses `key-binding' to | |
3447 | ;; look up if the key has an associated command in another currently active | |
3448 | ;; keymap (minor modes, major mode, global), and executes that command. | |
3449 | ;; There might be problems if any of the keys used by the table editor is | |
3450 | ;; otherwise used as a prefix key. | |
3451 | ||
3452 | ;; Another challenge is that the key binding for TAB can be tab or \C-i, | |
3453 | ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode | |
3454 | ;; addresses this by checking explicitly for both bindings. | |
3455 | ||
3456 | ;; The optimized version (see variable `orgtbl-optimized') takes over | |
3457 | ;; all keys which are bound to `self-insert-command' in the *global map*. | |
3458 | ;; Some modes bind other commands to simple characters, for example | |
3459 | ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode | |
3460 | ;; active, this binding is ignored inside tables and replaced with a | |
3461 | ;; modified self-insert. | |
3462 | ||
86fbb8ca | 3463 | |
20908596 CD |
3464 | (defvar orgtbl-mode-map (make-keymap) |
3465 | "Keymap for `orgtbl-mode'.") | |
3466 | ||
3467 | ;;;###autoload | |
3468 | (defun turn-on-orgtbl () | |
3469 | "Unconditionally turn on `orgtbl-mode'." | |
3470 | (orgtbl-mode 1)) | |
3471 | ||
3472 | (defvar org-old-auto-fill-inhibit-regexp nil | |
86fbb8ca | 3473 | "Local variable used by `orgtbl-mode'.") |
20908596 | 3474 | |
8d642074 CD |
3475 | (defconst orgtbl-line-start-regexp |
3476 | "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\|TBLNAME\\):\\)" | |
20908596 CD |
3477 | "Matches a line belonging to an orgtbl.") |
3478 | ||
3479 | (defconst orgtbl-extra-font-lock-keywords | |
3480 | (list (list (concat "^" orgtbl-line-start-regexp ".*") | |
3481 | 0 (quote 'org-table) 'prepend)) | |
86fbb8ca | 3482 | "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.") |
20908596 | 3483 | |
56eb0904 SM |
3484 | ;; Install it as a minor mode. |
3485 | (put 'orgtbl-mode :included t) | |
3486 | (put 'orgtbl-mode :menu-tag "Org Table Mode") | |
86fbb8ca | 3487 | |
20908596 | 3488 | ;;;###autoload |
56eb0904 | 3489 | (define-minor-mode orgtbl-mode |
20908596 | 3490 | "The `org-mode' table editor as a minor mode for use in other modes." |
56eb0904 | 3491 | :lighter " OrgTbl" :keymap orgtbl-mode-map |
20908596 | 3492 | (org-load-modules-maybe) |
56eb0904 SM |
3493 | (cond |
3494 | ((org-mode-p) | |
3495 | ;; Exit without error, in case some hook functions calls this | |
3496 | ;; by accident in org-mode. | |
3497 | (message "Orgtbl-mode is not useful in org-mode, command ignored")) | |
3498 | (orgtbl-mode | |
3499 | (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?! | |
3500 | ;; Make sure we are first in minor-mode-map-alist | |
3501 | (let ((c (assq 'orgtbl-mode minor-mode-map-alist))) | |
3502 | ;; FIXME: maybe it should use emulation-mode-map-alists? | |
3503 | (and c (setq minor-mode-map-alist | |
3504 | (cons c (delq c minor-mode-map-alist))))) | |
3505 | (org-set-local (quote org-table-may-need-update) t) | |
3506 | (org-add-hook 'before-change-functions 'org-before-change-function | |
3507 | nil 'local) | |
3508 | (org-set-local 'org-old-auto-fill-inhibit-regexp | |
3509 | auto-fill-inhibit-regexp) | |
3510 | (org-set-local 'auto-fill-inhibit-regexp | |
3511 | (if auto-fill-inhibit-regexp | |
3512 | (concat orgtbl-line-start-regexp "\\|" | |
3513 | auto-fill-inhibit-regexp) | |
3514 | orgtbl-line-start-regexp)) | |
86fbb8ca | 3515 | (add-to-invisibility-spec '(org-cwidth)) |
56eb0904 SM |
3516 | (when (fboundp 'font-lock-add-keywords) |
3517 | (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords) | |
3518 | (org-restart-font-lock)) | |
3519 | (easy-menu-add orgtbl-mode-menu)) | |
3520 | (t | |
3521 | (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp) | |
3522 | (org-table-cleanup-narrow-column-properties) | |
3523 | (org-remove-from-invisibility-spec '(org-cwidth)) | |
3524 | (remove-hook 'before-change-functions 'org-before-change-function t) | |
3525 | (when (fboundp 'font-lock-remove-keywords) | |
3526 | (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords) | |
3527 | (org-restart-font-lock)) | |
3528 | (easy-menu-remove orgtbl-mode-menu) | |
3529 | (force-mode-line-update 'all)))) | |
20908596 | 3530 | |
ff4be292 | 3531 | (defun org-table-cleanup-narrow-column-properties () |
20908596 CD |
3532 | "Remove all properties related to narrow-column invisibility." |
3533 | (let ((s 1)) | |
3534 | (while (setq s (text-property-any s (point-max) | |
3535 | 'display org-narrow-column-arrow)) | |
3536 | (remove-text-properties s (1+ s) '(display t))) | |
3537 | (setq s 1) | |
3538 | (while (setq s (text-property-any s (point-max) 'org-cwidth 1)) | |
3539 | (remove-text-properties s (1+ s) '(org-cwidth t))) | |
3540 | (setq s 1) | |
3541 | (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth)) | |
3542 | (remove-text-properties s (1+ s) '(invisible t))))) | |
3543 | ||
20908596 CD |
3544 | (defun orgtbl-make-binding (fun n &rest keys) |
3545 | "Create a function for binding in the table minor mode. | |
3546 | FUN is the command to call inside a table. N is used to create a unique | |
3547 | command name. KEYS are keys that should be checked in for a command | |
3548 | to execute outside of tables." | |
3549 | (eval | |
3550 | (list 'defun | |
3551 | (intern (concat "orgtbl-hijacker-command-" (int-to-string n))) | |
3552 | '(arg) | |
3553 | (concat "In tables, run `" (symbol-name fun) "'.\n" | |
3554 | "Outside of tables, run the binding of `" | |
3555 | (mapconcat (lambda (x) (format "%s" x)) keys "' or `") | |
3556 | "'.") | |
3557 | '(interactive "p") | |
3558 | (list 'if | |
3559 | '(org-at-table-p) | |
3560 | (list 'call-interactively (list 'quote fun)) | |
3561 | (list 'let '(orgtbl-mode) | |
3562 | (list 'call-interactively | |
3563 | (append '(or) | |
3564 | (mapcar (lambda (k) | |
3565 | (list 'key-binding k)) | |
3566 | keys) | |
3567 | '('orgtbl-error)))))))) | |
3568 | ||
3569 | (defun orgtbl-error () | |
3570 | "Error when there is no default binding for a table key." | |
3571 | (interactive) | |
3572 | (error "This key has no function outside tables")) | |
3573 | ||
3574 | (defun orgtbl-setup () | |
3575 | "Setup orgtbl keymaps." | |
3576 | (let ((nfunc 0) | |
3577 | (bindings | |
365f8d85 SM |
3578 | '(([(meta shift left)] org-table-delete-column) |
3579 | ([(meta left)] org-table-move-column-left) | |
3580 | ([(meta right)] org-table-move-column-right) | |
3581 | ([(meta shift right)] org-table-insert-column) | |
3582 | ([(meta shift up)] org-table-kill-row) | |
3583 | ([(meta shift down)] org-table-insert-row) | |
3584 | ([(meta up)] org-table-move-row-up) | |
3585 | ([(meta down)] org-table-move-row-down) | |
3586 | ("\C-c\C-w" org-table-cut-region) | |
3587 | ("\C-c\M-w" org-table-copy-region) | |
3588 | ("\C-c\C-y" org-table-paste-rectangle) | |
3589 | ("\C-c-" org-table-insert-hline) | |
3590 | ("\C-c}" org-table-toggle-coordinate-overlays) | |
3591 | ("\C-c{" org-table-toggle-formula-debugger) | |
3592 | ("\C-m" org-table-next-row) | |
3593 | ([(shift return)] org-table-copy-down) | |
3594 | ("\C-c?" org-table-field-info) | |
3595 | ("\C-c " org-table-blank-field) | |
3596 | ("\C-c+" org-table-sum) | |
3597 | ("\C-c=" org-table-eval-formula) | |
3598 | ("\C-c'" org-table-edit-formulas) | |
3599 | ("\C-c`" org-table-edit-field) | |
3600 | ("\C-c*" org-table-recalculate) | |
3601 | ("\C-c^" org-table-sort-lines) | |
3602 | ("\M-a" org-table-beginning-of-field) | |
3603 | ("\M-e" org-table-end-of-field) | |
3604 | ([(control ?#)] org-table-rotate-recalc-marks))) | |
20908596 CD |
3605 | elt key fun cmd) |
3606 | (while (setq elt (pop bindings)) | |
3607 | (setq nfunc (1+ nfunc)) | |
3608 | (setq key (org-key (car elt)) | |
3609 | fun (nth 1 elt) | |
3610 | cmd (orgtbl-make-binding fun nfunc key)) | |
3611 | (org-defkey orgtbl-mode-map key cmd)) | |
3612 | ||
3613 | ;; Special treatment needed for TAB and RET | |
3614 | (org-defkey orgtbl-mode-map [(return)] | |
3615 | (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m")) | |
3616 | (org-defkey orgtbl-mode-map "\C-m" | |
3617 | (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)])) | |
3618 | ||
3619 | (org-defkey orgtbl-mode-map [(tab)] | |
3620 | (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i")) | |
3621 | (org-defkey orgtbl-mode-map "\C-i" | |
3622 | (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])) | |
3623 | ||
3624 | (org-defkey orgtbl-mode-map [(shift tab)] | |
3625 | (orgtbl-make-binding 'org-table-previous-field 104 | |
3626 | [(shift tab)] [(tab)] "\C-i")) | |
3627 | ||
8bfe682a CD |
3628 | |
3629 | (unless (featurep 'xemacs) | |
3630 | (org-defkey orgtbl-mode-map [S-iso-lefttab] | |
3631 | (orgtbl-make-binding 'org-table-previous-field 107 | |
3632 | [S-iso-lefttab] [backtab] [(shift tab)] | |
3633 | [(tab)] "\C-i"))) | |
c8d0cf5c CD |
3634 | |
3635 | (org-defkey orgtbl-mode-map [backtab] | |
3636 | (orgtbl-make-binding 'org-table-previous-field 108 | |
3637 | [backtab] [S-iso-lefttab] [(shift tab)] | |
3638 | [(tab)] "\C-i")) | |
3639 | ||
20908596 CD |
3640 | (org-defkey orgtbl-mode-map "\M-\C-m" |
3641 | (orgtbl-make-binding 'org-table-wrap-region 105 | |
3642 | "\M-\C-m" [(meta return)])) | |
3643 | (org-defkey orgtbl-mode-map [(meta return)] | |
3644 | (orgtbl-make-binding 'org-table-wrap-region 106 | |
3645 | [(meta return)] "\M-\C-m")) | |
3646 | ||
3647 | (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c) | |
ff4be292 CD |
3648 | (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region) |
3649 | ||
20908596 CD |
3650 | (when orgtbl-optimized |
3651 | ;; If the user wants maximum table support, we need to hijack | |
3652 | ;; some standard editing functions | |
3653 | (org-remap orgtbl-mode-map | |
3654 | 'self-insert-command 'orgtbl-self-insert-command | |
3655 | 'delete-char 'org-delete-char | |
3656 | 'delete-backward-char 'org-delete-backward-char) | |
3657 | (org-defkey orgtbl-mode-map "|" 'org-force-self-insert)) | |
3658 | (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu" | |
3659 | '("OrgTbl" | |
ff4be292 CD |
3660 | ["Create or convert" org-table-create-or-convert-from-region |
3661 | :active (not (org-at-table-p)) :keys "C-c |" ] | |
3662 | "--" | |
20908596 CD |
3663 | ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"] |
3664 | ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"] | |
3665 | ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"] | |
3666 | ["Next Row" org-return :active (org-at-table-p) :keys "RET"] | |
3667 | "--" | |
3668 | ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"] | |
3669 | ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "] | |
3670 | ["Copy Field from Above" | |
3671 | org-table-copy-down :active (org-at-table-p) :keys "S-RET"] | |
3672 | "--" | |
3673 | ("Column" | |
3674 | ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"] | |
3675 | ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"] | |
3676 | ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"] | |
3677 | ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]) | |
3678 | ("Row" | |
3679 | ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"] | |
3680 | ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"] | |
3681 | ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"] | |
3682 | ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"] | |
3683 | ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"] | |
3684 | "--" | |
3685 | ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"]) | |
3686 | ("Rectangle" | |
3687 | ["Copy Rectangle" org-copy-special :active (org-at-table-p)] | |
3688 | ["Cut Rectangle" org-cut-special :active (org-at-table-p)] | |
3689 | ["Paste Rectangle" org-paste-special :active (org-at-table-p)] | |
3690 | ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)]) | |
3691 | "--" | |
3692 | ("Radio tables" | |
3693 | ["Insert table template" orgtbl-insert-radio-table | |
3694 | (assq major-mode orgtbl-radio-table-templates)] | |
3695 | ["Comment/uncomment table" orgtbl-toggle-comment t]) | |
3696 | "--" | |
3697 | ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="] | |
3698 | ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="] | |
3699 | ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"] | |
3700 | ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"] | |
3701 | ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"] | |
3702 | ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"] | |
3703 | ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"] | |
3704 | ["Sum Column/Rectangle" org-table-sum | |
3705 | :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"] | |
3706 | ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"] | |
3707 | ["Debug Formulas" | |
3708 | org-table-toggle-formula-debugger :active (org-at-table-p) | |
3709 | :keys "C-c {" | |
3710 | :style toggle :selected org-table-formula-debug] | |
3711 | ["Show Col/Row Numbers" | |
3712 | org-table-toggle-coordinate-overlays :active (org-at-table-p) | |
3713 | :keys "C-c }" | |
3714 | :style toggle :selected org-table-overlay-coordinates] | |
3715 | )) | |
3716 | t)) | |
3717 | ||
3718 | (defun orgtbl-ctrl-c-ctrl-c (arg) | |
3719 | "If the cursor is inside a table, realign the table. | |
c8d0cf5c | 3720 | If it is a table to be sent away to a receiver, do it. |
20908596 CD |
3721 | With prefix arg, also recompute table." |
3722 | (interactive "P") | |
3723 | (let ((pos (point)) action) | |
3724 | (save-excursion | |
3725 | (beginning-of-line 1) | |
c8d0cf5c | 3726 | (setq action (cond ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0)) |
20908596 | 3727 | ((looking-at "[ \t]*|") pos) |
c8d0cf5c | 3728 | ((looking-at "[ \t]*#\\+TBLFM:") 'recalc)))) |
20908596 CD |
3729 | (cond |
3730 | ((integerp action) | |
3731 | (goto-char action) | |
3732 | (org-table-maybe-eval-formula) | |
3733 | (if arg | |
3734 | (call-interactively 'org-table-recalculate) | |
3735 | (org-table-maybe-recalculate-line)) | |
3736 | (call-interactively 'org-table-align) | |
acedf35c CD |
3737 | (when (orgtbl-send-table 'maybe) |
3738 | (run-hooks 'orgtbl-after-send-table-hook))) | |
20908596 CD |
3739 | ((eq action 'recalc) |
3740 | (save-excursion | |
3741 | (beginning-of-line 1) | |
3742 | (skip-chars-backward " \r\n\t") | |
3743 | (if (org-at-table-p) | |
3744 | (org-call-with-arg 'org-table-recalculate t)))) | |
3745 | (t (let (orgtbl-mode) | |
3746 | (call-interactively (key-binding "\C-c\C-c"))))))) | |
3747 | ||
ff4be292 CD |
3748 | (defun orgtbl-create-or-convert-from-region (arg) |
3749 | "Create table or convert region to table, if no conflicting binding. | |
3750 | This installs the table binding `C-c |', but only if there is no | |
3751 | conflicting binding to this key outside orgtbl-mode." | |
3752 | (interactive "P") | |
3753 | (let* (orgtbl-mode (cmd (key-binding "\C-c|"))) | |
3754 | (if cmd | |
3755 | (call-interactively cmd) | |
3756 | (call-interactively 'org-table-create-or-convert-from-region)))) | |
3757 | ||
20908596 CD |
3758 | (defun orgtbl-tab (arg) |
3759 | "Justification and field motion for `orgtbl-mode'." | |
3760 | (interactive "P") | |
3761 | (if arg (org-table-edit-field t) | |
3762 | (org-table-justify-field-maybe) | |
3763 | (org-table-next-field))) | |
3764 | ||
3765 | (defun orgtbl-ret () | |
3766 | "Justification and field motion for `orgtbl-mode'." | |
3767 | (interactive) | |
ff4be292 CD |
3768 | (if (bobp) |
3769 | (newline) | |
3770 | (org-table-justify-field-maybe) | |
3771 | (org-table-next-row))) | |
20908596 CD |
3772 | |
3773 | (defun orgtbl-self-insert-command (N) | |
3774 | "Like `self-insert-command', use overwrite-mode for whitespace in tables. | |
3775 | If the cursor is in a table looking at whitespace, the whitespace is | |
3776 | overwritten, and the table is not marked as requiring realignment." | |
3777 | (interactive "p") | |
3778 | (if (and (org-at-table-p) | |
3779 | (or | |
3780 | (and org-table-auto-blank-field | |
3781 | (member last-command | |
3782 | '(orgtbl-hijacker-command-100 | |
3783 | orgtbl-hijacker-command-101 | |
3784 | orgtbl-hijacker-command-102 | |
3785 | orgtbl-hijacker-command-103 | |
3786 | orgtbl-hijacker-command-104 | |
c8d0cf5c CD |
3787 | orgtbl-hijacker-command-105 |
3788 | yas/expand)) | |
20908596 CD |
3789 | (org-table-blank-field)) |
3790 | t) | |
3791 | (eq N 1) | |
3792 | (looking-at "[^|\n]* +|")) | |
3793 | (let (org-table-may-need-update) | |
3794 | (goto-char (1- (match-end 0))) | |
3795 | (delete-backward-char 1) | |
3796 | (goto-char (match-beginning 0)) | |
3797 | (self-insert-command N)) | |
3798 | (setq org-table-may-need-update t) | |
c8d0cf5c CD |
3799 | (let* (orgtbl-mode |
3800 | a | |
3801 | (cmd (or (key-binding | |
3802 | (or (and (listp function-key-map) | |
3803 | (setq a (assoc last-input-event function-key-map)) | |
3804 | (cdr a)) | |
3805 | (vector last-input-event))) | |
3806 | 'self-insert-command))) | |
3807 | (call-interactively cmd) | |
3808 | (if (and org-self-insert-cluster-for-undo | |
3809 | (eq cmd 'self-insert-command)) | |
3810 | (if (not (eq last-command 'orgtbl-self-insert-command)) | |
3811 | (setq org-self-insert-command-undo-counter 1) | |
3812 | (if (>= org-self-insert-command-undo-counter 20) | |
3813 | (setq org-self-insert-command-undo-counter 1) | |
3814 | (and (> org-self-insert-command-undo-counter 0) | |
3815 | buffer-undo-list | |
3816 | (not (cadr buffer-undo-list)) ; remove nil entry | |
3817 | (setcdr buffer-undo-list (cddr buffer-undo-list))) | |
3818 | (setq org-self-insert-command-undo-counter | |
3819 | (1+ org-self-insert-command-undo-counter)))))))) | |
20908596 CD |
3820 | |
3821 | (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$" | |
3822 | "Regular expression matching exponentials as produced by calc.") | |
3823 | ||
3824 | (defun orgtbl-export (table target) | |
3825 | (require 'org-exp) | |
3826 | (let ((func (intern (concat "orgtbl-to-" (symbol-name target)))) | |
3827 | (lines (org-split-string table "[ \t]*\n[ \t]*")) | |
3828 | org-table-last-alignment org-table-last-column-widths | |
3829 | maxcol column) | |
3830 | (if (not (fboundp func)) | |
3831 | (error "Cannot export orgtbl table to %s" target)) | |
3832 | (setq lines (org-table-clean-before-export lines)) | |
3833 | (setq table | |
3834 | (mapcar | |
3835 | (lambda (x) | |
3836 | (if (string-match org-table-hline-regexp x) | |
3837 | 'hline | |
3838 | (org-split-string (org-trim x) "\\s-*|\\s-*"))) | |
3839 | lines)) | |
3840 | (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0)) | |
3841 | table))) | |
3842 | (loop for i from (1- maxcol) downto 0 do | |
3843 | (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table)) | |
3844 | (setq column (delq nil column)) | |
3845 | (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths) | |
3846 | (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)) | |
3847 | (funcall func table nil))) | |
3848 | ||
3849 | (defun orgtbl-gather-send-defs () | |
86fbb8ca | 3850 | "Gather a plist of :name, :transform, :params for each destination before |
20908596 CD |
3851 | a radio table." |
3852 | (save-excursion | |
3853 | (goto-char (org-table-begin)) | |
3854 | (let (rtn) | |
3855 | (beginning-of-line 0) | |
86fbb8ca | 3856 | (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?") |
20908596 CD |
3857 | (let ((name (org-no-properties (match-string 1))) |
3858 | (transform (intern (match-string 2))) | |
3859 | (params (if (match-end 3) | |
3860 | (read (concat "(" (match-string 3) ")"))))) | |
3861 | (push (list :name name :transform transform :params params) | |
3862 | rtn) | |
3863 | (beginning-of-line 0))) | |
3864 | rtn))) | |
3865 | ||
3866 | (defun orgtbl-send-replace-tbl (name txt) | |
3867 | "Find and replace table NAME with TXT." | |
3868 | (save-excursion | |
3869 | (goto-char (point-min)) | |
3870 | (unless (re-search-forward | |
3871 | (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t) | |
3872 | (error "Don't know where to insert translated table")) | |
3873 | (goto-char (match-beginning 0)) | |
3874 | (beginning-of-line 2) | |
3875 | (save-excursion | |
3876 | (let ((beg (point))) | |
3877 | (unless (re-search-forward | |
3878 | (concat "END RECEIVE ORGTBL +" name) nil t) | |
3879 | (error "Cannot find end of insertion region")) | |
3880 | (beginning-of-line 1) | |
3881 | (delete-region beg (point)))) | |
3882 | (insert txt "\n"))) | |
3883 | ||
621f83e4 | 3884 | ;;;###autoload |
2c3ad40d CD |
3885 | (defun org-table-to-lisp (&optional txt) |
3886 | "Convert the table at point to a Lisp structure. | |
3887 | The structure will be a list. Each item is either the symbol `hline' | |
3888 | for a horizontal separator line, or a list of field values as strings. | |
3889 | The table is taken from the parameter TXT, or from the buffer at point." | |
3890 | (unless txt | |
3891 | (unless (org-at-table-p) | |
3892 | (error "No table at point"))) | |
ff4be292 | 3893 | (let* ((txt (or txt |
2c3ad40d CD |
3894 | (buffer-substring-no-properties (org-table-begin) |
3895 | (org-table-end)))) | |
3896 | (lines (org-split-string txt "[ \t]*\n[ \t]*"))) | |
3897 | ||
3898 | (mapcar | |
3899 | (lambda (x) | |
3900 | (if (string-match org-table-hline-regexp x) | |
3901 | 'hline | |
3902 | (org-split-string (org-trim x) "\\s-*|\\s-*"))) | |
3903 | lines))) | |
3904 | ||
20908596 | 3905 | (defun orgtbl-send-table (&optional maybe) |
33306645 | 3906 | "Send a transformed version of this table to the receiver position. |
20908596 CD |
3907 | With argument MAYBE, fail quietly if no transformation is defined for |
3908 | this table." | |
3909 | (interactive) | |
3910 | (catch 'exit | |
3911 | (unless (org-at-table-p) (error "Not at a table")) | |
3912 | ;; when non-interactive, we assume align has just happened. | |
3913 | (when (interactive-p) (org-table-align)) | |
3914 | (let ((dests (orgtbl-gather-send-defs)) | |
3915 | (txt (buffer-substring-no-properties (org-table-begin) | |
3916 | (org-table-end))) | |
3917 | (ntbl 0)) | |
3918 | (unless dests (if maybe (throw 'exit nil) | |
f924a367 | 3919 | (error "Don't know how to transform this table"))) |
20908596 CD |
3920 | (dolist (dest dests) |
3921 | (let* ((name (plist-get dest :name)) | |
3922 | (transform (plist-get dest :transform)) | |
3923 | (params (plist-get dest :params)) | |
3924 | (skip (plist-get params :skip)) | |
3925 | (skipcols (plist-get params :skipcols)) | |
3926 | beg | |
3927 | (lines (org-table-clean-before-export | |
3928 | (nthcdr (or skip 0) | |
3929 | (org-split-string txt "[ \t]*\n[ \t]*")))) | |
3930 | (i0 (if org-table-clean-did-remove-column 2 1)) | |
3931 | (table (mapcar | |
3932 | (lambda (x) | |
3933 | (if (string-match org-table-hline-regexp x) | |
3934 | 'hline | |
3935 | (org-remove-by-index | |
3936 | (org-split-string (org-trim x) "\\s-*|\\s-*") | |
3937 | skipcols i0))) | |
3938 | lines)) | |
3939 | (fun (if (= i0 2) 'cdr 'identity)) | |
3940 | (org-table-last-alignment | |
3941 | (org-remove-by-index (funcall fun org-table-last-alignment) | |
3942 | skipcols i0)) | |
3943 | (org-table-last-column-widths | |
3944 | (org-remove-by-index (funcall fun org-table-last-column-widths) | |
3945 | skipcols i0)) | |
3946 | (txt (if (fboundp transform) | |
3947 | (funcall transform table params) | |
3948 | (error "No such transformation function %s" transform)))) | |
3949 | (orgtbl-send-replace-tbl name txt)) | |
3950 | (setq ntbl (1+ ntbl))) | |
3951 | (message "Table converted and installed at %d receiver location%s" | |
acedf35c CD |
3952 | ntbl (if (> ntbl 1) "s" "")) |
3953 | (if (> ntbl 0) | |
3954 | ntbl | |
3955 | nil)))) | |
20908596 CD |
3956 | |
3957 | (defun org-remove-by-index (list indices &optional i0) | |
3958 | "Remove the elements in LIST with indices in INDICES. | |
3959 | First element has index 0, or I0 if given." | |
3960 | (if (not indices) | |
3961 | list | |
3962 | (if (integerp indices) (setq indices (list indices))) | |
3963 | (setq i0 (1- (or i0 0))) | |
3964 | (delq :rm (mapcar (lambda (x) | |
3965 | (setq i0 (1+ i0)) | |
3966 | (if (memq i0 indices) :rm x)) | |
3967 | list)))) | |
3968 | ||
3969 | (defun orgtbl-toggle-comment () | |
3970 | "Comment or uncomment the orgtbl at point." | |
3971 | (interactive) | |
3972 | (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp)) | |
3973 | (re2 (concat "^" orgtbl-line-start-regexp)) | |
3974 | (commented (save-excursion (beginning-of-line 1) | |
3975 | (cond ((looking-at re1) t) | |
3976 | ((looking-at re2) nil) | |
3977 | (t (error "Not at an org table"))))) | |
3978 | (re (if commented re1 re2)) | |
3979 | beg end) | |
3980 | (save-excursion | |
3981 | (beginning-of-line 1) | |
3982 | (while (looking-at re) (beginning-of-line 0)) | |
3983 | (beginning-of-line 2) | |
3984 | (setq beg (point)) | |
3985 | (while (looking-at re) (beginning-of-line 2)) | |
3986 | (setq end (point))) | |
3987 | (comment-region beg end (if commented '(4) nil)))) | |
3988 | ||
3989 | (defun orgtbl-insert-radio-table () | |
3990 | "Insert a radio table template appropriate for this major mode." | |
3991 | (interactive) | |
3992 | (let* ((e (assq major-mode orgtbl-radio-table-templates)) | |
3993 | (txt (nth 1 e)) | |
3994 | name pos) | |
3995 | (unless e (error "No radio table setup defined for %s" major-mode)) | |
3996 | (setq name (read-string "Table name: ")) | |
3997 | (while (string-match "%n" txt) | |
3998 | (setq txt (replace-match name t t txt))) | |
3999 | (or (bolp) (insert "\n")) | |
4000 | (setq pos (point)) | |
4001 | (insert txt) | |
4002 | (goto-char pos))) | |
4003 | ||
4004 | ;; Dynamically bound input and output for table formatting. | |
4005 | (defvar *orgtbl-table* nil | |
4006 | "Carries the current table through formatting routines.") | |
4007 | (defvar *orgtbl-rtn* nil | |
4008 | "Formatting routines push the output lines here.") | |
4009 | ;; Formatting parameters for the current table section. | |
86fbb8ca CD |
4010 | (defvar *orgtbl-hline* nil "Text used for horizontal lines.") |
4011 | (defvar *orgtbl-sep* nil "Text used as a column separator.") | |
4012 | (defvar *orgtbl-default-fmt* nil "Default format for each entry.") | |
4013 | (defvar *orgtbl-fmt* nil "Format for each entry.") | |
4014 | (defvar *orgtbl-efmt* nil "Format for numbers.") | |
4015 | (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.") | |
4016 | (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.") | |
4017 | (defvar *orgtbl-lstart* nil "Text starting a row.") | |
4018 | (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.") | |
4019 | (defvar *orgtbl-lend* nil "Text ending a row.") | |
4020 | (defvar *orgtbl-llend* nil "Specializes lend for the last row.") | |
20908596 CD |
4021 | |
4022 | (defsubst orgtbl-get-fmt (fmt i) | |
4023 | "Retrieve the format from FMT corresponding to the Ith column." | |
4024 | (if (and (not (functionp fmt)) (consp fmt)) | |
4025 | (plist-get fmt i) | |
4026 | fmt)) | |
4027 | ||
4028 | (defsubst orgtbl-apply-fmt (fmt &rest args) | |
4029 | "Apply format FMT to the arguments. NIL FMTs return the first argument." | |
4030 | (cond ((functionp fmt) (apply fmt args)) | |
4031 | (fmt (apply 'format fmt args)) | |
4032 | (args (car args)) | |
4033 | (t args))) | |
4034 | ||
4035 | (defsubst orgtbl-eval-str (str) | |
4036 | "If STR is a function, evaluate it with no arguments." | |
4037 | (if (functionp str) | |
4038 | (funcall str) | |
4039 | str)) | |
4040 | ||
4041 | (defun orgtbl-format-line (line) | |
4042 | "Format LINE as a table row." | |
4043 | (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*)) | |
4044 | (let* ((i 0) | |
4045 | (line | |
4046 | (mapcar | |
4047 | (lambda (f) | |
4048 | (setq i (1+ i)) | |
4049 | (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i)) | |
4050 | (f (if (and efmt (string-match orgtbl-exp-regexp f)) | |
4051 | (orgtbl-apply-fmt efmt (match-string 1 f) | |
4052 | (match-string 2 f)) | |
4053 | f))) | |
33306645 CD |
4054 | (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i) |
4055 | *orgtbl-default-fmt*) | |
4056 | f))) | |
20908596 CD |
4057 | line))) |
4058 | (push (if *orgtbl-lfmt* | |
4059 | (orgtbl-apply-fmt *orgtbl-lfmt* line) | |
4060 | (concat (orgtbl-eval-str *orgtbl-lstart*) | |
4061 | (mapconcat 'identity line *orgtbl-sep*) | |
4062 | (orgtbl-eval-str *orgtbl-lend*))) | |
4063 | *orgtbl-rtn*)))) | |
4064 | ||
4065 | (defun orgtbl-format-section (section-stopper) | |
4066 | "Format lines until the first occurrence of SECTION-STOPPER." | |
4067 | (let (prevline) | |
4068 | (progn | |
4069 | (while (not (eq (car *orgtbl-table*) section-stopper)) | |
4070 | (if prevline (orgtbl-format-line prevline)) | |
4071 | (setq prevline (pop *orgtbl-table*))) | |
4072 | (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*) | |
4073 | (*orgtbl-lend* *orgtbl-llend*) | |
4074 | (*orgtbl-lfmt* *orgtbl-llfmt*)) | |
4075 | (orgtbl-format-line prevline)))))) | |
4076 | ||
4077 | (defun orgtbl-to-generic (table params) | |
4078 | "Convert the orgtbl-mode TABLE to some other format. | |
4079 | This generic routine can be used for many standard cases. | |
4080 | TABLE is a list, each entry either the symbol `hline' for a horizontal | |
4081 | separator line, or a list of fields for that line. | |
4082 | PARAMS is a property list of parameters that can influence the conversion. | |
4083 | For the generic converter, some parameters are obligatory: You need to | |
b349f79f | 4084 | specify either :lfmt, or all of (:lstart :lend :sep). |
20908596 CD |
4085 | |
4086 | Valid parameters are | |
4087 | ||
4088 | :splice When set to t, return only table body lines, don't wrap | |
b349f79f CD |
4089 | them into :tstart and :tend. Default is nil. When :splice |
4090 | is non-nil, this also means that the exporter should not look | |
4091 | for and interpret header and footer sections. | |
20908596 CD |
4092 | |
4093 | :hline String to be inserted on horizontal separation lines. | |
4094 | May be nil to ignore hlines. | |
4095 | ||
4096 | :sep Separator between two fields | |
4097 | :remove-nil-lines Do not include lines that evaluate to nil. | |
4098 | ||
4099 | ||
b349f79f CD |
4100 | Each in the following group may be either a string or a function |
4101 | of no arguments returning a string: | |
20908596 CD |
4102 | :tstart String to start the table. Ignored when :splice is t. |
4103 | :tend String to end the table. Ignored when :splice is t. | |
4104 | :lstart String to start a new table line. | |
4105 | :llstart String to start the last table line, defaults to :lstart. | |
4106 | :lend String to end a table line | |
4107 | :llend String to end the last table line, defaults to :lend. | |
4108 | ||
b349f79f CD |
4109 | Each in the following group may be a string, a function of one |
4110 | argument (the field or line) returning a string, or a plist | |
4111 | mapping columns to either of the above: | |
20908596 CD |
4112 | :lfmt Format for entire line, with enough %s to capture all fields. |
4113 | If this is present, :lstart, :lend, and :sep are ignored. | |
4114 | :llfmt Format for the entire last line, defaults to :lfmt. | |
4115 | :fmt A format to be used to wrap the field, should contain | |
4116 | %s for the original field value. For example, to wrap | |
4117 | everything in dollars, you could use :fmt \"$%s$\". | |
4118 | This may also be a property list with column numbers and | |
4119 | formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\") | |
4120 | ||
4121 | :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt | |
4122 | Same as above, specific for the header lines in the table. | |
4123 | All lines before the first hline are treated as header. | |
4124 | If any of these is not present, the data line value is used. | |
4125 | ||
b349f79f | 4126 | This may be either a string or a function of two arguments: |
20908596 CD |
4127 | :efmt Use this format to print numbers with exponentials. |
4128 | The format should have %s twice for inserting mantissa | |
4129 | and exponent, for example \"%s\\\\times10^{%s}\". This | |
4130 | may also be a property list with column numbers and | |
4131 | formats. :fmt will still be applied after :efmt. | |
4132 | ||
4133 | In addition to this, the parameters :skip and :skipcols are always handled | |
4134 | directly by `orgtbl-send-table'. See manual." | |
4135 | (interactive) | |
4136 | ||
4137 | (let* ((splicep (plist-get params :splice)) | |
4138 | (hline (plist-get params :hline)) | |
4139 | (remove-nil-linesp (plist-get params :remove-nil-lines)) | |
86fbb8ca | 4140 | (remove-newlines (plist-get params :remove-newlines)) |
20908596 CD |
4141 | (*orgtbl-hline* hline) |
4142 | (*orgtbl-table* table) | |
4143 | (*orgtbl-sep* (plist-get params :sep)) | |
4144 | (*orgtbl-efmt* (plist-get params :efmt)) | |
4145 | (*orgtbl-lstart* (plist-get params :lstart)) | |
4146 | (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*)) | |
4147 | (*orgtbl-lend* (plist-get params :lend)) | |
4148 | (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*)) | |
4149 | (*orgtbl-lfmt* (plist-get params :lfmt)) | |
4150 | (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*)) | |
4151 | (*orgtbl-fmt* (plist-get params :fmt)) | |
4152 | *orgtbl-rtn*) | |
4153 | ||
4154 | ;; Put header | |
4155 | (unless splicep | |
b349f79f CD |
4156 | (when (plist-member params :tstart) |
4157 | (let ((tstart (orgtbl-eval-str (plist-get params :tstart)))) | |
4158 | (if tstart (push tstart *orgtbl-rtn*))))) | |
20908596 CD |
4159 | |
4160 | ;; Do we have a heading section? If so, format it and handle the | |
4161 | ;; trailing hline. | |
db55f368 CD |
4162 | (if (and (not splicep) |
4163 | (or (consp (car *orgtbl-table*)) | |
4164 | (consp (nth 1 *orgtbl-table*))) | |
4165 | (memq 'hline (cdr *orgtbl-table*))) | |
20908596 | 4166 | (progn |
db55f368 CD |
4167 | (when (eq 'hline (car *orgtbl-table*)) |
4168 | ;; there is a hline before the first data line | |
4169 | (and hline (push hline *orgtbl-rtn*)) | |
4170 | (pop *orgtbl-table*)) | |
20908596 CD |
4171 | (let* ((*orgtbl-lstart* (or (plist-get params :hlstart) |
4172 | *orgtbl-lstart*)) | |
4173 | (*orgtbl-llstart* (or (plist-get params :hllstart) | |
4174 | *orgtbl-llstart*)) | |
4175 | (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*)) | |
4176 | (*orgtbl-llend* (or (plist-get params :hllend) | |
4177 | (plist-get params :hlend) *orgtbl-llend*)) | |
4178 | (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*)) | |
4179 | (*orgtbl-llfmt* (or (plist-get params :hllfmt) | |
4180 | (plist-get params :hlfmt) *orgtbl-llfmt*)) | |
4181 | (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*)) | |
4182 | (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*))) | |
4183 | (orgtbl-format-section 'hline)) | |
4184 | (if hline (push hline *orgtbl-rtn*)) | |
4185 | (pop *orgtbl-table*))) | |
4186 | ||
4187 | ;; Now format the main section. | |
4188 | (orgtbl-format-section nil) | |
4189 | ||
4190 | (unless splicep | |
b349f79f | 4191 | (when (plist-member params :tend) |
33306645 CD |
4192 | (let ((tend (orgtbl-eval-str (plist-get params :tend)))) |
4193 | (if tend (push tend *orgtbl-rtn*))))) | |
20908596 | 4194 | |
86fbb8ca CD |
4195 | (mapconcat (if remove-newlines |
4196 | (lambda (tend) | |
4197 | (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend)) | |
4198 | 'identity) | |
4199 | (nreverse (if remove-nil-linesp | |
4200 | (remq nil *orgtbl-rtn*) | |
4201 | *orgtbl-rtn*)) "\n"))) | |
20908596 | 4202 | |
b349f79f CD |
4203 | (defun orgtbl-to-tsv (table params) |
4204 | "Convert the orgtbl-mode table to TAB separated material." | |
4205 | (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params))) | |
4206 | (defun orgtbl-to-csv (table params) | |
4207 | "Convert the orgtbl-mode table to CSV material. | |
4208 | This does take care of the proper quoting of fields with comma or quotes." | |
4209 | (orgtbl-to-generic table (org-combine-plists | |
4210 | '(:sep "," :fmt org-quote-csv-field) | |
4211 | params))) | |
4212 | ||
20908596 CD |
4213 | (defun orgtbl-to-latex (table params) |
4214 | "Convert the orgtbl-mode TABLE to LaTeX. | |
4215 | TABLE is a list, each entry either the symbol `hline' for a horizontal | |
4216 | separator line, or a list of fields for that line. | |
4217 | PARAMS is a property list of parameters that can influence the conversion. | |
4218 | Supports all parameters from `orgtbl-to-generic'. Most important for | |
4219 | LaTeX are: | |
4220 | ||
4221 | :splice When set to t, return only table body lines, don't wrap | |
4222 | them into a tabular environment. Default is nil. | |
4223 | ||
4224 | :fmt A format to be used to wrap the field, should contain %s for the | |
4225 | original field value. For example, to wrap everything in dollars, | |
4226 | use :fmt \"$%s$\". This may also be a property list with column | |
4227 | numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\") | |
4228 | The format may also be a function that formats its one argument. | |
4229 | ||
4230 | :efmt Format for transforming numbers with exponentials. The format | |
4231 | should have %s twice for inserting mantissa and exponent, for | |
4232 | example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\". | |
4233 | This may also be a property list with column numbers and formats. | |
4234 | The format may also be a function that formats its two arguments. | |
4235 | ||
4236 | :llend If you find too much space below the last line of a table, | |
4237 | pass a value of \"\" for :llend to suppress the final \\\\. | |
4238 | ||
4239 | The general parameters :skip and :skipcols have already been applied when | |
4240 | this function is called." | |
4241 | (let* ((alignment (mapconcat (lambda (x) (if x "r" "l")) | |
4242 | org-table-last-alignment "")) | |
4243 | (params2 | |
4244 | (list | |
4245 | :tstart (concat "\\begin{tabular}{" alignment "}") | |
4246 | :tend "\\end{tabular}" | |
4247 | :lstart "" :lend " \\\\" :sep " & " | |
4248 | :efmt "%s\\,(%s)" :hline "\\hline"))) | |
4249 | (orgtbl-to-generic table (org-combine-plists params2 params)))) | |
4250 | ||
4251 | (defun orgtbl-to-html (table params) | |
86fbb8ca | 4252 | "Convert the orgtbl-mode TABLE to HTML. |
20908596 CD |
4253 | TABLE is a list, each entry either the symbol `hline' for a horizontal |
4254 | separator line, or a list of fields for that line. | |
4255 | PARAMS is a property list of parameters that can influence the conversion. | |
4256 | Currently this function recognizes the following parameters: | |
4257 | ||
4258 | :splice When set to t, return only table body lines, don't wrap | |
4259 | them into a <table> environment. Default is nil. | |
4260 | ||
4261 | The general parameters :skip and :skipcols have already been applied when | |
4262 | this function is called. The function does *not* use `orgtbl-to-generic', | |
4263 | so you cannot specify parameters for it." | |
4264 | (let* ((splicep (plist-get params :splice)) | |
71d35b24 | 4265 | (html-table-tag org-export-html-table-tag) |
20908596 CD |
4266 | html) |
4267 | ;; Just call the formatter we already have | |
4268 | ;; We need to make text lines for it, so put the fields back together. | |
4269 | (setq html (org-format-org-table-html | |
4270 | (mapcar | |
4271 | (lambda (x) | |
4272 | (if (eq x 'hline) | |
4273 | "|----+----|" | |
afe98dfa | 4274 | (concat "| " (mapconcat 'org-html-expand x " | ") " |"))) |
20908596 CD |
4275 | table) |
4276 | splicep)) | |
4277 | (if (string-match "\n+\\'" html) | |
4278 | (setq html (replace-match "" t t html))) | |
4279 | html)) | |
4280 | ||
4281 | (defun orgtbl-to-texinfo (table params) | |
4282 | "Convert the orgtbl-mode TABLE to TeXInfo. | |
4283 | TABLE is a list, each entry either the symbol `hline' for a horizontal | |
4284 | separator line, or a list of fields for that line. | |
4285 | PARAMS is a property list of parameters that can influence the conversion. | |
4286 | Supports all parameters from `orgtbl-to-generic'. Most important for | |
4287 | TeXInfo are: | |
4288 | ||
4289 | :splice nil/t When set to t, return only table body lines, don't wrap | |
4290 | them into a multitable environment. Default is nil. | |
4291 | ||
4292 | :fmt fmt A format to be used to wrap the field, should contain | |
4293 | %s for the original field value. For example, to wrap | |
4294 | everything in @kbd{}, you could use :fmt \"@kbd{%s}\". | |
4295 | This may also be a property list with column numbers and | |
4296 | formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\"). | |
4297 | Each format also may be a function that formats its one | |
4298 | argument. | |
4299 | ||
4300 | :cf \"f1 f2..\" The column fractions for the table. By default these | |
4301 | are computed automatically from the width of the columns | |
4302 | under org-mode. | |
4303 | ||
4304 | The general parameters :skip and :skipcols have already been applied when | |
4305 | this function is called." | |
4306 | (let* ((total (float (apply '+ org-table-last-column-widths))) | |
4307 | (colfrac (or (plist-get params :cf) | |
4308 | (mapconcat | |
4309 | (lambda (x) (format "%.3f" (/ (float x) total))) | |
4310 | org-table-last-column-widths " "))) | |
4311 | (params2 | |
4312 | (list | |
4313 | :tstart (concat "@multitable @columnfractions " colfrac) | |
4314 | :tend "@end multitable" | |
4315 | :lstart "@item " :lend "" :sep " @tab " | |
4316 | :hlstart "@headitem "))) | |
4317 | (orgtbl-to-generic table (org-combine-plists params2 params)))) | |
4318 | ||
b349f79f CD |
4319 | (defun orgtbl-to-orgtbl (table params) |
4320 | "Convert the orgtbl-mode TABLE into another orgtbl-mode table. | |
4321 | Useful when slicing one table into many. The :hline, :sep, | |
4322 | :lstart, and :lend provide orgtbl framing. The default nil :tstart | |
4323 | and :tend suppress strings without splicing; they can be set to | |
4324 | provide ORGTBL directives for the generated table." | |
4325 | (let* ((params2 | |
4326 | (list | |
86fbb8ca | 4327 | :remove-newlines t |
33306645 CD |
4328 | :tstart nil :tend nil |
4329 | :hline "|---" | |
4330 | :sep " | " | |
4331 | :lstart "| " | |
4332 | :lend " |")) | |
b349f79f CD |
4333 | (params (org-combine-plists params2 params))) |
4334 | (orgtbl-to-generic table params))) | |
4335 | ||
0bd48b37 CD |
4336 | (defun org-table-get-remote-range (name-or-id form) |
4337 | "Get a field value or a list of values in a range from table at ID. | |
4338 | ||
4339 | NAME-OR-ID may be the name of a table in the current file as set by | |
4340 | a \"#+TBLNAME:\" directive. The first table following this line | |
4341 | will then be used. Alternatively, it may be an ID referring to | |
4342 | any entry, also in a different file. In this case, the first table | |
8bfe682a | 4343 | in that entry will be referenced. |
0bd48b37 CD |
4344 | FORM is a field or range descriptor like \"@2$3\" or or \"B3\" or |
4345 | \"@I$2..@II$2\". All the references must be absolute, not relative. | |
4346 | ||
4347 | The return value is either a single string for a single field, or a | |
4348 | list of the fields in the rectangle ." | |
4349 | (save-match-data | |
4350 | (let ((id-loc nil) | |
4351 | org-table-column-names org-table-column-name-regexp | |
4352 | org-table-local-parameters org-table-named-field-locations | |
4353 | org-table-current-line-types org-table-current-begin-line | |
4354 | org-table-current-begin-pos org-table-dlines | |
4355 | org-table-hlines org-table-last-alignment | |
4356 | org-table-last-column-widths org-table-last-alignment | |
4357 | org-table-last-column-widths tbeg | |
4358 | buffer loc) | |
c8d0cf5c | 4359 | (setq form (org-table-convert-refs-to-rc form)) |
0bd48b37 CD |
4360 | (save-excursion |
4361 | (save-restriction | |
4362 | (widen) | |
4363 | (save-excursion | |
4364 | (goto-char (point-min)) | |
4365 | (if (re-search-forward | |
8d642074 | 4366 | (concat "^[ \t]*#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$") |
0bd48b37 CD |
4367 | nil t) |
4368 | (setq buffer (current-buffer) loc (match-beginning 0)) | |
c8d0cf5c CD |
4369 | (setq id-loc (org-id-find name-or-id 'marker)) |
4370 | (unless (and id-loc (markerp id-loc)) | |
4371 | (error "Can't find remote table \"%s\"" name-or-id)) | |
4372 | (setq buffer (marker-buffer id-loc) | |
0bd48b37 CD |
4373 | loc (marker-position id-loc)) |
4374 | (move-marker id-loc nil))) | |
86fbb8ca CD |
4375 | (with-current-buffer buffer |
4376 | (save-excursion | |
4377 | (save-restriction | |
4378 | (widen) | |
4379 | (goto-char loc) | |
4380 | (forward-char 1) | |
4381 | (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t) | |
4382 | (not (match-beginning 1))) | |
4383 | (error "Cannot find a table at NAME or ID %s" name-or-id)) | |
4384 | (setq tbeg (point-at-bol)) | |
4385 | (org-table-get-specials) | |
4386 | (setq form (org-table-formula-substitute-names form)) | |
4387 | (if (and (string-match org-table-range-regexp form) | |
4388 | (> (length (match-string 0 form)) 1)) | |
4389 | (save-match-data | |
4390 | (org-table-get-range (match-string 0 form) tbeg 1)) | |
4391 | form))))))))) | |
0bd48b37 | 4392 | |
20908596 CD |
4393 | (provide 'org-table) |
4394 | ||
b349f79f | 4395 | |
20908596 | 4396 | ;;; org-table.el ends here |