Spelling fixes.
[bpt/emacs.git] / lisp / textmodes / table.el
CommitLineData
238240c9
RS
1;;; table.el --- create and edit WYSIWYG text based embedded tables
2
73b0cd50 3;; Copyright (C) 2000-2011 Free Software Foundation, Inc.
238240c9
RS
4
5;; Keywords: wp, convenience
6;; Author: Takaaki Ota <Takaaki.Ota@am.sony.com>
7;; Created: Sat Jul 08 2000 13:28:45 (PST)
238240c9
RS
8
9;; This file is part of GNU Emacs.
10
1fecc8fe 11;; GNU Emacs is free software: you can redistribute it and/or modify
238240c9 12;; it under the terms of the GNU General Public License as published by
1fecc8fe
GM
13;; the Free Software Foundation, either version 3 of the License, or
14;; (at your option) any later version.
238240c9
RS
15
16;; GNU Emacs is distributed in the hope that it will be useful,
17;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19;; GNU General Public License for more details.
20
21;; You should have received a copy of the GNU General Public License
1fecc8fe 22;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
238240c9
RS
23
24;;; Commentary:
25
26;; -------------
27;; Introduction:
28;; -------------
29;;
30;; This package provides text based table creation and editing
31;; feature. With this package Emacs is capable of editing tables that
32;; are embedded inside a text document, the feature similar to the
33;; ones seen in modern WYSIWYG word processors. A table is a
34;; rectangular text area consisting from a surrounding frame and
35;; content inside the frame. The content is usually subdivided into
36;; multiple rectangular cells, see the actual tables used below in
37;; this document. Once a table is recognized, editing operation
38;; inside a table cell is confined into that specific cell's
39;; rectangular area. This means that typing and deleting characters
40;; inside a cell do not affect any outside text but introduces
41;; appropriate formatting only to the cell contents. If necessary for
42;; accommodating added text in the cell, the cell automatically grows
43;; vertically and/or horizontally. The package uses no major mode nor
44;; minor mode for its implementation because the subject text is
45;; localized within a buffer. Therefore the special behaviors inside
46;; a table cells are implemented by using keymap text property
47;; instead of buffer wide mode-map.
48;;
49;;
50;; -----------
51;; Background:
52;; -----------
53;;
54;; Paul Georgief is one of my best friends. He became an Emacs
55;; convert after I recommended him trying it several years ago. Now
56;; we both are devoted disciples of Emacsism and elisp cult. One day
57;; in his Emacs exploration he asked me "Tak, what is a command to
58;; edit tables in Emacs?". This question started my journey of this
59;; table package development. May the code be with me! In the
60;; software world Emacs is probably one of the longest lifetime record
61;; holders. Amazingly there have been no direct support for WYSIWYG
62;; table editing tasks in Emacs. Many people must have experienced
63;; manipulating existing overwrite-mode and picture-mode for this task
64;; and only dreamed of having such a lisp package which supports this
65;; specific task directly. Certainly, I have been one of them. The
66;; most difficult part of dealing with table editing in Emacs probably
67;; is how to realize localized rectangular editing effect. Emacs has
68;; no rectangular narrowing mechanism. Existing rect package provides
69;; basically kill, delete and yank operations of a rectangle, which
70;; internally is a mere list of strings. A simple approach for
71;; realizing the localized virtual rectangular operation is combining
72;; rect package capability with a temporary buffer. Insertion and
73;; deletion of a character to a table cell can be trapped by a
74;; function that copies the cell rectangle to a temporary buffer then
75;; apply the insertion/deletion to the temporary contents. Then it
76;; formats the contents by filling the paragraphs in order to fit it
77;; into the original rectangular area and finally copy it back to the
78;; original buffer. This simplistic approach has to bear with
79;; significant performance hit. As cell grows larger the copying
80;; rectangle back and forth between the original buffer and the
81;; temporary buffer becomes expensive and unbearably slow. It was
82;; completely impractical and an obvious failure. An idea has been
83;; borrowed from the original Emacs design to overcome this
84;; shortcoming. When the terminal screen update was slow and
85;; expensive Emacs employed a clever algorithm to reduce actual screen
86;; update by removing redundant redrawing operations. Also the actual
87;; redrawing was done only when there was enough idling time. This
88;; technique significantly improved the previously mentioned
89;; undesirable situation. Now the original buffer's rectangle is
90;; copied into a cache buffer only once. Any cell editing operation
91;; is done only to the cache contents. When there is enough idling
92;; time the original buffer's rectangle is updated with the current
93;; cache contents. This delayed operation is implemented by using
94;; Emacs's timer function. To reduce the visual awkwardness
95;; introduced by the delayed effect the cursor location is updated in
96;; real-time as a user types while the cell contents remains the same
97;; until the next idling time. A key to the success of this approach
98;; is how to maintain cache coherency. As a user moves point in and
99;; out of a cell the table buffer contents and the cache buffer
100;; contents must be synchronized without a mistake. By observing user
101;; action carefully this is possible however not easy. Once this
102;; mechanism is firmly implemented the rest of table features grew in
103;; relatively painless progression. Those users who are familiar with
104;; Emacs internals appreciate this table package more. Because it
105;; demonstrates how extensible Emacs is by showing something that
106;; appears like a magic. It lets you re-discover the potential of
107;; Emacs.
108;;
109;;
110;; -------------
111;; Entry Points:
112;; -------------
113;;
114;; If this is the first time for you to try this package, go ahead and
115;; load the package by M-x `load-file' RET. Specify the package file
116;; name "table.el". Then switch to a new test buffer and issue the
117;; command M-x `table-insert' RET. It'll ask you number of columns,
118;; number of rows, cell width and cell height. Give some small
119;; numbers for each of them. Play with the resulted table for a
120;; while. If you have menu system find the item "Table" under "Tools"
121;; and "Table" in the menu bar when the point is in a table cell.
122;; Some of them are pretty intuitive and you can easily guess what
123;; they do. M-x `describe-function' and get the documentation of
124;; `table-insert'. The document includes a short tutorial. When you
125;; are tired of guessing how it works come back to this document
126;; again.
127;;
128;; To use the package regularly place this file in the site library
129;; directory and add the next expression in your .emacs file. Make
130;; sure that directory is included in the `load-path'.
131;;
132;; (require 'table)
133;;
134;; Have the next expression also, if you want always be ready to edit
135;; tables inside text files. This mechanism is analogous to
136;; fontification in a sense that tables are recognized at editing time
137;; without having table information saved along with the text itself.
138;;
139;; (add-hook 'text-mode-hook 'table-recognize)
140;;
141;; Following is a table of entry points and brief description of each
142;; of them. The tables below are of course generated and edited by
143;; using this package. Not all the commands are bound to keys. Many
144;; of them must be invoked by "M-x" (`execute-extended-command')
145;; command. Refer to the section "Keymap" below for the commands
146;; available from keys.
147;;
148;; +------------------------------------------------------------------+
149;; | User Visible Entry Points |
150;; +-------------------------------+----------------------------------+
151;; | Function | Description |
152;; +-------------------------------+----------------------------------+
153;; |`table-insert' |Insert a table consisting of grid |
154;; | |of cells by specifying the number |
155;; | |of COLUMNS, number of ROWS, cell |
156;; | |WIDTH and cell HEIGHT. |
157;; +-------------------------------+----------------------------------+
158;; |`table-insert-row' |Insert row(s) of cells before the |
159;; | |current row that matches the |
160;; | |current row structure. |
161;; +-------------------------------+----------------------------------+
162;; |`table-insert-column' |Insert column(s) of cells before |
163;; | |the current column that matches |
164;; | |the current column structure. |
165;; +-------------------------------+----------------------------------+
166;; |`table-delete-row' |Delete row(s) of cells. The row |
167;; | |must consist from cells of the |
168;; | |same height. |
169;; +-------------------------------+----------------------------------+
170;; |`table-delete-column' |Delete column(s) of cells. The |
171;; | |column must consist from cells of |
172;; | |the same width. |
173;; +-------------------------------+----------------------------------+
174;; |`table-recognize' |Recognize all tables in the |
175;; |`table-unrecognize' |current buffer and |
e9a452d9 176;; | |activate/deactivate them. |
238240c9
RS
177;; +-------------------------------+----------------------------------+
178;; |`table-recognize-region' |Recognize all the cells in a |
e9a452d9 179;; |`table-unrecognize-region' |region and activate/deactivate |
238240c9
RS
180;; | |them. |
181;; +-------------------------------+----------------------------------+
182;; |`table-recognize-table' |Recognize all the cells in a |
183;; |`table-unrecognize-table' |single table and |
e9a452d9 184;; | |activate/deactivate them. |
238240c9
RS
185;; +-------------------------------+----------------------------------+
186;; |`table-recognize-cell' |Recognize a cell. Find a cell |
187;; |`table-unrecognize-cell' |which contains the current point |
e9a452d9 188;; | |and activate/deactivate that cell.|
238240c9
RS
189;; +-------------------------------+----------------------------------+
190;; |`table-forward-cell' |Move point to the next Nth cell in|
191;; | |a table. |
192;; +-------------------------------+----------------------------------+
193;; |`table-backward-cell' |Move point to the previous Nth |
194;; | |cell in a table. |
195;; +-------------------------------+----------------------------------+
196;; |`table-span-cell' |Span the current cell toward the |
197;; | |specified direction and merge it |
198;; | |with the adjacent cell. The |
199;; | |direction is right, left, above or|
200;; | |below. |
201;; +-------------------------------+----------------------------------+
202;; |`table-split-cell-vertically' |Split the current cell vertically |
203;; | |and create a cell above and a cell|
204;; | |below the point location. |
205;; +-------------------------------+----------------------------------+
206;; |`table-split-cell-horizontally'|Split the current cell |
207;; | |horizontally and create a cell on |
208;; | |the left and a cell on the right |
209;; | |of the point location. |
210;; +-------------------------------+----------------------------------+
211;; |`table-split-cell' |Split the current cell vertically |
212;; | |or horizontally. This is a |
213;; | |wrapper command to the other two |
214;; | |orientation specific commands. |
215;; +-------------------------------+----------------------------------+
216;; |`table-heighten-cell' |Heighten the current cell. |
217;; +-------------------------------+----------------------------------+
218;; |`table-shorten-cell' |Shorten the current cell. |
219;; +-------------------------------+----------------------------------+
220;; |`table-widen-cell' |Widen the current cell. |
221;; +-------------------------------+----------------------------------+
222;; |`table-narrow-cell' |Narrow the current cell. |
223;; +-------------------------------+----------------------------------+
224;; |`table-fixed-width-mode' |Toggle fixed width mode. In the |
225;; | |fixed width mode, typing inside a |
226;; | |cell never changes the cell width,|
227;; | |while in the normal mode the cell |
228;; | |width expands automatically in |
229;; | |order to prevent a word being |
230;; | |folded into multiple lines. Fixed|
231;; | |width mode reverses video or |
232;; | |underline the cell contents for |
233;; | |its indication. |
234;; +-------------------------------+----------------------------------+
235;; |`table-query-dimension' |Compute and report the current |
236;; | |cell dimension, current table |
237;; | |dimension and the number of |
238;; | |columns and rows in the table. |
239;; +-------------------------------+----------------------------------+
240;; |`table-generate-source' |Generate the source of the current|
241;; | |table in the specified language |
242;; | |and insert it into a specified |
243;; | |buffer. |
244;; +-------------------------------+----------------------------------+
245;; |`table-insert-sequence' |Travel cells forward while |
246;; | |inserting a specified sequence |
247;; | |string into each cell. |
248;; +-------------------------------+----------------------------------+
249;; |`table-capture' |Convert plain text into a table by|
250;; | |capturing the text in the region. |
251;; +-------------------------------+----------------------------------+
252;; |`table-release' |Convert a table into plain text by|
253;; | |removing the frame from a table. |
254;; +-------------------------------+----------------------------------+
255;; |`table-justify' |Justify the contents of cell(s). |
256;; +-------------------------------+----------------------------------+
257;;
258;;
259;; *Note*
260;;
261;; You may find that some of commonly expected table commands are
262;; missing such as copying a row/column and yanking it. Those
263;; functions can be obtained through existing Emacs text editing
264;; commands. Rows are easily manipulated with region commands and
265;; columns can be copied and pasted through rectangle commands. After
266;; all a table is still a part of text in the buffer. Only the
267;; special behaviors exist inside each cell through text properties.
268;;
269;; `table-generate-html' which appeared in earlier releases is
270;; deprecated in favor of `table-generate-source'. Now HTML is
271;; treated as one of the languages used for describing the table's
272;; logical structure.
273;;
274;;
275;; -------
276;; Keymap:
277;; -------
278;;
279;; Although this package does not use a mode it does use its own
280;; keymap inside a table cell by way of keymap text property. Some of
281;; the standard basic editing commands bound to certain keys are
282;; replaced with the table specific version of corresponding commands.
283;; This replacement combination is listed in the constant alist
284;; `table-command-remap-alist' declared below. This alist is
285;; not meant to be user configurable but mentioned here for your
286;; better understanding of using this package. In addition, table
287;; cells have some table specific bindings for cell navigation and
288;; cell reformation. You can find these additional bindings in the
289;; constant `table-cell-bindings'. Those key bound functions are
290;; considered as internal functions instead of normal commands,
291;; therefore they have special prefix, *table-- instead of table-, for
292;; symbols. The purpose of this is to make it easier for a user to
293;; use command name completion. There is a "normal hooks" variable
294;; `table-cell-map-hook' prepared for users to override the default
295;; table cell bindings. Following is the table of predefined default
296;; key bound commands inside a table cell. Remember these bindings
297;; exist only inside a table cell. When your terminal is a tty, the
298;; control modifier may not be available or applicable for those
299;; special characters. In this case use "C-cC-c", which is
300;; customizable via `table-command-prefix', as the prefix key
301;; sequence. This should preceding the following special character
302;; without the control modifier. For example, use "C-cC-c|" instead
303;; of "C-|".
304;;
305;; +------------------------------------------------------------------+
306;; | Default Bindings in a Table Cell |
307;; +-------+----------------------------------------------------------+
308;; | Key | Function |
309;; +-------+----------------------------------------------------------+
310;; | TAB |Move point forward to the beginning of the next cell. |
311;; +-------+----------------------------------------------------------+
312;; | "C->" |Widen the current cell. |
313;; +-------+----------------------------------------------------------+
314;; | "C-<" |Narrow the current cell. |
315;; +-------+----------------------------------------------------------+
316;; | "C-}" |Heighten the current cell. |
317;; +-------+----------------------------------------------------------+
318;; | "C-{" |Shorten the current cell. |
319;; +-------+----------------------------------------------------------+
320;; | "C--" |Split current cell vertically. (one above and one below) |
321;; +-------+----------------------------------------------------------+
322;; | "C-|" |Split current cell horizontally. (one left and one right) |
323;; +-------+----------------------------------------------------------+
324;; | "C-*" |Span current cell into adjacent one. |
325;; +-------+----------------------------------------------------------+
326;; | "C-+" |Insert row(s)/column(s). |
327;; +-------+----------------------------------------------------------+
328;; | "C-!" |Toggle between normal mode and fixed width mode. |
329;; +-------+----------------------------------------------------------+
330;; | "C-#" |Report cell and table dimension. |
331;; +-------+----------------------------------------------------------+
332;; | "C-^" |Generate the source in a language from the current table. |
333;; +-------+----------------------------------------------------------+
334;; | "C-:" |Justify the contents of cell(s). |
335;; +-------+----------------------------------------------------------+
336;;
337;; *Note*
338;;
339;; When using `table-cell-map-hook' do not use `local-set-key'.
340;;
341;; (add-hook 'table-cell-map-hook
342;; (function (lambda ()
343;; (local-set-key [<key sequence>] '<function>))))
344;;
345;; Above code is well known ~/.emacs idiom for customizing a mode
346;; specific keymap however it does not work for this package. This is
347;; because there is no table mode in effect. This package does not
348;; use a local map therefor you must modify `table-cell-map'
349;; explicitly. The correct way of achieving above task is:
350;;
351;; (add-hook 'table-cell-map-hook
352;; (function (lambda ()
353;; (define-key table-cell-map [<key sequence>] '<function>))))
354;;
355;; -----
356;; Menu:
357;; -----
358;;
359;; If a menu system is available a group of table specific menu items,
360;; "Table" under "Tools" section of the menu bar, is globally added
361;; after this package is loaded. The commands in this group are
362;; limited to the ones that are related to creation and initialization
363;; of tables, such as to insert a table, to insert rows and columns,
364;; or recognize and unrecognize tables. Once tables are created and
365;; point is placed inside of a table cell a table specific menu item
366;; "Table" appears directly on the menu bar. The commands in this
367;; menu give full control on table manipulation that include cell
368;; navigation, insertion, splitting, spanning, shrinking, expansion
369;; and unrecognizing. In addition to above two types of menu there is
370;; a pop-up menu available within a table cell. The content of pop-up
371;; menu is identical to the full table menu. [mouse-3] is the default
372;; button, defined in `table-cell-bindings', to bring up the pop-up
373;; menu. It can be reconfigured via `table-cell-map-hook'. The
374;; benefit of a pop-up menu is that it combines selection of the
375;; location (which cell, where in the cell) and selection of the
376;; desired operation into a single clicking action.
377;;
378;;
379;; -------------------------------
380;; Definition of tables and cells:
381;; -------------------------------
382;;
383;; There is no artificial-intelligence magic in this package. The
384;; definition of a table and the cells inside the table is reasonably
385;; limited in order to achieve acceptable performance in the
386;; interactive operation under Emacs lisp implementation. A valid
387;; table is a rectangular text area completely filled with valid
388;; cells. A valid cell is a rectangle text area, which four borders
389;; consist of valid border characters. Cells can not be nested one to
390;; another or overlapped to each other except sharing the border
391;; lines. A valid character of a cell's vertical border is either
392;; table-cell-vertical-char `|' or table-cell-intersection-char `+'.
393;; A valid character of a cell's horizontal border is either
1b2679cf
SM
394;; one of table-cell-horizontal-chars (`-' or `=')
395;; or table-cell-intersection-char `+'.
238240c9
RS
396;; A valid character of the four corners of a cell must be
397;; table-cell-intersection-char `+'. A cell must contain at least one
398;; character space inside. There is no restriction about the contents
399;; of a table cell, however it is advised if possible to avoid using
400;; any of the border characters inside a table cell. Normally a few
401;; boarder characters inside a table cell are harmless. But it is
402;; possible that they accidentally align up to emulate a bogus cell
403;; corner on which software relies on for cell recognition. When this
404;; happens the software may be fooled by it and fail to determine
405;; correct cell dimension.
406;;
407;; Following are the examples of valid tables.
408;;
409;; +--+----+---+ +-+ +--+-----+
410;; | | | | | | | | |
411;; +--+----+---+ +-+ | +--+--+
412;; | | | | | | | |
413;; +--+----+---+ +--+--+ |
414;; | | |
415;; +-----+--+
416;;
417;; The next five tables are the examples of invalid tables. (From
418;; left to right, 1. nested cells 2. overlapped cells and a
419;; non-rectangle cell 3. non-rectangle table 4. zero width/height
420;; cells 5. zero sized cell)
421;;
422;; +-----+ +-----+ +--+ +-++--+ ++
423;; | | | | | | | || | ++
424;; | +-+ | | | | | | || |
425;; | | | | +--+ | +--+--+ +-++--+
426;; | +-+ | | | | | | | +-++--+
427;; | | | | | | | | | || |
428;; +-----+ +--+--+ +--+--+ +-++--+
429;;
430;; Although the program may recognizes some of these invalid tables,
431;; results from the subsequent editing operations inside those cells
432;; are not predictable and will most likely start destroying the table
433;; structures.
434;;
435;; It is strongly recommended to have at least one blank line above
436;; and below a table. For a table to coexist peacefully with
437;; surrounding environment table needs to be separated from unrelated
438;; text. This is necessary for the left table to grow or shrink
439;; horizontally without breaking the right table in the following
440;; example.
441;;
442;; +-----+-----+-----+
443;; +-----+-----+ | | | |
444;; | | | +-----+-----+-----+
445;; +-----+-----+ | | | |
446;; +-----+-----+-----+
447;;
448;;
449;; -------------------------
450;; Cell contents formatting:
451;; -------------------------
452;;
453;; The cell contents are formatted by filling a paragraph immediately
454;; after characters are inserted into or deleted from a cell. Because
455;; of this, cell contents always remain fit inside a cell neatly. One
456;; drawback of this is that users do not have full control over
457;; spacing between words and line breaking. Only one space can be
458;; entered between words and up to two spaces between sentences. For
459;; a newline to be effective the new line must form a beginning of
460;; paragraph, otherwise it'll automatically be merged with the
461;; previous line in a same paragraph. To form a new paragraph the
462;; line must start with some space characters or immediately follow a
463;; blank line. Here is a typical example of how to list items within
464;; a cell. Without a space at the beginning of each line the items
465;; can not stand on their own.
466;;
467;; +---------------------------------+
468;; |Each one of the following three |
469;; |items starts with a space |
470;; |character thus forms a paragraph |
471;; |of its own. Limitations in cell |
472;; |contents formatting are: |
473;; | |
474;; | 1. Only one space between words.|
475;; | 2. Up to two spaces between |
476;; |sentences. |
477;; | 3. A paragraph must start with |
478;; |spaces or follow a blank line. |
479;; | |
480;; |This paragraph stays away from |
481;; |the item 3 because there is a |
482;; |blank line between them. |
483;; +---------------------------------+
484;;
485;; In the normal operation table cell width grows automatically when
486;; certain word has to be folded into the next line if the width had
487;; not been increased. This normal operation is useful and
488;; appropriate for most of the time, however, it is sometimes useful
489;; or necessary to fix the width of table and width of table cells.
490;; For this purpose the package provides fixed width mode. You can
491;; toggle between fixed width mode and normal mode by "C-!".
492;;
493;; Here is a simple example of the fixed width mode. Suppose we have
494;; a table like this one.
495;;
496;; +-----+
497;; | |
498;; +-----+
499;;
500;; In normal mode if you type a word "antidisestablishmentarianism" it
501;; grows the cell horizontally like this.
502;;
503;; +----------------------------+
504;; |antidisestablishmentarianism|
505;; +----------------------------+
506;;
507;; In the fixed width mode the same action produces the following
508;; result. The folded locations are indicated by a continuation
509;; character (`\' is the default). The continuation character is
510;; treated specially so it is recommended to choose a character that
511;; does not appear elsewhere in table cells. This character is
512;; configurable via customization and is kept in the variable
513;; `table-word-continuation-char'. The continuation character is
514;; treated specially only in the fixed width mode and has no special
515;; meaning in the normal mode however.
516;;
517;; +-----+
518;; |anti\|
519;; |dise\|
520;; |stab\|
521;; |lish\|
522;; |ment\|
523;; |aria\|
524;; |nism |
525;; +-----+
526;;
527;;
528;; -------------------
529;; Cell Justification:
530;; -------------------
531;;
532;; By default the cell contents are filled with left justification and
533;; no vertical justification. A paragraph can be justified
534;; individually but only horizontally. Paragraph justification is for
535;; appearance only and does not change any structural information
536;; while cell justification affects table's structural information.
537;; For cell justification a user can select horizontal justification
538;; and vertical justification independently. Horizontal justification
539;; must be one of the three 'left, 'center or 'right. Vertical
540;; justification can be 'top, 'middle, 'bottom or 'none. When a cell
541;; is justified, that information is recorded as a part of text
542;; property therefore the information is persistent as long as the
543;; cell remains within the Emacs world. Even copying tables by region
544;; and rectangle manipulation commands preserve this information.
545;; However, once the table text is saved as a file and the buffer is
546;; killed the justification information vanishes permanently. To
547;; alleviate this shortcoming without forcing users to save and
548;; maintain a separate attribute file, the table code detects
549;; justification of each cell when recognizing a table. This
550;; detection is done by guessing the justification by looking at the
551;; appearance of the cell contents. Since it is a guessing work it
552;; does not guarantee the perfectness but it is designed to be
553;; practically good enough. The guessing algorithm is implemented in
554;; the function `table--detect-cell-alignment'. If you have better
555;; algorithm or idea any suggestion is welcome.
556;;
557;;
558;; -----
559;; Todo: (in the order of priority, some are just possibility)
560;; -----
561;;
562;; Fix compatibilities with other input method than quail
563;; Resolve conflict with flyspell
564;; Use mouse for resizing cells
565;; A mechanism to link cells internally
566;; Consider the use of variable width font under Emacs 21
567;; Consider the use of `:box' face attribute under Emacs 21
568;; Consider the use of `modification-hooks' text property instead of
569;; rebinding the keymap
570;; Maybe provide complete XEmacs support in the future however the
571;; "extent" is the single largest obstacle lying ahead, read the
572;; document in Emacs info.
573;; (eval '(progn (require 'info) (Info-find-node "elisp" "Not Intervals")))
574;;
575;;
576;; ---------------
577;; Acknowledgment:
578;; ---------------
579;;
580;; Table would not have been possible without the help and
581;; encouragement of the following spirited contributors.
582;;
583;; Paul Georgief <georgief@igpp.ucsd.edu> has been the best tester
584;; of the code as well as the constructive criticizer.
585;;
586;; Gerd Moellmann <gerd@gnu.org> gave me useful suggestions from Emacs
587;; 21 point of view.
588;;
589;; Richard Stallman <rms@gnu.org> showed the initial interest in this
590;; attempt of implementing the table feature to Emacs. This greatly
591;; motivated me to follow through to its completion.
592;;
593;; Kenichi Handa <handa@etl.go.jp> kindly guided me through to
594;; overcome many technical issues while I was struggling with quail
595;; related internationalization problems.
596;;
597;; Christoph Conrad <christoph.conrad@gmx.de> suggested making symbol
598;; names consistent as well as fixing several bugs.
599;;
600;; Paul Lew <paullew@cisco.com> suggested implementing fixed width
601;; mode as well as multi column width (row height) input interface.
602;;
603;; Michael Smith <smith@xml-doc.org> a well-informed DocBook user
604;; asked for CALS table source generation and helped me following
605;; through the work by offering valuable suggestions and testing out
606;; the code. Jorge Godoy <godoy@conectiva.com> has also suggested
607;; supporting for DocBook tables.
608;;
609;; And many other individuals who reported bugs and suggestions.
610
611;;; Code:
612
613\f
fc53ebf6 614(require 'regexp-opt)
238240c9
RS
615
616;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
617;;;
618;;; Compatibility:
619;;;
620
621;; hush up the byte-compiler
1042fc7f
SM
622(defvar quail-translating)
623(defvar quail-converting)
624(defvar flyspell-mode)
625(defvar real-last-command)
626(defvar delete-selection-mode)
627;; This is evil!!
628;; (eval-when-compile
629;; (unless (fboundp 'set-face-property)
630;; (defun set-face-property (face prop value)))
631;; (unless (fboundp 'unibyte-char-to-multibyte)
632;; (defun unibyte-char-to-multibyte (char)))
633;; (defun table--point-in-cell-p (&optional location)))
238240c9
RS
634
635;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
636;;;
637;;; Customization:
638;;;
639
640(defgroup table nil
eba5b4dd 641 "Text based table manipulation utilities."
238240c9
RS
642 :tag "Table"
643 :prefix "table-"
238240c9 644 :group 'wp
bf247b6e 645 :version "22.1")
238240c9 646
23179a73 647(defgroup table-hooks nil
ec85195e 648 "Hooks for table manipulation utilities."
23179a73
MR
649 :group 'table)
650
238240c9 651(defcustom table-time-before-update 0.2
1fc7dabf 652 "Time in seconds before updating the cell contents after typing.
238240c9
RS
653Updating the cell contents on the screen takes place only after this
654specified amount of time has passed after the last modification to the
655cell contents. When the contents of a table cell changes repetitively
656and frequently the updating the cell contents on the screen is
657deferred until at least this specified amount of quiet time passes. A
658smaller number wastes more computation resource by unnecessarily
659frequent screen update. A large number presents noticeable and
660annoying delay before the typed result start appearing on the screen."
661 :tag "Time Before Cell Update"
662 :type 'number
663 :group 'table)
664
665(defcustom table-time-before-reformat 0.2
1fc7dabf 666 "Time in seconds before reformatting the table.
238240c9
RS
667This many seconds must pass in addition to `table-time-before-update'
668before the table is updated with newly widened width or heightened
669height."
670 :tag "Time Before Cell Reformat"
671 :type 'number
672 :group 'table)
673
674(defcustom table-command-prefix [(control c) (control c)]
1fc7dabf 675 "Key sequence to be used as prefix for table command key bindings."
790f437c 676 :type '(vector (repeat :inline t sexp))
238240c9
RS
677 :tag "Table Command Prefix"
678 :group 'table)
679
b4c925d8 680(defface table-cell
ea81d57e
DN
681 '((((min-colors 88) (class color))
682 (:foreground "gray90" :background "blue1"))
683 (((class color))
238240c9
RS
684 (:foreground "gray90" :background "blue"))
685 (t (:bold t)))
1fc7dabf 686 "Face used for table cell contents."
238240c9
RS
687 :tag "Cell Face"
688 :group 'table)
689
e99add21 690(defcustom table-cell-horizontal-chars "-="
1fc7dabf 691 "Characters that may be used for table cell's horizontal border line."
e99add21
JB
692 :tag "Cell Horizontal Boundary Characters"
693 :type 'string
238240c9
RS
694 :group 'table)
695
696(defcustom table-cell-vertical-char ?\|
1fc7dabf 697 "Character that forms table cell's vertical border line."
238240c9
RS
698 :tag "Cell Vertical Boundary Character"
699 :type 'character
700 :group 'table)
701
702(defcustom table-cell-intersection-char ?\+
1fc7dabf 703 "Character that forms table cell's corner."
238240c9
RS
704 :tag "Cell Intersection Character"
705 :type 'character
706 :group 'table)
707
708(defcustom table-word-continuation-char ?\\
1fc7dabf 709 "Character that indicates word continuation into the next line.
238240c9
RS
710This character has a special meaning only in the fixed width mode,
711that is when `table-fixed-width-mode' is non-nil . In the fixed width
712mode this character indicates that the location is continuing into the
713next line. Be careful about the choice of this character. It is
714treated substantially different manner than ordinary characters. Try
715select a character that is unlikely to appear in your document."
716 :tag "Cell Word Continuation Character"
717 :type 'character
718 :group 'table)
719
720(defun table-set-table-fixed-width-mode (variable value)
721 (if (fboundp variable)
722 (funcall variable (if value 1 -1))))
723
724(defun table-initialize-table-fixed-width-mode (variable value)
725 (set variable value))
726
727(defcustom table-fixed-width-mode nil
1fc7dabf 728 "Cell width is fixed when this is non-nil.
238240c9
RS
729Normally it should be nil for allowing automatic cell width expansion
730that widens a cell when it is necessary. When non-nil, typing in a
731cell does not automatically expand the cell width. A word that is too
732long to fit in a cell is chopped into multiple lines. The chopped
733location is indicated by `table-word-continuation-char'. This
734variable's value can be toggled by \\[table-fixed-width-mode] at
735run-time."
736 :tag "Fix Cell Width"
737 :type 'boolean
738 :initialize 'table-initialize-table-fixed-width-mode
739 :set 'table-set-table-fixed-width-mode
740 :group 'table)
741
742(defcustom table-detect-cell-alignment t
1fc7dabf 743 "Detect cell contents alignment automatically.
238240c9
RS
744When non-nil cell alignment is automatically determined by the
745appearance of the current cell contents when recognizing tables as a
746whole. This applies to `table-recognize', `table-recognize-region'
747and `table-recognize-table' but not to `table-recognize-cell'."
748 :tag "Detect Cell Alignment"
749 :type 'boolean
750 :group 'table)
751
752(defcustom table-dest-buffer-name "table"
1fc7dabf 753 "Default buffer name (without a suffix) for source generation."
238240c9
RS
754 :tag "Source Buffer Name"
755 :type 'string
756 :group 'table)
757
758(defcustom table-html-delegate-spacing-to-user-agent nil
1fc7dabf 759 "Non-nil delegates cell contents spacing entirely to user agent.
238240c9
RS
760Otherwise, when nil, it preserves the original spacing and line breaks."
761 :tag "HTML delegate spacing"
762 :type 'boolean
763 :group 'table)
764
765(defcustom table-html-th-rows 0
1fc7dabf 766 "Number of top rows to become header cells automatically in HTML generation."
238240c9
RS
767 :tag "HTML Header Rows"
768 :type 'integer
769 :group 'table)
770
771(defcustom table-html-th-columns 0
1fc7dabf 772 "Number of left columns to become header cells automatically in HTML generation."
238240c9
RS
773 :tag "HTML Header Columns"
774 :type 'integer
775 :group 'table)
776
777(defcustom table-html-table-attribute "border=\"1\""
1fc7dabf 778 "Table attribute that applies to the table in HTML generation."
238240c9
RS
779 :tag "HTML table attribute"
780 :type 'string
781 :group 'table)
782
783(defcustom table-html-cell-attribute ""
1fc7dabf 784 "Cell attribute that applies to all cells in HTML generation.
238240c9
RS
785Do not specify \"align\" and \"valign\" because they are determined by
786the cell contents dynamically."
787 :tag "HTML cell attribute"
788 :type 'string
789 :group 'table)
790
791(defcustom table-cals-thead-rows 1
1fc7dabf 792 "Number of top rows to become header rows in CALS table."
238240c9
RS
793 :tag "CALS Header Rows"
794 :type 'integer
795 :group 'table)
796
797;;;###autoload
798(defcustom table-cell-map-hook nil
1fc7dabf 799 "Normal hooks run when finishing construction of `table-cell-map'.
238240c9
RS
800User can modify `table-cell-map' by adding custom functions here."
801 :tag "Cell Keymap Hooks"
802 :type 'hook
23179a73 803 :group 'table-hooks)
238240c9
RS
804
805(defcustom table-disable-incompatibility-warning nil
1fc7dabf 806 "Disable compatibility warning notice.
238240c9
RS
807When nil user is reminded of known incompatible issues."
808 :tag "Disable Incompatibility Warning"
809 :type 'boolean
810 :group 'table)
811
812(defcustom table-abort-recognition-when-input-pending t
1fc7dabf 813 "Abort current recognition process when input pending.
238240c9
RS
814Abort current recognition process when we are not sure that no input
815is available. When non-nil lengthy recognition process is aborted
816simply by any key input."
817 :tag "Abort Recognition When Input Pending"
818 :type 'boolean
819 :group 'table)
820
821;;;###autoload
822(defcustom table-load-hook nil
1fc7dabf 823 "List of functions to be called after the table is first loaded."
238240c9
RS
824 :type 'hook
825 :group 'table-hooks)
826
827;;;###autoload
828(defcustom table-point-entered-cell-hook nil
1fc7dabf 829 "List of functions to be called after point entered a table cell."
238240c9
RS
830 :type 'hook
831 :group 'table-hooks)
832
833;;;###autoload
834(defcustom table-point-left-cell-hook nil
1fc7dabf 835 "List of functions to be called after point left a table cell."
238240c9
RS
836 :type 'hook
837 :group 'table-hooks)
838
273681e1
KS
839(defvar table-yank-handler '(nil nil t nil)
840 "Yank handler for tables.")
d6db9101 841
238240c9
RS
842(setplist 'table-disable-incompatibility-warning nil)
843
844(defvar table-disable-menu (null (and (locate-library "easymenu")
845 (require 'easymenu)
846 (fboundp 'easy-menu-add-item)))
847 "*When non-nil, use of menu by table package is disabled.
848It must be set before loading this package `table.el' for the first
849time.")
850
851\f
852;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
853;;;
854;;; Implementation:
855;;;
856
857;;; Internal variables and constants
858;;; No need of user configuration
859
860(defconst table-paragraph-start "[ \t\n\f]"
1fc7dabf 861 "Regexp for beginning of a line that starts OR separates paragraphs.")
238240c9
RS
862(defconst table-cache-buffer-name " *table cell cache*"
863 "Cell cache buffer name.")
864(defvar table-cell-info-lu-coordinate nil
865 "Zero based coordinate of the cached cell's left upper corner.")
866(defvar table-cell-info-rb-coordinate nil
867 "Zero based coordinate of the cached cell's right bottom corner.")
868(defvar table-cell-info-width nil
869 "Number of characters per cached cell width.")
870(defvar table-cell-info-height nil
871 "Number of lines per cached cell height.")
872(defvar table-cell-info-justify nil
873 "Justification information of the cached cell.")
874(defvar table-cell-info-valign nil
875 "Vertical alignment information of the cached cell.")
876(defvar table-cell-self-insert-command-count 0
877 "Counter for undo control.")
878(defvar table-cell-map nil
879 "Keymap for table cell contents.")
880(defvar table-cell-global-map-alist nil
881 "Alist of copy of global maps that are substituted in `table-cell-map'.")
882(defvar table-global-menu-map nil
883 "Menu map created via `easy-menu-define'.")
884(defvar table-cell-menu-map nil
885 "Menu map created via `easy-menu-define'.")
886(defvar table-cell-buffer nil
887 "Buffer that contains the table cell.")
888(defvar table-cell-cache-point-coordinate nil
889 "Cache point coordinate based from the cell origin.")
890(defvar table-cell-cache-mark-coordinate nil
891 "Cache mark coordinate based from the cell origin.")
892(defvar table-cell-entered-state nil
893 "Records the state whether currently in a cell or nor.")
894(defvar table-update-timer nil
895 "Timer id for deferred cell update.")
896(defvar table-widen-timer nil
897 "Timer id for deferred cell update.")
898(defvar table-heighten-timer nil
899 "Timer id for deferred cell update.")
900(defvar table-inhibit-update nil
901 "Non-nil inhibits implicit cell and cache updates.
902It inhibits `table-with-cache-buffer' to update data in both direction, cell to cache and cache to cell.")
903(defvar table-inhibit-auto-fill-paragraph nil
904 "Non-nil inhibits auto fill paragraph when `table-with-cache-buffer' exits.
905This is always set to nil at the entry to `table-with-cache-buffer' before executing body forms.")
906(defvar table-mode-indicator nil
907 "For mode line indicator")
1042fc7f
SM
908;; This is not a real minor-mode but placed in the minor-mode-alist
909;; so that we can show the indicator on the mode line handy.
d2eed686 910(make-variable-buffer-local 'table-mode-indicator)
1042fc7f
SM
911(unless (assq table-mode-indicator minor-mode-alist)
912 (push '(table-mode-indicator (table-fixed-width-mode " Fixed-Table" " Table"))
913 minor-mode-alist))
914
238240c9
RS
915(defconst table-source-languages '(html latex cals)
916 "Supported source languages.")
917(defvar table-source-info-plist nil
918 "General storage for temporary information used while generating source.")
1042fc7f 919
d355a0b7
SM
920;; The following history containers not only keep the history of user
921;; entries but also serve as the default value providers. When an
922;; interactive command is invoked it offers a user the latest entry
923;; of the history as a default selection. Therefore the values below
924;; are the first default value when a command is invoked for the very
925;; first time when there is no real history existing yet.
238240c9
RS
926(defvar table-cell-span-direction-history '("right"))
927(defvar table-cell-split-orientation-history '("horizontally"))
928(defvar table-cell-split-contents-to-history '("split"))
929(defvar table-insert-row-column-history '("row"))
930(defvar table-justify-history '("center"))
931(defvar table-columns-history '("3"))
932(defvar table-rows-history '("3"))
933(defvar table-cell-width-history '("5"))
934(defvar table-cell-height-history '("1"))
935(defvar table-source-caption-history '("Table"))
936(defvar table-sequence-string-history '("0"))
937(defvar table-sequence-count-history '("0"))
938(defvar table-sequence-increment-history '("1"))
939(defvar table-sequence-interval-history '("1"))
940(defvar table-sequence-justify-history '("left"))
941(defvar table-source-language-history '("html"))
942(defvar table-col-delim-regexp-history '(""))
943(defvar table-row-delim-regexp-history '(""))
944(defvar table-capture-justify-history '("left"))
945(defvar table-capture-min-cell-width-history '("5"))
946(defvar table-capture-columns-history '(""))
947(defvar table-target-history '("cell"))
948
d355a0b7
SM
949;; Some entries in `table-cell-bindings' are duplicated in
950;; `table-command-remap-alist'. There is a good reason for
951;; this. Common key like return key may be taken by some other
952;; function than normal `newline' function. Thus binding return key
953;; directly for `*table--cell-newline' ensures that the correct enter
954;; operation in a table cell. However
955;; `table-command-remap-alist' has an additional role than
956;; replacing commands. It is also used to construct a table command
957;; list. This list is very important because it is used to check if
958;; the previous command was one of them in this list or not. If the
959;; previous command is found in the list the current command will not
960;; refill the table cache. If the command were not listed fast
961;; typing can cause unwanted cache refill.
238240c9
RS
962(defconst table-cell-bindings
963 '(([(control i)] . table-forward-cell)
964 ([(control I)] . table-backward-cell)
965 ([tab] . table-forward-cell)
966 ([(shift backtab)] . table-backward-cell) ; for HPUX console keyboard
967 ([(shift iso-lefttab)] . table-backward-cell) ; shift-tab on a microsoft natural keyboard and redhat linux
968 ([(shift tab)] . table-backward-cell)
969 ([return] . *table--cell-newline)
970 ([(control m)] . *table--cell-newline)
971 ([(control j)] . *table--cell-newline-and-indent)
972 ([mouse-3] . *table--present-cell-popup-menu)
973 ([(control ?>)] . table-widen-cell)
974 ([(control ?<)] . table-narrow-cell)
975 ([(control ?})] . table-heighten-cell)
976 ([(control ?{)] . table-shorten-cell)
977 ([(control ?-)] . table-split-cell-vertically)
978 ([(control ?|)] . table-split-cell-horizontally)
979 ([(control ?*)] . table-span-cell)
980 ([(control ?+)] . table-insert-row-column)
981 ([(control ?!)] . table-fixed-width-mode)
982 ([(control ?#)] . table-query-dimension)
983 ([(control ?^)] . table-generate-source)
984 ([(control ?:)] . table-justify)
985 )
986 "Bindings for table cell commands.")
987
e99add21 988(defvar table-command-remap-alist
238240c9
RS
989 '((self-insert-command . *table--cell-self-insert-command)
990 (completion-separator-self-insert-autofilling . *table--cell-self-insert-command)
991 (completion-separator-self-insert-command . *table--cell-self-insert-command)
992 (delete-char . *table--cell-delete-char)
993 (delete-backward-char . *table--cell-delete-backward-char)
994 (backward-delete-char . *table--cell-delete-backward-char)
995 (backward-delete-char-untabify . *table--cell-delete-backward-char)
996 (newline . *table--cell-newline)
997 (newline-and-indent . *table--cell-newline-and-indent)
998 (open-line . *table--cell-open-line)
999 (quoted-insert . *table--cell-quoted-insert)
1000 (describe-mode . *table--cell-describe-mode)
1001 (describe-bindings . *table--cell-describe-bindings)
1002 (dabbrev-expand . *table--cell-dabbrev-expand)
1003 (dabbrev-completion . *table--cell-dabbrev-completion))
1004 "List of cons cells consisting of (ORIGINAL-COMMAND . TABLE-VERSION-OF-THE-COMMAND).")
1005
e99add21 1006(defvar table-command-list nil
238240c9
RS
1007 "List of commands that override original commands.")
1008;; construct the real contents of the `table-command-list'
1009(let ((remap-alist table-command-remap-alist))
1010 (setq table-command-list nil)
1011 (while remap-alist
1012 (setq table-command-list (cons (cdar remap-alist) table-command-list))
1013 (setq remap-alist (cdr remap-alist))))
1014
1015(defconst table-global-menu
1016 '("Table"
1017 ("Insert"
1018 ["a Table..." table-insert
1019 :active (and (not buffer-read-only) (not (table--probe-cell)))
1020 :help "Insert a text based table at point"]
1021 ["Row" table-insert-row
951f97e6 1022 :active (table--row-column-insertion-point-p)
238240c9
RS
1023 :help "Insert row(s) of cells in table"]
1024 ["Column" table-insert-column
951f97e6 1025 :active (table--row-column-insertion-point-p 'column)
238240c9
RS
1026 :help "Insert column(s) of cells in table"])
1027 "----"
1028 ("Recognize"
1029 ["in Buffer" table-recognize
1030 :active t
1031 :help "Recognize all tables in the current buffer"]
1032 ["in Region" table-recognize-region
1033 :active (and mark-active (not (eq (mark t) (point))))
1034 :help "Recognize all tables in the current region"]
1035 ["a Table" table-recognize-table
1036 :active (table--probe-cell)
1037 :help "Recognize a table at point"]
1038 ["a Cell" table-recognize-cell
1039 :active (let ((cell (table--probe-cell)))
1040 (and cell (null (table--at-cell-p (car cell)))))
1041 :help "Recognize a cell at point"])
1042 ("Unrecognize"
1043 ["in Buffer" table-unrecognize
1044 :active t
1045 :help "Unrecognize all tables in the current buffer"]
1046 ["in Region" table-unrecognize-region
1047 :active (and mark-active (not (eq (mark t) (point))))
1048 :help "Unrecognize all tables in the current region"]
1049 ["a Table" table-unrecognize-table
1050 :active (table--probe-cell)
1051 :help "Unrecognize the current table"]
1052 ["a Cell" table-unrecognize-cell
1053 :active (let ((cell (table--probe-cell)))
1054 (and cell (table--at-cell-p (car cell))))
1055 :help "Unrecognize the current cell"])
1056 "----"
1057 ["Capture Region" table-capture
1058 :active (and (not buffer-read-only) mark-active (not (eq (mark t) (point))) (not (table--probe-cell)))
1059 :help "Capture text in the current region as a table"]
1060 ["Release" table-release
1061 :active (table--editable-cell-p)
1062 :help "Release the current table as plain text"]))
1063
1064(defconst table-cell-menu
1065 '("Table"
1066 ("Insert"
1067 ["Row" table-insert-row
951f97e6 1068 :active (table--row-column-insertion-point-p)
238240c9
RS
1069 :help "Insert row(s) of cells in table"]
1070 ["Column" table-insert-column
951f97e6 1071 :active (table--row-column-insertion-point-p 'column)
238240c9
RS
1072 :help "Insert column(s) of cells in table"])
1073 ("Delete"
1074 ["Row" table-delete-row
1075 :active (table--editable-cell-p)
1076 :help "Delete row(s) of cells in table"]
1077 ["Column" table-delete-column
1078 :active (table--editable-cell-p)
1079 :help "Delete column(s) of cells in table"])
1080 "----"
1081 ("Split a Cell"
1082 ["Horizontally" table-split-cell-horizontally
1083 :active (table--cell-can-split-horizontally-p)
1084 :help "Split the current cell horizontally at point"]
1085 ["Vertically" table-split-cell-vertically
1086 :active (table--cell-can-split-vertically-p)
1087 :help "Split the current cell vertical at point"])
1088 ("Span a Cell to"
1089 ["Right" (table-span-cell 'right)
1090 :active (table--cell-can-span-p 'right)
1091 :help "Span the current cell into the right cell"]
1092 ["Left" (table-span-cell 'left)
1093 :active (table--cell-can-span-p 'left)
1094 :help "Span the current cell into the left cell"]
1095 ["Above" (table-span-cell 'above)
1096 :active (table--cell-can-span-p 'above)
1097 :help "Span the current cell into the cell above"]
1098 ["Below" (table-span-cell 'below)
1099 :active (table--cell-can-span-p 'below)
1100 :help "Span the current cell into the cell below"])
1101 "----"
1102 ("Shrink Cells"
1103 ["Horizontally" table-narrow-cell
1104 :active (table--editable-cell-p)
1105 :help "Shrink the current cell horizontally"]
1106 ["Vertically" table-shorten-cell
1107 :active (table--editable-cell-p)
1108 :help "Shrink the current cell vertically"])
1109 ("Expand Cells"
1110 ["Horizontally" table-widen-cell
1111 :active (table--editable-cell-p)
1112 :help "Expand the current cell horizontally"]
1113 ["Vertically" table-heighten-cell
1114 :active (table--editable-cell-p)
1115 :help "Expand the current cell vertically"])
1116 "----"
1117 ("Justify"
1118 ("a Cell"
1119 ["Left" (table-justify-cell 'left)
1120 :active (table--editable-cell-p)
1121 :help "Left justify the contents of the current cell"]
1122 ["Center" (table-justify-cell 'center)
1123 :active (table--editable-cell-p)
1124 :help "Center justify the contents of the current cell"]
1125 ["Right" (table-justify-cell 'right)
1126 :active (table--editable-cell-p)
1127 :help "Right justify the contents of the current cell"]
1128 "----"
1129 ["Top" (table-justify-cell 'top)
1130 :active (table--editable-cell-p)
1131 :help "Top align the contents of the current cell"]
1132 ["Middle" (table-justify-cell 'middle)
1133 :active (table--editable-cell-p)
1134 :help "Middle align the contents of the current cell"]
1135 ["Bottom" (table-justify-cell 'bottom)
1136 :active (table--editable-cell-p)
1137 :help "Bottom align the contents of the current cell"]
1138 ["None" (table-justify-cell 'none)
1139 :active (table--editable-cell-p)
1140 :help "Remove vertical alignment from the current cell"])
1141 ("a Row"
1142 ["Left" (table-justify-row 'left)
1143 :active (table--editable-cell-p)
1144 :help "Left justify the contents of all cells in the current row"]
1145 ["Center" (table-justify-row 'center)
1146 :active (table--editable-cell-p)
1147 :help "Center justify the contents of all cells in the current row"]
1148 ["Right" (table-justify-row 'right)
1149 :active (table--editable-cell-p)
1150 :help "Right justify the contents of all cells in the current row"]
1151 "----"
1152 ["Top" (table-justify-row 'top)
1153 :active (table--editable-cell-p)
1154 :help "Top align the contents of all cells in the current row"]
1155 ["Middle" (table-justify-row 'middle)
1156 :active (table--editable-cell-p)
1157 :help "Middle align the contents of all cells in the current row"]
1158 ["Bottom" (table-justify-row 'bottom)
1159 :active (table--editable-cell-p)
1160 :help "Bottom align the contents of all cells in the current row"]
1161 ["None" (table-justify-cell 'none)
1162 :active (table--editable-cell-p)
1163 :help "Remove vertical alignment from all cells in the current row"])
1164 ("a Column"
1165 ["Left" (table-justify-column 'left)
1166 :active (table--editable-cell-p)
1167 :help "Left justify the contents of all cells in the current column"]
1168 ["Center" (table-justify-column 'center)
1169 :active (table--editable-cell-p)
1170 :help "Center justify the contents of all cells in the current column"]
1171 ["Right" (table-justify-column 'right)
1172 :active (table--editable-cell-p)
1173 :help "Right justify the contents of all cells in the current column"]
1174 "----"
1175 ["Top" (table-justify-column 'top)
1176 :active (table--editable-cell-p)
1177 :help "Top align the contents of all cells in the current column"]
1178 ["Middle" (table-justify-column 'middle)
1179 :active (table--editable-cell-p)
1180 :help "Middle align the contents of all cells in the current column"]
1181 ["Bottom" (table-justify-column 'bottom)
1182 :active (table--editable-cell-p)
1183 :help "Bottom align the contents of all cells in the current column"]
1184 ["None" (table-justify-cell 'none)
1185 :active (table--editable-cell-p)
1186 :help "Remove vertical alignment from all cells in the current column"])
1187 ("a Paragraph"
1188 ["Left" (table-justify-cell 'left t)
1189 :active (table--editable-cell-p)
1190 :help "Left justify the current paragraph"]
1191 ["Center" (table-justify-cell 'center t)
1192 :active (table--editable-cell-p)
1193 :help "Center justify the current paragraph"]
1194 ["Right" (table-justify-cell 'right t)
1195 :active (table--editable-cell-p)
1196 :help "Right justify the current paragraph"]))
1197 "----"
1198 ["Query Dimension" table-query-dimension
1199 :active (table--probe-cell)
1200 :help "Get the dimension of the current cell and the current table"]
1201 ["Generate Source" table-generate-source
1202 :active (table--probe-cell)
1203 :help "Generate source of the current table in the specified language"]
1204 ["Insert Sequence" table-insert-sequence
1205 :active (table--editable-cell-p)
1206 :help "Travel cells forward while inserting a specified sequence string in each cell"]
1207 ("Unrecognize"
1208 ["a Table" table-unrecognize-table
1209 :active (table--probe-cell)
1210 :help "Unrecognize the current table"]
1211 ["a Cell" table-unrecognize-cell
1212 :active (let ((cell (table--probe-cell)))
1213 (and cell (table--at-cell-p (car cell))))
1214 :help "Unrecognize the current cell"])
1215 ["Release" table-release
1216 :active (table--editable-cell-p)
1217 :help "Release the current table as plain text"]
1218 ("Configure Width to"
1219 ["Auto Expand Mode" (table-fixed-width-mode -1)
1220 :active t
1221 :style radio
1222 :selected (not table-fixed-width-mode)
1223 :help "A mode that allows automatic horizontal cell expansion"]
1224 ["Fixed Width Mode" (table-fixed-width-mode 1)
1225 :active t
1226 :style radio
1227 :selected table-fixed-width-mode
1228 :help "A mode that does not allow automatic horizontal cell expansion"])
1229 ("Navigate"
1230 ["Forward Cell" table-forward-cell
1231 :active (table--probe-cell)
1232 :help "Move point forward by cell(s)"]
1233 ["Backward Cell" table-backward-cell
1234 :active (table--probe-cell)
1235 :help "Move point backward by cell(s)"])
1236 ))
1237
1238;; XEmacs causes an error when encountering unknown keywords in the
1239;; menu definition. Specifically the :help keyword is new in Emacs 21
1240;; and causes error for the XEmacs function `check-menu-syntax'. IMHO
1241;; it is unwise to generate an error for unknown keywords because it
1242;; kills the nice backward compatible extensibility of keyword use.
1243;; Unknown keywords should be quietly ignore so that future extension
1244;; does not cause a problem in the old implementation. Sigh...
1245(when (featurep 'xemacs)
1246 (mapcar
1247 (defun table--tweak-menu-for-xemacs (menu)
1248 (cond
1249 ((listp menu)
1250 (mapcar 'table--tweak-menu-for-xemacs menu))
1251 ((vectorp menu)
1252 (let ((i 0) (len (length menu)))
1253 (while (< i len)
1254 ;; replace :help with something harmless.
1255 (if (eq (aref menu i) :help) (aset menu i :included))
1256 (setq i (1+ i)))))))
1257 (list table-global-menu table-cell-menu))
1258 (defvar mark-active t))
1259
1260;; register table menu under global tools menu
1261(unless table-disable-menu
1262 (easy-menu-define table-global-menu-map nil "Table global menu" table-global-menu)
1263 (if (featurep 'xemacs)
1264 (progn
1265 (easy-menu-add-item nil '("Tools") table-global-menu-map))
6e50f7e0 1266 (easy-menu-add-item (current-global-map) '("menu-bar" "tools") "--")
238240c9
RS
1267 (easy-menu-add-item (current-global-map) '("menu-bar" "tools") table-global-menu-map)))
1268
1269;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1270;;
1271;; Macros
1272;;
1273
1274(defmacro table-with-cache-buffer (&rest body)
1275 "Execute the forms in BODY with table cache buffer as the current buffer.
1276This macro simplifies the rest of the work greatly by condensing the
1277common idiom used in many of the cell manipulation functions. It does
1278not return any meaningful value.
1279
1280Save the current buffer and set the cache buffer as the current
1281buffer. Move the point to the cache buffer coordinate
1282`table-cell-cache-point-coordinate'. After BODY forms are executed,
1283the paragraph is filled as long as `table-inhibit-auto-fill-paragraph'
1284remains nil. BODY can set it to t when it does not want to fill the
1285paragraph. If necessary the cell width and height are extended as the
1286consequence of cell content modification by the BODY. Then the
1287current buffer is restored to the original one. The last cache point
1288coordinate is stored in `table-cell-cache-point-coordinate'. The
1289original buffer's point is moved to the location that corresponds to
1290the last cache point coordinate."
1291 (let ((height-expansion (make-symbol "height-expansion-var-symbol"))
1292 (width-expansion (make-symbol "width-expansion-var-symbol")))
1293 `(let (,height-expansion ,width-expansion)
1294 ;; make sure cache has valid data unless it is explicitly inhibited.
1295 (unless table-inhibit-update
1296 (table-recognize-cell))
1297 (with-current-buffer (get-buffer-create table-cache-buffer-name)
1298 ;; goto the cell coordinate based on `table-cell-cache-point-coordinate'.
1299 (set-mark (table--goto-coordinate table-cell-cache-mark-coordinate))
1300 (table--goto-coordinate table-cell-cache-point-coordinate)
1301 (table--untabify-line)
1302 ;; always reset before executing body forms because auto-fill behavior is the default.
1303 (setq table-inhibit-auto-fill-paragraph nil)
1304 ;; do the body
1305 ,@body
1306 ;; fill paragraph unless the body does not want to by setting `table-inhibit-auto-fill-paragraph'.
1307 (unless table-inhibit-auto-fill-paragraph
1308 (if (and table-cell-info-justify
1309 (not (eq table-cell-info-justify 'left)))
1310 (table--fill-region (point-min) (point-max))
1311 (table--fill-region
1312 (save-excursion (forward-paragraph -1) (point))
1313 (save-excursion (forward-paragraph 1) (point)))))
1314 ;; keep the updated cell coordinate.
1315 (setq table-cell-cache-point-coordinate (table--get-coordinate))
1316 ;; determine the cell width expansion.
1317 (setq ,width-expansion (table--measure-max-width))
1318 (if (<= ,width-expansion table-cell-info-width) nil
1319 (table--fill-region (point-min) (point-max) ,width-expansion)
1320 ;; keep the updated cell coordinate.
1321 (setq table-cell-cache-point-coordinate (table--get-coordinate)))
1322 (setq ,width-expansion (- ,width-expansion table-cell-info-width))
1323 ;; determine the cell height expansion.
1324 (if (looking-at "\\s *\\'") nil
1325 (goto-char (point-min))
1326 (if (re-search-forward "\\(\\s *\\)\\'" nil t)
1327 (goto-char (match-beginning 1))))
1328 (setq ,height-expansion (- (cdr (table--get-coordinate)) (1- table-cell-info-height))))
1329 ;; now back to the table buffer.
1330 ;; expand the cell width in the table buffer if necessary.
1331 (if (> ,width-expansion 0)
1332 (table-widen-cell ,width-expansion 'no-copy 'no-update))
1333 ;; expand the cell height in the table buffer if necessary.
1334 (if (> ,height-expansion 0)
1335 (table-heighten-cell ,height-expansion 'no-copy 'no-update))
1336 ;; do valign
1337 (with-current-buffer (get-buffer-create table-cache-buffer-name)
1338 (table--goto-coordinate table-cell-cache-point-coordinate)
1339 (setq table-cell-cache-point-coordinate (table--valign)))
1340 ;; move the point in the table buffer to the location that corresponds to
1341 ;; the location in the cell cache buffer
1342 (table--goto-coordinate (table--transcoord-cache-to-table table-cell-cache-point-coordinate))
1343 ;; set up the update timer unless it is explicitly inhibited.
1344 (unless table-inhibit-update
1345 (table--update-cell)))))
1346
1347;; for debugging the body form of the macro
1348(put 'table-with-cache-buffer 'edebug-form-spec '(body))
1349;; for neat presentation use the same indentation as `progn'
1350(put 'table-with-cache-buffer 'lisp-indent-function 0)
1351(if (or (featurep 'xemacs)
1352 (null (fboundp 'font-lock-add-keywords))) nil
1353 ;; color it as a keyword
1354 (font-lock-add-keywords
1355 'emacs-lisp-mode
1356 '("\\<table-with-cache-buffer\\>")))
1357
1358(defmacro table-put-source-info (prop value)
1359 "Register source generation information."
1360 `(put 'table-source-info-plist ,prop ,value))
1361
1362(defmacro table-get-source-info (prop)
1363 "Retrieve source generation information."
1364 `(get 'table-source-info-plist ,prop))
1365
1366;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1367;;
1368;; Modified commands for cell operation
1369;;
1370
1371;; Point Motion Only Group
4e454e5b 1372(mapc
238240c9
RS
1373 (lambda (command)
1374 (let ((func-symbol (intern (format "*table--cell-%s" command)))
1375 (doc-string (format "Table remapped function for `%s'." command)))
1376 (fset func-symbol
1377 `(lambda
1378 (&rest args)
1379 ,doc-string
1380 (interactive)
1381 (let ((table-inhibit-update t)
1382 (deactivate-mark nil))
1383 (table--finish-delayed-tasks)
1384 (table-recognize-cell 'force)
1385 (table-with-cache-buffer
1386 (call-interactively ',command)
1387 (setq table-inhibit-auto-fill-paragraph t)))))
1388 (setq table-command-remap-alist
1389 (cons (cons command func-symbol)
1390 table-command-remap-alist))))
04437a8f
EZ
1391 '(move-beginning-of-line
1392 beginning-of-line
1393 move-end-of-line
238240c9
RS
1394 end-of-line
1395 beginning-of-buffer
1396 end-of-buffer
1397 forward-word
1398 backward-word
7780d793
JB
1399 forward-sentence
1400 backward-sentence
238240c9
RS
1401 forward-paragraph
1402 backward-paragraph))
1403
1404;; Extraction Group
4e454e5b 1405(mapc
238240c9
RS
1406 (lambda (command)
1407 (let ((func-symbol (intern (format "*table--cell-%s" command)))
1408 (doc-string (format "Table remapped function for `%s'." command)))
1409 (fset func-symbol
1410 `(lambda
1411 (&rest args)
1412 ,doc-string
1413 (interactive)
1414 (table--finish-delayed-tasks)
1415 (table-recognize-cell 'force)
1416 (table-with-cache-buffer
1417 (table--remove-cell-properties (point-min) (point-max))
1418 (table--remove-eol-spaces (point-min) (point-max))
1419 (call-interactively ',command))
1420 (table--finish-delayed-tasks)))
1421 (setq table-command-remap-alist
1422 (cons (cons command func-symbol)
1423 table-command-remap-alist))))
1424 '(kill-region
7780d793 1425 kill-ring-save
238240c9
RS
1426 delete-region
1427 copy-region-as-kill
7780d793
JB
1428 kill-line
1429 kill-word
1430 backward-kill-word
1431 kill-sentence
1432 backward-kill-sentence
1433 kill-paragraph
1434 backward-kill-paragraph
1435 kill-sexp
1436 backward-kill-sexp))
238240c9
RS
1437
1438;; Pasting Group
4e454e5b 1439(mapc
238240c9
RS
1440 (lambda (command)
1441 (let ((func-symbol (intern (format "*table--cell-%s" command)))
1442 (doc-string (format "Table remapped function for `%s'." command)))
1443 (fset func-symbol
1444 `(lambda
1445 (&rest args)
1446 ,doc-string
1447 (interactive)
1448 (table--finish-delayed-tasks)
1449 (table-recognize-cell 'force)
1450 (table-with-cache-buffer
1451 (call-interactively ',command)
1452 (table--untabify (point-min) (point-max))
1453 (table--fill-region (point-min) (point-max))
1454 (setq table-inhibit-auto-fill-paragraph t))
1455 (table--finish-delayed-tasks)))
1456 (setq table-command-remap-alist
1457 (cons (cons command func-symbol)
1458 table-command-remap-alist))))
1459 '(yank
1460 clipboard-yank
1461 yank-clipboard-selection
1462 insert))
1463
1464;; Formatting Group
4e454e5b 1465(mapc
238240c9
RS
1466 (lambda (command)
1467 (let ((func-symbol (intern (format "*table--cell-%s" command)))
1468 (doc-string (format "Table remapped function for `%s'." command)))
1469 (fset func-symbol
1470 `(lambda
1471 (&rest args)
1472 ,doc-string
1473 (interactive)
1474 (table--finish-delayed-tasks)
1475 (table-recognize-cell 'force)
1476 (table-with-cache-buffer
1477 (let ((fill-column table-cell-info-width))
1478 (call-interactively ',command))
1479 (setq table-inhibit-auto-fill-paragraph t))
1480 (table--finish-delayed-tasks)))
1481 (setq table-command-remap-alist
1482 (cons (cons command func-symbol)
1483 table-command-remap-alist))))
1484 '(center-line
da6062e6 1485 center-region
238240c9
RS
1486 center-paragraph
1487 fill-paragraph))
1488
1489;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1490;;
1491;; Commands
1492;;
1493
1494;;;###autoload
1495(defun table-insert (columns rows &optional cell-width cell-height)
1496 "Insert an editable text table.
1497Insert a table of specified number of COLUMNS and ROWS. Optional
1498parameter CELL-WIDTH and CELL-HEIGHT can specify the size of each
1499cell. The cell size is uniform across the table if the specified size
1500is a number. They can be a list of numbers to specify different size
1501for each cell. When called interactively, the list of number is
1502entered by simply listing all the numbers with space characters
1503delimiting them.
1504
1505Examples:
1506
1507\\[table-insert] inserts a table at the current point location.
1508
1509Suppose we have the following situation where `-!-' indicates the
1510location of point.
1511
1512 -!-
1513
1514Type \\[table-insert] and hit ENTER key. As it asks table
1515specification, provide 3 for number of columns, 1 for number of rows,
15165 for cell width and 1 for cell height. Now you shall see the next
1517table and the point is automatically moved to the beginning of the
1518first cell.
1519
1520 +-----+-----+-----+
1521 |-!- | | |
1522 +-----+-----+-----+
1523
1524Inside a table cell, there are special key bindings. \\<table-cell-map>
1525
1526M-9 \\[table-widen-cell] (or \\[universal-argument] 9 \\[table-widen-cell]) widens the first cell by 9 character
1527width, which results as
1528
1529 +--------------+-----+-----+
1530 |-!- | | |
1531 +--------------+-----+-----+
1532
1533Type TAB \\[table-widen-cell] then type TAB M-2 M-7 \\[table-widen-cell] (or \\[universal-argument] 2 7 \\[table-widen-cell]). Typing
1534TAB moves the point forward by a cell. The result now looks like this:
1535
1536 +--------------+------+--------------------------------+
1537 | | |-!- |
1538 +--------------+------+--------------------------------+
1539
1540If you knew each width of the columns prior to the table creation,
1541what you could have done better was to have had given the complete
1542width information to `table-insert'.
1543
1544Cell width(s): 14 6 32
1545
db95369b 1546instead of
238240c9
RS
1547
1548Cell width(s): 5
1549
1550This would have eliminated the previously mentioned width adjustment
1551work all together.
1552
1553If the point is in the last cell type S-TAB S-TAB to move it to the
1554first cell. Now type \\[table-heighten-cell] which heighten the row by a line.
1555
1556 +--------------+------+--------------------------------+
1557 |-!- | | |
1558 | | | |
1559 +--------------+------+--------------------------------+
1560
1561Type \\[table-insert-row-column] and tell it to insert a row.
1562
1563 +--------------+------+--------------------------------+
1564 |-!- | | |
1565 | | | |
1566 +--------------+------+--------------------------------+
1567 | | | |
1568 | | | |
1569 +--------------+------+--------------------------------+
1570
1571Move the point under the table as shown below.
1572
1573 +--------------+------+--------------------------------+
1574 | | | |
1575 | | | |
1576 +--------------+------+--------------------------------+
1577 | | | |
1578 | | | |
1579 +--------------+------+--------------------------------+
1580 -!-
1581
1582Type M-x table-insert-row instead of \\[table-insert-row-column]. \\[table-insert-row-column] does not work
1583when the point is outside of the table. This insertion at
1584outside of the table effectively appends a row at the end.
1585
1586 +--------------+------+--------------------------------+
1587 | | | |
1588 | | | |
1589 +--------------+------+--------------------------------+
1590 | | | |
1591 | | | |
1592 +--------------+------+--------------------------------+
1593 |-!- | | |
1594 | | | |
1595 +--------------+------+--------------------------------+
1596
1597Text editing inside the table cell produces reasonably expected
1598results.
1599
1600 +--------------+------+--------------------------------+
1601 | | | |
1602 | | | |
1603 +--------------+------+--------------------------------+
1604 | | |Text editing inside the table |
1605 | | |cell produces reasonably |
1606 | | |expected results.-!- |
1607 +--------------+------+--------------------------------+
1608 | | | |
1609 | | | |
1610 +--------------+------+--------------------------------+
1611
1612Inside a table cell has a special keymap.
1613
1614\\{table-cell-map}
1615"
1616 (interactive
1617 (progn
1618 (barf-if-buffer-read-only)
1619 (if (table--probe-cell)
1620 (error "Can't insert a table inside a table"))
1621 (mapcar (function table--read-from-minibuffer)
1622 '(("Number of columns" . table-columns-history)
1623 ("Number of rows" . table-rows-history)
1624 ("Cell width(s)" . table-cell-width-history)
1625 ("Cell height(s)" . table-cell-height-history)))))
1626 (table--make-cell-map)
1627 ;; reform the arguments.
1628 (if (null cell-width) (setq cell-width (car table-cell-width-history)))
1629 (if (null cell-height) (setq cell-height (car table-cell-height-history)))
1630 (if (stringp columns) (setq columns (string-to-number columns)))
1631 (if (stringp rows) (setq rows (string-to-number rows)))
1632 (if (stringp cell-width) (setq cell-width (table--string-to-number-list cell-width)))
1633 (if (stringp cell-height) (setq cell-height (table--string-to-number-list cell-height)))
1634 (if (numberp cell-width) (setq cell-width (cons cell-width nil)))
1635 (if (numberp cell-height) (setq cell-height (cons cell-height nil)))
1636 ;; test validity of the arguments.
4e454e5b
JB
1637 (mapc (lambda (arg)
1638 (let* ((value (symbol-value arg))
1639 (error-handler
1640 (function (lambda ()
1641 (error "%s must be a positive integer%s" arg
1642 (if (listp value) " or a list of positive integers" ""))))))
1643 (if (null value) (funcall error-handler))
1644 (mapcar (function (lambda (arg1)
1645 (if (or (not (integerp arg1))
1646 (< arg1 1))
1647 (funcall error-handler))))
1648 (if (listp value) value
1649 (cons value nil)))))
1650 '(columns rows cell-width cell-height))
238240c9
RS
1651 (let ((orig-coord (table--get-coordinate))
1652 (coord (table--get-coordinate))
1653 r i cw ch cell-str border-str)
1654 ;; prefabricate the building blocks border-str and cell-str.
1655 (with-temp-buffer
1656 ;; construct border-str
1657 (insert table-cell-intersection-char)
1658 (setq cw cell-width)
1659 (setq i 0)
1660 (while (< i columns)
e99add21 1661 (insert (make-string (car cw) (string-to-char table-cell-horizontal-chars)) table-cell-intersection-char)
238240c9
RS
1662 (if (cdr cw) (setq cw (cdr cw)))
1663 (setq i (1+ i)))
1664 (setq border-str (buffer-substring (point-min) (point-max)))
1665 ;; construct cell-str
1666 (erase-buffer)
1667 (insert table-cell-vertical-char)
1668 (setq cw cell-width)
1669 (setq i 0)
1670 (while (< i columns)
1671 (let ((beg (point)))
ec85195e 1672 (insert (make-string (car cw) ?\s))
238240c9
RS
1673 (insert table-cell-vertical-char)
1674 (table--put-cell-line-property beg (1- (point))))
1675 (if (cdr cw) (setq cw (cdr cw)))
1676 (setq i (1+ i)))
1677 (setq cell-str (buffer-substring (point-min) (point-max))))
1678 ;; if the construction site has an empty border push that border down.
1679 (save-excursion
1680 (beginning-of-line)
1681 (if (looking-at "\\s *$")
1682 (progn
1683 (setq border-str (concat border-str "\n"))
1684 (setq cell-str (concat cell-str "\n")))))
1685 ;; now build the table using the prefabricated building blocks
1686 (setq r 0)
1687 (setq ch cell-height)
1688 (while (< r rows)
1689 (if (> r 0) nil
1690 (table--goto-coordinate coord) (setcdr coord (1+ (cdr coord)))
1691 (table--untabify-line (point))
1692 (insert border-str))
1693 (setq i 0)
1694 (while (< i (car ch))
1695 (table--goto-coordinate coord) (setcdr coord (1+ (cdr coord)))
1696 (table--untabify-line (point))
1697 (insert cell-str)
1698 (setq i (1+ i)))
1699 (table--goto-coordinate coord) (setcdr coord (1+ (cdr coord)))
1700 (table--untabify-line (point))
1701 (insert border-str)
1702 (if (cdr ch) (setq ch (cdr ch)))
1703 (setq r (1+ r)))
1704 ;; stand by at the first cell
1705 (table--goto-coordinate (table--offset-coordinate orig-coord '(1 . 1)))
1706 (table-recognize-cell 'force)))
1707
1708;;;###autoload
1709(defun table-insert-row (n)
1710 "Insert N table row(s).
1711When point is in a table the newly inserted row(s) are placed above
1712the current row. When point is outside of the table it must be below
1713the table within the table width range, then the newly created row(s)
1714are appended at the bottom of the table."
1715 (interactive "*p")
1716 (if (< n 0) (setq n 1))
1717 (let* ((current-coordinate (table--get-coordinate))
1718 (coord-list (table--cell-list-to-coord-list (table--horizontal-cell-list t nil 'top)))
1719 (append-row (if coord-list nil (setq coord-list (table--find-row-column))))
1720 (cell-height (cdr (table--min-coord-list coord-list)))
1721 (left-list nil)
1722 (this-list coord-list)
1723 (right-list (cdr coord-list))
1724 (bottom-border-y (1+ (cdr (table--get-coordinate (cdr (table--vertical-cell-list nil t))))))
1725 (vertical-str (string table-cell-vertical-char))
1726 (vertical-str-with-properties (let ((str (string table-cell-vertical-char)))
1727 (table--put-cell-keymap-property 0 (length str) str)
1728 (table--put-cell-rear-nonsticky 0 (length str) str) str))
1729 (first-time t))
1730 ;; create the space below for the table to grow
1731 (table--create-growing-space-below (* n (+ 1 cell-height)) coord-list bottom-border-y)
1732 ;; vertically expand each cell from left to right
1733 (while this-list
1734 (let* ((left (prog1 (car left-list) (setq left-list (if left-list (cdr left-list) coord-list))))
1735 (this (prog1 (car this-list) (setq this-list (cdr this-list))))
1736 (right (prog1 (car right-list) (setq right-list (cdr right-list))))
1737 (exclude-left (and left (< (cdar left) (cdar this))))
1738 (exclude-right (and right (<= (cdar right) (cdar this))))
1739 (beg (table--goto-coordinate
1740 (cons (if exclude-left (caar this) (1- (caar this)))
1741 (cdar this))))
1742 (end (table--goto-coordinate
1743 (cons (if exclude-right (cadr this) (1+ (cadr this)))
1744 bottom-border-y)))
1745 (rect (if append-row nil (extract-rectangle beg end))))
1746 ;; prepend blank cell lines to the extracted rectangle
1747 (let ((i n))
1748 (while (> i 0)
1749 (setq rect (cons
1750 (concat (if exclude-left "" (char-to-string table-cell-intersection-char))
e99add21 1751 (make-string (- (cadr this) (caar this)) (string-to-char table-cell-horizontal-chars))
238240c9
RS
1752 (if exclude-right "" (char-to-string table-cell-intersection-char)))
1753 rect))
1754 (let ((j cell-height))
1755 (while (> j 0)
1756 (setq rect (cons
1757 (concat (if exclude-left ""
1758 (if first-time vertical-str vertical-str-with-properties))
1759 (table--cell-blank-str (- (cadr this) (caar this)))
1760 (if exclude-right "" vertical-str-with-properties))
1761 rect))
1762 (setq j (1- j))))
1763 (setq i (1- i))))
1764 (setq first-time nil)
1765 (if append-row
1766 (table--goto-coordinate (cons (if exclude-left (caar this) (1- (caar this)))
1767 (1+ bottom-border-y)))
1768 (delete-rectangle beg end)
1769 (goto-char beg))
1770 (table--insert-rectangle rect)))
1771 ;; fix up the intersections
1772 (setq this-list (if append-row nil coord-list))
1773 (while this-list
1774 (let ((this (prog1 (car this-list) (setq this-list (cdr this-list))))
1775 (i 0))
1776 (while (< i n)
1777 (let ((y (1- (* i (+ 1 cell-height)))))
1778 (table--goto-coordinate (table--offset-coordinate (car this) (cons -1 y)))
1779 (delete-char 1) (insert table-cell-intersection-char)
1780 (table--goto-coordinate (table--offset-coordinate (cons (cadr this) (cdar this)) (cons 0 y)))
1781 (delete-char 1) (insert table-cell-intersection-char)
1782 (setq i (1+ i))))))
1783 ;; move the point to the beginning of the first newly inserted cell.
1784 (if (table--goto-coordinate
1785 (if append-row (cons (car (caar coord-list)) (1+ bottom-border-y))
1786 (caar coord-list))) nil
1787 (table--goto-coordinate current-coordinate))
1788 ;; re-recognize the current cell's new dimension
1789 (table-recognize-cell 'force)))
1790
1791;;;###autoload
1792(defun table-insert-column (n)
1793 "Insert N table column(s).
1794When point is in a table the newly inserted column(s) are placed left
1795of the current column. When point is outside of the table it must be
1796right side of the table within the table height range, then the newly
1797created column(s) are appended at the right of the table."
1798 (interactive "*p")
1799 (if (< n 0) (setq n 1))
1800 (let* ((current-coordinate (table--get-coordinate))
1801 (coord-list (table--cell-list-to-coord-list (table--vertical-cell-list t nil 'left)))
1802 (append-column (if coord-list nil (setq coord-list (table--find-row-column 'column))))
1803 (cell-width (car (table--min-coord-list coord-list)))
e99add21 1804 (border-str (table--multiply-string (concat (make-string cell-width (string-to-char table-cell-horizontal-chars))
238240c9
RS
1805 (char-to-string table-cell-intersection-char)) n))
1806 (cell-str (table--multiply-string (concat (table--cell-blank-str cell-width)
1807 (let ((str (string table-cell-vertical-char)))
1808 (table--put-cell-keymap-property 0 (length str) str)
1809 (table--put-cell-rear-nonsticky 0 (length str) str) str)) n))
1810 (columns-to-extend (* n (+ 1 cell-width)))
1811 (above-list nil)
1812 (this-list coord-list)
1813 (below-list (cdr coord-list))
1814 (right-border-x (car (table--get-coordinate (cdr (table--horizontal-cell-list nil t))))))
1815 ;; push back the affected area above and below this table
1816 (table--horizontally-shift-above-and-below columns-to-extend coord-list)
1817 ;; process each cell vertically from top to bottom
1818 (while this-list
1819 (let* ((above (prog1 (car above-list) (setq above-list (if above-list (cdr above-list) coord-list))))
1820 (this (prog1 (car this-list) (setq this-list (cdr this-list))))
1821 (below (prog1 (car below-list) (setq below-list (cdr below-list))))
1822 (exclude-above (and above (<= (caar above) (caar this))))
1823 (exclude-below (and below (< (caar below) (caar this))))
1824 (beg-coord (cons (if append-column (1+ right-border-x) (caar this))
1825 (if exclude-above (cdar this) (1- (cdar this)))))
1826 (end-coord (cons (1+ right-border-x)
1827 (if exclude-below (cddr this) (1+ (cddr this)))))
1828 rect)
1829 ;; untabify the area right of the bar that is about to be inserted
1830 (let ((coord (table--copy-coordinate beg-coord))
1831 (i 0)
1832 (len (length rect)))
1833 (while (< i len)
1834 (if (table--goto-coordinate coord 'no-extension)
1835 (table--untabify-line (point)))
1836 (setcdr coord (1+ (cdr coord)))
1837 (setq i (1+ i))))
1838 ;; extract and delete the rectangle area including the current
1839 ;; cell and to the right border of the table.
1840 (setq rect (extract-rectangle (table--goto-coordinate beg-coord)
1841 (table--goto-coordinate end-coord)))
1842 (delete-rectangle (table--goto-coordinate beg-coord)
1843 (table--goto-coordinate end-coord))
1844 ;; prepend the empty column string at the beginning of each
1845 ;; rectangle string extracted before.
1846 (let ((rect-str rect)
1847 (first t))
1848 (while rect-str
1849 (if (and first (null exclude-above))
1850 (setcar rect-str (concat border-str (car rect-str)))
1851 (if (and (null (cdr rect-str)) (null exclude-below))
1852 (setcar rect-str (concat border-str (car rect-str)))
1853 (setcar rect-str (concat cell-str (car rect-str)))))
1854 (setq first nil)
1855 (setq rect-str (cdr rect-str))))
1856 ;; insert the extended rectangle
1857 (table--goto-coordinate beg-coord)
1858 (table--insert-rectangle rect)))
1859 ;; fix up the intersections
1860 (setq this-list (if append-column nil coord-list))
1861 (while this-list
1862 (let ((this (prog1 (car this-list) (setq this-list (cdr this-list))))
1863 (i 0))
1864 (while (< i n)
1865 (let ((x (1- (* (1+ i) (+ 1 cell-width)))))
1866 (table--goto-coordinate (table--offset-coordinate (car this) (cons x -1)))
1867 (delete-char 1) (insert table-cell-intersection-char)
1868 (table--goto-coordinate (table--offset-coordinate (cons (caar this) (cddr this)) (cons x 1)))
1869 (delete-char 1) (insert table-cell-intersection-char)
1870 (setq i (1+ i))))))
1871 ;; move the point to the beginning of the first newly inserted cell.
1872 (if (table--goto-coordinate
1873 (if append-column
1874 (cons (1+ right-border-x)
1875 (cdar (car coord-list)))
1876 (caar coord-list))) nil
1877 (table--goto-coordinate current-coordinate))
1878 ;; re-recognize the current cell's new dimension
1879 (table-recognize-cell 'force)))
1880
1881;;;###autoload
1882(defun table-insert-row-column (row-column n)
1883 "Insert row(s) or column(s).
1884See `table-insert-row' and `table-insert-column'."
1885 (interactive
1886 (let ((n (prefix-numeric-value current-prefix-arg)))
1887 (if (< n 0) (setq n 1))
1888 (list (intern (let ((completion-ignore-case t)
1889 (default (car table-insert-row-column-history)))
1890 (downcase (completing-read
1891 (format "Insert %s row%s/column%s (default %s): "
1892 (if (> n 1) (format "%d" n) "a")
1893 (if (> n 1) "s" "")
1894 (if (> n 1) "s" "")
1895 default)
1896 '(("row") ("column"))
1897 nil t nil 'table-insert-row-column-history default))))
1898 n)))
1899 (cond ((eq row-column 'row)
1900 (table-insert-row n))
1901 ((eq row-column 'column)
1902 (table-insert-column n))))
1903
1904;;;###autoload
1905(defun table-recognize (&optional arg)
1906 "Recognize all tables within the current buffer and activate them.
1907Scans the entire buffer and recognizes valid table cells. If the
1908optional numeric prefix argument ARG is negative the tables in the
1909buffer become inactive, meaning the tables become plain text and loses
1910all the table specific features."
1911 (interactive "P")
1912 (setq arg (prefix-numeric-value arg))
1913 (let* ((inhibit-read-only t))
1914 (table-recognize-region (point-min) (point-max) -1)
1915 (if (>= arg 0)
1916 (save-excursion
1917 (goto-char (point-min))
e99add21
JB
1918 (let* ((border (format "[%s%c%c]"
1919 table-cell-horizontal-chars
238240c9
RS
1920 table-cell-vertical-char
1921 table-cell-intersection-char))
1922 (border3 (concat border border border))
e99add21
JB
1923 (non-border (format "^[^%s%c%c]*$"
1924 table-cell-horizontal-chars
238240c9
RS
1925 table-cell-vertical-char
1926 table-cell-intersection-char)))
1927 ;; `table-recognize-region' is an expensive function so minimize
1928 ;; the search area. A minimum table at least consists of three consecutive
1929 ;; table border characters to begin with such as
1930 ;; +-+
1931 ;; |A|
1932 ;; +-+
1933 ;; and any tables end with a line containing no table border characters
1934 ;; or the end of buffer.
1935 (while (and (re-search-forward border3 (point-max) t)
1936 (not (and (input-pending-p)
1937 table-abort-recognition-when-input-pending)))
1938 (message "Recognizing tables...(%d%%)" (/ (* 100 (match-beginning 0)) (- (point-max) (point-min))))
1939 (let ((beg (match-beginning 0))
1940 end)
1941 (if (re-search-forward non-border (point-max) t)
1942 (setq end (match-beginning 0))
1943 (setq end (goto-char (point-max))))
1944 (table-recognize-region beg end arg)))
1945 (message "Recognizing tables...done"))))))
1946
1947;;;###autoload
1948(defun table-unrecognize ()
1949 (interactive)
1950 (table-recognize -1))
1951
1952;;;###autoload
1953(defun table-recognize-region (beg end &optional arg)
1954 "Recognize all tables within region.
1955BEG and END specify the region to work on. If the optional numeric
1956prefix argument ARG is negative the tables in the region become
1957inactive, meaning the tables become plain text and lose all the table
1958specific features."
1959 (interactive "r\nP")
1960 (setq arg (prefix-numeric-value arg))
1961 (let ((inhibit-read-only t)
1962 (modified-flag (buffer-modified-p)))
1963 (if (< arg 0)
1964 (table--remove-cell-properties beg end)
1965 (save-excursion
1966 (goto-char beg)
e99add21
JB
1967 (let* ((border (format "[%s%c%c]"
1968 table-cell-horizontal-chars
238240c9
RS
1969 table-cell-vertical-char
1970 table-cell-intersection-char))
e99add21
JB
1971 (non-border (format "[^%s%c%c]"
1972 table-cell-horizontal-chars
238240c9
RS
1973 table-cell-vertical-char
1974 table-cell-intersection-char))
1975 (inhibit-read-only t))
1976 (unwind-protect
1977 (progn
1978 (remove-text-properties beg end '(table-cell nil))
1979 (while (and (< (point) end)
1980 (not (and (input-pending-p)
1981 table-abort-recognition-when-input-pending)))
1982 (cond
1983 ((looking-at "\n")
1984 (forward-char 1))
1985 ((looking-at border)
1986 (if (re-search-forward non-border end t)
1987 (goto-char (match-beginning 0))
1988 (goto-char end)))
1989 ((table--at-cell-p (point))
1990 (goto-char (next-single-property-change (point) 'table-cell nil end)))
1991 (t
1992 (let ((cell (table-recognize-cell 'force 'no-copy)))
1993 (if (and cell table-detect-cell-alignment)
1994 (table--detect-cell-alignment cell)))
1995 (unless (re-search-forward border end t)
1996 (goto-char end))))))))))
1042fc7f 1997 (restore-buffer-modified-p modified-flag)))
238240c9
RS
1998
1999;;;###autoload
2000(defun table-unrecognize-region (beg end)
2001 (interactive "r")
2002 (table-recognize-region beg end -1))
2003
2004;;;###autoload
2005(defun table-recognize-table (&optional arg)
2006 "Recognize a table at point.
2007If the optional numeric prefix argument ARG is negative the table
2008becomes inactive, meaning the table becomes plain text and loses all
2009the table specific features."
2010 (interactive "P")
2011 (setq arg (prefix-numeric-value arg))
2012 (let ((unrecognize (< arg 0))
2013 (origin-cell (table--probe-cell))
2014 (inhibit-read-only t))
2015 (if origin-cell
2016 (save-excursion
2017 (while
2018 (progn
2019 (table-forward-cell 1 nil unrecognize)
2020 (let ((cell (table--probe-cell)))
2021 (if (and cell table-detect-cell-alignment)
2022 (table--detect-cell-alignment cell))
2023 (and cell (not (equal cell origin-cell))))))))))
2024
2025;;;###autoload
2026(defun table-unrecognize-table ()
2027 (interactive)
2028 (table-recognize-table -1))
2029
2030;;;###autoload
2031(defun table-recognize-cell (&optional force no-copy arg)
2032 "Recognize a table cell that contains current point.
2033Probe the cell dimension and prepare the cell information. The
2034optional two arguments FORCE and NO-COPY are for internal use only and
2035must not be specified. When the optional numeric prefix argument ARG
2036is negative the cell becomes inactive, meaning that the cell becomes
2037plain text and loses all the table specific features."
2038 (interactive "i\ni\np")
2039 (table--make-cell-map)
2040 (if (or force (not (memq (table--get-last-command) table-command-list)))
32226619 2041 (let* ((cell (table--probe-cell (called-interactively-p 'interactive)))
238240c9
RS
2042 (cache-buffer (get-buffer-create table-cache-buffer-name))
2043 (modified-flag (buffer-modified-p))
2044 (inhibit-read-only t))
2045 (unwind-protect
2046 (unless (null cell)
2047 ;; initialize the cell info variables
2048 (let ((lu-coordinate (table--get-coordinate (car cell)))
2049 (rb-coordinate (table--get-coordinate (cdr cell))))
2050 ;; update the previous cell if this cell is different from the previous one.
2051 ;; care only lu but ignore rb since size change does not matter.
2052 (unless (equal table-cell-info-lu-coordinate lu-coordinate)
2053 (table--finish-delayed-tasks))
2054 (setq table-cell-info-lu-coordinate lu-coordinate)
2055 (setq table-cell-info-rb-coordinate rb-coordinate)
2056 (setq table-cell-info-width (- (car table-cell-info-rb-coordinate)
2057 (car table-cell-info-lu-coordinate)))
2058 (setq table-cell-info-height (+ (- (cdr table-cell-info-rb-coordinate)
2059 (cdr table-cell-info-lu-coordinate)) 1))
2060 (setq table-cell-info-justify (table--get-cell-justify-property cell))
2061 (setq table-cell-info-valign (table--get-cell-valign-property cell)))
2062 ;; set/remove table cell properties
2063 (if (< (prefix-numeric-value arg) 0)
2064 (let ((coord (table--get-coordinate (car cell)))
2065 (n table-cell-info-height))
2066 (save-excursion
2067 (while (> n 0)
2068 (table--remove-cell-properties
2069 (table--goto-coordinate coord)
2070 (table--goto-coordinate (cons (+ (car coord) table-cell-info-width 1) (cdr coord))))
2071 (setq n (1- n))
2072 (setcdr coord (1+ (cdr coord))))))
2073 (table--put-cell-property cell))
2074 ;; copy the cell contents to the cache buffer
2075 ;; only if no-copy is nil and timers are not set
2076 (unless no-copy
2077 (setq table-cell-cache-point-coordinate (table--transcoord-table-to-cache))
2078 (setq table-cell-cache-mark-coordinate (table--transcoord-table-to-cache
2079 (table--get-coordinate (marker-position (mark-marker)))))
2080 (setq table-cell-buffer (current-buffer))
2081 (let ((rectangle (extract-rectangle (car cell)
2082 (cdr cell))))
2083 (save-current-buffer
2084 (set-buffer cache-buffer)
2085 (erase-buffer)
2086 (table--insert-rectangle rectangle)))))
1042fc7f 2087 (restore-buffer-modified-p modified-flag))
238240c9
RS
2088 (if (featurep 'xemacs)
2089 (table--warn-incompatibility))
2090 cell)))
2091
2092;;;###autoload
2093(defun table-unrecognize-cell ()
2094 (interactive)
2095 (table-recognize-cell nil nil -1))
2096
2097;;;###autoload
2098(defun table-heighten-cell (n &optional no-copy no-update)
2099 "Heighten the current cell by N lines by expanding the cell vertically.
2100Heightening is done by adding blank lines at the bottom of the current
2101cell. Other cells aligned horizontally with the current one are also
2102heightened in order to keep the rectangular table structure. The
2103optional argument NO-COPY is internal use only and must not be
2104specified."
2105 (interactive "*p")
2106 (if (< n 0) (setq n 1))
2107 (let* ((coord-list (table--cell-list-to-coord-list (table--horizontal-cell-list t)))
2108 (left-list nil)
2109 (this-list coord-list)
2110 (right-list (cdr coord-list))
2111 (bottom-border-y (1+ (cdr (table--get-coordinate (cdr (table--vertical-cell-list nil t))))))
2112 (vertical-str (string table-cell-vertical-char))
2113 (vertical-str-with-properties (string table-cell-vertical-char))
2114 (first-time t)
2115 (current-coordinate (table--get-coordinate)))
2116 ;; prepare the right vertical string with appropriate properties put
2117 (table--put-cell-keymap-property 0 (length vertical-str-with-properties) vertical-str-with-properties)
2118 ;; create the space below for the table to grow
2119 (table--create-growing-space-below n coord-list bottom-border-y)
2120 ;; vertically expand each cell from left to right
2121 (while this-list
2122 (let* ((left (prog1 (car left-list) (setq left-list (if left-list (cdr left-list) coord-list))))
2123 (this (prog1 (car this-list) (setq this-list (cdr this-list))))
2124 (right (prog1 (car right-list) (setq right-list (cdr right-list))))
2125 (exclude-left (and left (< (cddr left) (cddr this))))
2126 (exclude-right (and right (<= (cddr right) (cddr this))))
2127 (beg (table--goto-coordinate
2128 (cons (if exclude-left (caar this) (1- (caar this)))
2129 (1+ (cddr this)))))
2130 (end (table--goto-coordinate
2131 (cons (if exclude-right (cadr this) (1+ (cadr this)))
2132 bottom-border-y)))
2133 (rect (extract-rectangle beg end)))
2134 ;; prepend blank cell lines to the extracted rectangle
2135 (let ((i n))
2136 (while (> i 0)
2137 (setq rect (cons
2138 (concat (if exclude-left ""
2139 (if first-time vertical-str vertical-str-with-properties))
2140 (table--cell-blank-str (- (cadr this) (caar this)))
2141 (if exclude-right "" vertical-str-with-properties))
2142 rect))
2143 (setq i (1- i))))
2144 (setq first-time nil)
2145 (delete-rectangle beg end)
2146 (goto-char beg)
2147 (table--insert-rectangle rect)))
2148 (table--goto-coordinate current-coordinate)
2149 ;; re-recognize the current cell's new dimension
2150 (table-recognize-cell 'force no-copy)
2151 (unless no-update
2152 (table--update-cell-heightened))))
2153
2154;;;###autoload
2155(defun table-shorten-cell (n)
2156 "Shorten the current cell by N lines by shrinking the cell vertically.
2157Shortening is done by removing blank lines from the bottom of the cell
2158and possibly from the top of the cell as well. Therefor, the cell
2159must have some bottom/top blank lines to be shorten effectively. This
2160is applicable to all the cells aligned horizontally with the current
2161one because they are also shortened in order to keep the rectangular
2162table structure."
2163 (interactive "*p")
2164 (if (< n 0) (setq n 1))
2165 (table--finish-delayed-tasks)
2166 (let* ((table-inhibit-update t)
2167 (coord-list (table--cell-list-to-coord-list (table--horizontal-cell-list t)))
2168 (left-list nil)
2169 (this-list coord-list)
2170 (right-list (cdr coord-list))
2171 (bottom-budget-list nil)
2172 (bottom-border-y (1+ (cdr (table--get-coordinate (cdr (table--vertical-cell-list nil t))))))
2173 (current-coordinate (table--get-coordinate))
2174 (current-cell-coordinate (table--cell-to-coord (table--probe-cell)))
2175 (blank-line-regexp "\\s *$"))
2176 (message "Shortening...");; this operation may be lengthy
2177 ;; for each cell calculate the maximum number of blank lines we can delete
2178 ;; and adjust the argument n. n is adjusted so that the total number of
2179 ;; blank lines from top and bottom of a cell do not exceed n, all cell has
2180 ;; at least one line height after blank line deletion.
2181 (while this-list
2182 (let ((this (prog1 (car this-list) (setq this-list (cdr this-list)))))
2183 (table--goto-coordinate (car this))
2184 (table-recognize-cell 'force)
2185 (table-with-cache-buffer
2186 (catch 'end-count
2187 (let ((blank-line-count 0))
2188 (table--goto-coordinate (cons 0 (1- table-cell-info-height)))
2189 ;; count bottom
2190 (while (and (looking-at blank-line-regexp)
2191 (setq blank-line-count (1+ blank-line-count))
2192 ;; need to leave at least one blank line
2193 (if (> blank-line-count n) (throw 'end-count nil) t)
2194 (if (zerop (forward-line -1)) t
2195 (setq n (if (zerop blank-line-count) 0
2196 (1- blank-line-count)))
2197 (throw 'end-count nil))))
2198 (table--goto-coordinate (cons 0 0))
2199 ;; count top
2200 (while (and (looking-at blank-line-regexp)
2201 (setq blank-line-count (1+ blank-line-count))
2202 ;; can consume all blank lines
2203 (if (>= blank-line-count n) (throw 'end-count nil) t)
2204 (zerop (forward-line 1))))
2205 (setq n blank-line-count))))))
2206 ;; construct the bottom-budget-list which is a list of numbers where each number
2207 ;; corresponds to how many lines to be deleted from the bottom of each cell. If
2208 ;; this number, say bb, is smaller than n (bb < n) that means the difference (n - bb)
2209 ;; number of lines must be deleted from the top of the cell in addition to deleting
2210 ;; bb lines from the bottom of the cell.
2211 (setq this-list coord-list)
2212 (while this-list
2213 (let ((this (prog1 (car this-list) (setq this-list (cdr this-list)))))
2214 (table--goto-coordinate (car this))
2215 (table-recognize-cell 'force)
2216 (table-with-cache-buffer
2217 (setq bottom-budget-list
2218 (cons
2219 (let ((blank-line-count 0))
2220 (table--goto-coordinate (cons 0 (1- table-cell-info-height)))
2221 (while (and (looking-at blank-line-regexp)
2222 (< blank-line-count n)
2223 (setq blank-line-count (1+ blank-line-count))
2224 (zerop (forward-line -1))))
2225 blank-line-count)
2226 bottom-budget-list)))))
2227 (setq bottom-budget-list (nreverse bottom-budget-list))
2228 ;; vertically shorten each cell from left to right
2229 (setq this-list coord-list)
2230 (while this-list
2231 (let* ((left (prog1 (car left-list) (setq left-list (if left-list (cdr left-list) coord-list))))
2232 (this (prog1 (car this-list) (setq this-list (cdr this-list))))
2233 (right (prog1 (car right-list) (setq right-list (cdr right-list))))
2234 (bottom-budget (prog1 (car bottom-budget-list) (setq bottom-budget-list (cdr bottom-budget-list))))
2235 (exclude-left (and left (< (cddr left) (cddr this))))
2236 (exclude-right (and right (<= (cddr right) (cddr this))))
2237 (beg (table--goto-coordinate (cons (caar this) (cdar this))))
2238 (end (table--goto-coordinate (cons (cadr this) bottom-border-y)))
2239 (rect (extract-rectangle beg end))
2240 (height (+ (- (cddr this) (cdar this)) 1))
ec85195e 2241 (blank-line (make-string (- (cadr this) (caar this)) ?\s)))
238240c9
RS
2242 ;; delete lines from the bottom of the cell
2243 (setcdr (nthcdr (- height bottom-budget 1) rect) (nthcdr height rect))
2244 ;; delete lines from the top of the cell
2245 (if (> n bottom-budget)
2246 (let ((props (text-properties-at 0 (car rect))))
2247 (setq rect (nthcdr (- n bottom-budget) rect))
2248 (set-text-properties 0 1 props (car rect))))
2249 ;; append blank lines below the table
2250 (setq rect (append rect (make-list n blank-line)))
2251 ;; now swap the area with the prepared rect of the same size
2252 (delete-rectangle beg end)
2253 (goto-char beg)
2254 (table--insert-rectangle rect)
2255 ;; for the left and right borders always delete lines from the bottom of the cell
2256 (unless exclude-left
2257 (let* ((beg (table--goto-coordinate (cons (1- (caar this)) (cdar this))))
2258 (end (table--goto-coordinate (cons (caar this) bottom-border-y)))
2259 (rect (extract-rectangle beg end)))
2260 (setcdr (nthcdr (- height n 1) rect) (nthcdr height rect))
2261 (setq rect (append rect (make-list n " ")))
2262 (delete-rectangle beg end)
2263 (goto-char beg)
2264 (table--insert-rectangle rect)))
2265 (unless exclude-right
2266 (let* ((beg (table--goto-coordinate (cons (cadr this) (cdar this))))
2267 (end (table--goto-coordinate (cons (1+ (cadr this)) bottom-border-y)))
2268 (rect (extract-rectangle beg end)))
2269 (setcdr (nthcdr (- height n 1) rect) (nthcdr height rect))
2270 (setq rect (append rect (make-list n " ")))
2271 (delete-rectangle beg end)
2272 (goto-char beg)
2273 (table--insert-rectangle rect)))
2274 ;; if this is the cell where the original point was in, adjust the point location
2275 (if (null (equal this current-cell-coordinate)) nil
2276 (let ((y (- (cdr current-coordinate) (cdar this))))
2277 (if (< y (- n bottom-budget))
2278 (setcdr current-coordinate (cdar this))
2279 (if (< (- y (- n bottom-budget)) (- height n))
2280 (setcdr current-coordinate (+ (cdar this) (- y (- n bottom-budget))))
2281 (setcdr current-coordinate (+ (cdar this) (- height n 1)))))))))
2282 ;; remove the appended blank lines below the table if they are unnecessary
2283 (table--goto-coordinate (cons 0 (1+ (- bottom-border-y n))))
2284 (table--remove-blank-lines n)
2285 ;; re-recognize the current cell's new dimension
2286 (table--goto-coordinate current-coordinate)
2287 (table-recognize-cell 'force)
2288 (table--update-cell-heightened)
2289 (message "")))
2290
2291;;;###autoload
2292(defun table-widen-cell (n &optional no-copy no-update)
2293 "Widen the current cell by N columns and expand the cell horizontally.
2294Some other cells in the same table are widen as well to keep the
2295table's rectangle structure."
2296 (interactive "*p")
2297 (if (< n 0) (setq n 1))
2298 (let* ((coord-list (table--cell-list-to-coord-list (table--vertical-cell-list)))
2299 (below-list nil)
2300 (this-list coord-list)
2301 (above-list (cdr coord-list)))
2302 (save-excursion
2303 ;; push back the affected area above and below this table
2304 (table--horizontally-shift-above-and-below n (reverse coord-list))
2305 ;; now widen vertically for each cell
2306 (while this-list
2307 (let* ((below (prog1 (car below-list) (setq below-list (if below-list (cdr below-list) coord-list))))
2308 (this (prog1 (car this-list) (setq this-list (cdr this-list))))
2309 (above (prog1 (car above-list) (setq above-list (cdr above-list))))
2310 (beg (table--goto-coordinate
2311 (cons (car (cdr this))
2312 (if (or (null above) (<= (car (cdr this)) (car (cdr above))))
2313 (1- (cdr (car this)))
2314 (cdr (car this))))))
2315 (end (table--goto-coordinate
2316 (cons (1+ (car (cdr this)))
2317 (if (or (null below) (< (car (cdr this)) (car (cdr below))))
2318 (1+ (cdr (cdr this)))
2319 (cdr (cdr this))))))
2320 (tmp (extract-rectangle (1- beg) end))
e99add21
JB
2321 (border (format "[%s%c]\\%c"
2322 table-cell-horizontal-chars
238240c9
RS
2323 table-cell-intersection-char
2324 table-cell-intersection-char))
2325 (blank (table--cell-blank-str))
2326 rectangle)
2327 ;; create a single wide vertical bar of empty cell fragment
2328 (while tmp
e99add21
JB
2329; (message "tmp is %s" tmp)
2330 (setq rectangle (cons
2331 (if (string-match border (car tmp))
2332 (substring (car tmp) 0 1)
238240c9
RS
2333 blank)
2334 rectangle))
e99add21 2335; (message "rectangle is %s" rectangle)
238240c9
RS
2336 (setq tmp (cdr tmp)))
2337 (setq rectangle (nreverse rectangle))
2338 ;; untabify the area right of the bar that is about to be inserted
2339 (let ((coord (table--get-coordinate beg))
2340 (i 0)
2341 (len (length rectangle)))
2342 (while (< i len)
2343 (if (table--goto-coordinate coord 'no-extension)
2344 (table--untabify-line (point)))
2345 (setcdr coord (1+ (cdr coord)))
2346 (setq i (1+ i))))
2347 ;; insert the bar n times
2348 (goto-char beg)
2349 (let ((i 0))
2350 (while (< i n)
2351 (save-excursion
2352 (table--insert-rectangle rectangle))
2353 (setq i (1+ i)))))))
2354 (table-recognize-cell 'force no-copy)
2355 (unless no-update
2356 (table--update-cell-widened))))
2357
2358;;;###autoload
2359(defun table-narrow-cell (n)
2360 "Narrow the current cell by N columns and shrink the cell horizontally.
2361Some other cells in the same table are narrowed as well to keep the
2362table's rectangle structure."
2363 (interactive "*p")
2364 (if (< n 0) (setq n 1))
2365 (table--finish-delayed-tasks)
2366 (let* ((coord-list (table--cell-list-to-coord-list (table--vertical-cell-list)))
2367 (current-cell (table--cell-to-coord (table--probe-cell)))
2368 (current-coordinate (table--get-coordinate))
2369 tmp-list)
2370 (message "Narrowing...");; this operation may be lengthy
2371 ;; determine the doable n by try narrowing each cell.
2372 (setq tmp-list coord-list)
2373 (while tmp-list
2374 (let ((cell (prog1 (car tmp-list) (setq tmp-list (cdr tmp-list))))
2375 (table-inhibit-update t)
2376 cell-n)
2377 (table--goto-coordinate (car cell))
2378 (table-recognize-cell 'force)
2379 (table-with-cache-buffer
2380 (table--fill-region (point-min) (point-max) (- table-cell-info-width n))
2381 (if (< (setq cell-n (- table-cell-info-width (table--measure-max-width))) n)
2382 (setq n cell-n))
2383 (erase-buffer)
2384 (setq table-inhibit-auto-fill-paragraph t))))
2385 (if (< n 1) nil
2386 ;; narrow only the contents of each cell but leave the cell frame as is because
2387 ;; we need to have valid frame structure in order for table-with-cache-buffer
2388 ;; to work correctly.
2389 (setq tmp-list coord-list)
2390 (while tmp-list
2391 (let* ((cell (prog1 (car tmp-list) (setq tmp-list (cdr tmp-list))))
2392 (table-inhibit-update t)
2393 (currentp (equal cell current-cell))
2394 old-height)
2395 (if currentp (table--goto-coordinate current-coordinate)
2396 (table--goto-coordinate (car cell)))
2397 (table-recognize-cell 'force)
2398 (setq old-height table-cell-info-height)
2399 (table-with-cache-buffer
2400 (let ((out-of-bound (>= (- (car current-coordinate) (car table-cell-info-lu-coordinate))
2401 (- table-cell-info-width n)))
2402 (sticky (and currentp
2403 (save-excursion
2404 (unless (bolp) (forward-char -1))
2405 (looking-at ".*\\S ")))))
2406 (table--fill-region (point-min) (point-max) (- table-cell-info-width n))
2407 (if (or sticky (and currentp (looking-at ".*\\S ")))
2408 (setq current-coordinate (table--transcoord-cache-to-table))
2409 (if out-of-bound (setcar current-coordinate
2410 (+ (car table-cell-info-lu-coordinate) (- table-cell-info-width n 1))))))
2411 (setq table-inhibit-auto-fill-paragraph t))
2412 (table--update-cell 'now)
2413 ;; if this cell heightens and pushes the current cell below, move
2414 ;; the current-coordinate (point location) down accordingly.
2415 (if currentp (setq current-coordinate (table--get-coordinate))
2416 (if (and (> table-cell-info-height old-height)
2417 (> (cdr current-coordinate) (cdr table-cell-info-lu-coordinate)))
2418 (setcdr current-coordinate (+ (cdr current-coordinate)
2419 (- table-cell-info-height old-height)))))
2420 ))
2421 ;; coord-list is now possibly invalid since some cells may have already
2422 ;; been heightened so recompute them by table--vertical-cell-list.
2423 (table--goto-coordinate current-coordinate)
2424 (setq coord-list (table--cell-list-to-coord-list (table--vertical-cell-list)))
2425 ;; push in the affected area above and below this table so that things
2426 ;; on the right side of the table are shifted horizontally neatly.
2427 (table--horizontally-shift-above-and-below (- n) (reverse coord-list))
2428 ;; finally narrow the frames for each cell.
2429 (let* ((below-list nil)
2430 (this-list coord-list)
2431 (above-list (cdr coord-list)))
2432 (while this-list
2433 (let* ((below (prog1 (car below-list) (setq below-list (if below-list (cdr below-list) coord-list))))
2434 (this (prog1 (car this-list) (setq this-list (cdr this-list))))
2435 (above (prog1 (car above-list) (setq above-list (cdr above-list)))))
2436 (delete-rectangle
2437 (table--goto-coordinate
2438 (cons (- (cadr this) n)
2439 (if (or (null above) (<= (cadr this) (cadr above)))
2440 (1- (cdar this))
2441 (cdar this))))
2442 (table--goto-coordinate
2443 (cons (cadr this)
2444 (if (or (null below) (< (cadr this) (cadr below)))
2445 (1+ (cddr this))
2446 (cddr this)))))))))
2447 (table--goto-coordinate current-coordinate)
2448 ;; re-recognize the current cell's new dimension
2449 (table-recognize-cell 'force)
2450 (message "")))
2451
2452;;;###autoload
2453(defun table-forward-cell (&optional arg no-recognize unrecognize)
2454 "Move point forward to the beginning of the next cell.
2455With argument ARG, do it ARG times;
2456a negative argument ARG = -N means move backward N cells.
2457Do not specify NO-RECOGNIZE and UNRECOGNIZE. They are for internal use only.
2458
2459Sample Cell Traveling Order (In Irregular Table Cases)
2460
2461You can actually try how it works in this buffer. Press
2462\\[table-recognize] and go to cells in the following tables and press
2463\\[table-forward-cell] or TAB key.
2464
2465+-----+--+ +--+-----+ +--+--+--+ +--+--+--+ +---------+ +--+---+--+
2466|0 |1 | |0 |1 | |0 |1 |2 | |0 |1 |2 | |0 | |0 |1 |2 |
2467+--+--+ | | +--+--+ +--+ | | | | +--+ +----+----+ +--+-+-+--+
2468|2 |3 | | | |2 |3 | |3 +--+ | | +--+3 | |1 |2 | |3 |4 |
2469| +--+--+ +--+--+ | +--+4 | | | |4 +--+ +--+-+-+--+ +----+----+
2470| |4 | |4 | | |5 | | | | | |5 | |3 |4 |5 | |5 |
2471+--+-----+ +-----+--+ +--+--+--+ +--+--+--+ +--+---+--+ +---------+
2472
2473+--+--+--+ +--+--+--+ +--+--+--+ +--+--+--+
2474|0 |1 |2 | |0 |1 |2 | |0 |1 |2 | |0 |1 |2 |
2475| | | | | +--+ | | | | | +--+ +--+
2476+--+ +--+ +--+3 +--+ | +--+ | |3 +--+4 |
2477|3 | |4 | |4 +--+5 | | |3 | | +--+5 +--+
2478| | | | | |6 | | | | | | |6 | |7 |
2479+--+--+--+ +--+--+--+ +--+--+--+ +--+--+--+
2480
2481+--+--+--+ +--+--+--+ +--+--+--+--+ +--+-----+--+ +--+--+--+--+
2482|0 |1 |2 | |0 |1 |2 | |0 |1 |2 |3 | |0 |1 |2 | |0 |1 |2 |3 |
2483| +--+ | | +--+ | | +--+--+ | | | | | | +--+--+ |
2484| |3 +--+ +--+3 | | +--+4 +--+ +--+ +--+ +--+4 +--+
2485+--+ |4 | |4 | +--+ |5 +--+--+6 | |3 +--+--+4 | |5 | |6 |
2486|5 +--+ | | +--+5 | | |7 |8 | | | |5 |6 | | | | | |
2487| |6 | | | |6 | | +--+--+--+--+ +--+--+--+--+ +--+-----+--+
2488+--+--+--+ +--+--+--+
2489"
2490 ;; After modifying this function, test against the above tables in
2491 ;; the doc string. It is quite tricky. The tables above do not
2492 ;; mean to cover every possible cases of cell layout, of course.
2493 ;; They are examples of tricky cases from implementation point of
2494 ;; view and provided for simple regression test purpose.
2495 (interactive "p")
2496 (or arg (setq arg 1))
2497 (table--finish-delayed-tasks)
2498 (while (null (zerop arg))
2499 (let* ((pivot (table--probe-cell 'abort-on-error))
2500 (cell pivot) edge tip)
2501 ;; go to the beginning of the first right/left cell with same height if exists
2502 (while (and (setq cell (table--goto-coordinate
2503 (cons (if (> arg 0) (1+ (car (table--get-coordinate (cdr cell))))
2504 (1- (car (table--get-coordinate (car cell)))))
2505 (cdr (table--get-coordinate (car pivot)))) 'no-extension))
2506 (setq cell (table--probe-cell))
2507 (/= (cdr (table--get-coordinate (car cell)))
2508 (cdr (table--get-coordinate (car pivot))))))
2509 (if cell (goto-char (car cell)) ; done
2510 ;; if the horizontal move fails search the most left/right edge cell below/above the pivot
2511 ;; but first find the edge cell
2512 (setq edge pivot)
2513 (while (and (table--goto-coordinate
2514 (cons (if (> arg 0) (1- (car (table--get-coordinate (car edge))))
2515 (1+ (car (table--get-coordinate (cdr edge)))))
2516 (cdr (table--get-coordinate (car pivot)))) 'no-extension)
2517 (setq cell (table--probe-cell))
2518 (setq edge cell)))
2519 (setq cell (if (> arg 0) edge
2520 (or (and (table--goto-coordinate
2521 (cons (car (table--get-coordinate (cdr edge)))
2522 (1- (cdr (table--get-coordinate (car edge))))))
2523 (table--probe-cell))
2524 edge)))
2525 ;; now search for the tip which is the highest/lowest below/above cell
2526 (while cell
2527 (let (below/above)
2528 (and (table--goto-coordinate
2529 (cons (car (table--get-coordinate (if (> arg 0) (car cell)
2530 (cdr cell))))
2531 (if (> arg 0) (+ 2 (cdr (table--get-coordinate (cdr cell))))
2532 (1- (cdr (table--get-coordinate (car pivot)))))) 'no-extension)
2533 (setq below/above (table--probe-cell))
2534 (or (null tip)
2535 (if (> arg 0)
2536 (< (cdr (table--get-coordinate (car below/above)))
2537 (cdr (table--get-coordinate (car tip))))
2538 (> (cdr (table--get-coordinate (car below/above)))
2539 (cdr (table--get-coordinate (car tip))))))
2540 (setq tip below/above)))
2541 (and (setq cell (table--goto-coordinate
2542 (cons (if (> arg 0) (1+ (car (table--get-coordinate (cdr cell))))
2543 (1- (car (table--get-coordinate (car cell)))))
2544 (if (> arg 0) (cdr (table--get-coordinate (car pivot)))
2545 (1- (cdr (table--get-coordinate (car pivot)))))) 'no-extension))
2546 (setq cell (table--probe-cell))))
2547 (if tip (goto-char (car tip)) ; done
2548 ;; let's climb up/down to the top/bottom from the edge
2549 (while (and (table--goto-coordinate
2550 (cons (if (> arg 0) (car (table--get-coordinate (car edge)))
2551 (car (table--get-coordinate (cdr edge))))
2552 (if (> arg 0) (1- (cdr (table--get-coordinate (car edge))))
2553 (+ 2 (cdr (table--get-coordinate (cdr edge)))))) 'no-extension)
2554 (setq cell (table--probe-cell))
2555 (setq edge cell)))
2556 (if (< arg 0)
2557 (progn
2558 (setq cell edge)
2559 (while (and (table--goto-coordinate
2560 (cons (1- (car (table--get-coordinate (car cell))))
2561 (cdr (table--get-coordinate (cdr cell)))) 'no-extension)
2562 (setq cell (table--probe-cell)))
2563 (if (> (cdr (table--get-coordinate (car cell)))
2564 (cdr (table--get-coordinate (car edge))))
2565 (setq edge cell)))))
2566 (goto-char (car edge))))) ; the top left cell
2567 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
2568 (unless no-recognize
2569 (table-recognize-cell 'force nil (if unrecognize -1 nil)))) ; refill the cache with new cell contents
2570
2571;;;###autoload
2572(defun table-backward-cell (&optional arg)
2573 "Move backward to the beginning of the previous cell.
2574With argument ARG, do it ARG times;
2575a negative argument ARG = -N means move forward N cells."
2576 (interactive "p")
2577 (or arg (setq arg 1))
2578 (table-forward-cell (- arg)))
2579
2580;;;###autoload
2581(defun table-span-cell (direction)
2582 "Span current cell into adjacent cell in DIRECTION.
2583DIRECTION is one of symbols; right, left, above or below."
2584 (interactive
2585 (list
2586 (let* ((dummy (barf-if-buffer-read-only))
2587 (direction-list
2588 (let* ((tmp (delete nil
2589 (mapcar (lambda (d)
2590 (if (table--cell-can-span-p d)
2591 (list (symbol-name d))))
2592 '(right left above below)))))
2593 (if (null tmp)
2594 (error "Can't span this cell"))
2595 tmp))
2596 (default-direction (if (member (list (car table-cell-span-direction-history)) direction-list)
2597 (car table-cell-span-direction-history)
2598 (caar direction-list)))
2599 (completion-ignore-case t))
2600 (intern (downcase (completing-read
2601 (format "Span into (default %s): " default-direction)
2602 direction-list
2603 nil t nil 'table-cell-span-direction-history default-direction))))))
2604 (unless (memq direction '(right left above below))
2605 (error "Invalid direction %s, must be right, left, above or below"
2606 (symbol-name direction)))
2607 (table-recognize-cell 'force)
2608 (unless (table--cell-can-span-p direction)
2609 (error "Can't span %s" (symbol-name direction)))
2610 ;; prepare beginning and ending positions of the border bar to strike through
2611 (let ((beg (cond
2612 ((eq direction 'right)
2613 (save-excursion
2614 (table--goto-coordinate
2615 (cons (car table-cell-info-rb-coordinate)
2616 (1- (cdr table-cell-info-lu-coordinate))) 'no-extension)))
2617 ((eq direction 'below)
2618 (save-excursion
2619 (table--goto-coordinate
2620 (cons (1- (car table-cell-info-lu-coordinate))
2621 (1+ (cdr table-cell-info-rb-coordinate))) 'no-extension)))
2622 (t
2623 (save-excursion
2624 (table--goto-coordinate
2625 (cons (1- (car table-cell-info-lu-coordinate))
2626 (1- (cdr table-cell-info-lu-coordinate))) 'no-extension)))))
2627 (end (cond
2628 ((eq direction 'left)
2629 (save-excursion
2630 (table--goto-coordinate
2631 (cons (car table-cell-info-lu-coordinate)
2632 (1+ (cdr table-cell-info-rb-coordinate))) 'no-extension)))
2633 ((eq direction 'above)
2634 (save-excursion
2635 (table--goto-coordinate
2636 (cons (1+ (car table-cell-info-rb-coordinate))
2637 (1- (cdr table-cell-info-lu-coordinate))) 'no-extension)))
2638 (t
2639 (save-excursion
2640 (table--goto-coordinate
2641 (cons (1+ (car table-cell-info-rb-coordinate))
2642 (1+ (cdr table-cell-info-rb-coordinate))) 'no-extension))))))
2643 ;; replace the bar with blank space while taking care of edges to be border or intersection
2644 (save-excursion
2645 (goto-char beg)
2646 (if (memq direction '(left right))
2647 (let* ((column (current-column))
2648 rectangle
2649 (n-element (- (length (extract-rectangle beg end)) 2))
2650 (above-contp (and (goto-char beg)
2651 (zerop (forward-line -1))
2652 (= (move-to-column column) column)
2653 (looking-at (regexp-quote (char-to-string table-cell-vertical-char)))))
2654 (below-contp (and (goto-char end)
2655 (progn (forward-char -1) t)
2656 (zerop (forward-line 1))
2657 (= (move-to-column column) column)
2658 (looking-at (regexp-quote (char-to-string table-cell-vertical-char))))))
2659 (setq rectangle
2660 (cons (if below-contp
2661 (char-to-string table-cell-intersection-char)
e99add21 2662 (substring table-cell-horizontal-chars 0 1))
238240c9
RS
2663 rectangle))
2664 (while (> n-element 0)
2665 (setq rectangle (cons (table--cell-blank-str 1) rectangle))
2666 (setq n-element (1- n-element)))
2667 (setq rectangle
2668 (cons (if above-contp
2669 (char-to-string table-cell-intersection-char)
e99add21 2670 (substring table-cell-horizontal-chars 0 1))
238240c9
RS
2671 rectangle))
2672 (delete-rectangle beg end)
2673 (goto-char beg)
2674 (table--insert-rectangle rectangle))
2675 (delete-region beg end)
2676 (insert (if (and (> (point) (point-min))
2677 (save-excursion
2678 (forward-char -1)
e99add21
JB
2679 (looking-at (regexp-opt-charset
2680 (string-to-list table-cell-horizontal-chars)))))
238240c9
RS
2681 table-cell-intersection-char
2682 table-cell-vertical-char)
2683 (table--cell-blank-str (- end beg 2))
e99add21
JB
2684 (if (looking-at (regexp-opt-charset
2685 (string-to-list table-cell-horizontal-chars)))
238240c9
RS
2686 table-cell-intersection-char
2687 table-cell-vertical-char))))
2688 ;; recognize the newly created spanned cell
2689 (table-recognize-cell 'force)
2690 (if (member direction '(right left))
2691 (table-with-cache-buffer
2692 (table--fill-region (point-min) (point-max))
2693 (setq table-inhibit-auto-fill-paragraph t)))))
2694
2695;;;###autoload
2696(defun table-split-cell-vertically ()
2697 "Split current cell vertically.
2698Creates a cell above and a cell below the current point location."
2699 (interactive "*")
2700 (table-recognize-cell 'force)
2701 (let ((point-y (cdr (table--get-coordinate))))
2702 (unless (table--cell-can-split-vertically-p)
2703 (error "Can't split here"))
2704 (let* ((old-coordinate (table--get-coordinate))
2705 (column (current-column))
2706 (beg (table--goto-coordinate
2707 (cons (1- (car table-cell-info-lu-coordinate))
2708 point-y)))
2709 (end (table--goto-coordinate
2710 (cons (1+ (car table-cell-info-rb-coordinate))
2711 point-y)))
2712 (line (buffer-substring (1+ beg) (1- end))))
2713 (when (= (cdr old-coordinate) (cdr table-cell-info-rb-coordinate))
2714 (table--goto-coordinate old-coordinate)
2715 (table-heighten-cell 1 'no-copy 'no-update))
2716 (goto-char beg)
2717 (delete-region beg end)
2718 (insert table-cell-intersection-char
e99add21 2719 (make-string table-cell-info-width (string-to-char table-cell-horizontal-chars))
238240c9
RS
2720 table-cell-intersection-char)
2721 (table--goto-coordinate old-coordinate)
2722 (forward-line 1)
2723 (move-to-column column)
2724 (setq old-coordinate (table--get-coordinate))
2725 (table-recognize-cell 'force)
2726 (unless (string-match "^\\s *$" line)
2727 (table-with-cache-buffer
2728 (goto-char (point-min))
2729 (insert line ?\n)
2730 (goto-char (point-min)) ;; don't heighten cell unnecessarily
2731 (setq table-inhibit-auto-fill-paragraph t)))
2732 (table--update-cell 'now) ;; can't defer this operation
2733 (table--goto-coordinate old-coordinate)
2734 (move-to-column column)
2735 (table-recognize-cell 'force))))
2736
2737;;;###autoload
2738(defun table-split-cell-horizontally ()
2739 "Split current cell horizontally.
2740Creates a cell on the left and a cell on the right of the current point location."
2741 (interactive "*")
2742 (table-recognize-cell 'force)
2743 (let* ((o-coordinate (table--get-coordinate))
2744 (point-x (car o-coordinate))
2745 cell-empty cell-contents cell-coordinate
2746 contents-to beg end rectangle strip-rect
2747 (right-edge (= (car o-coordinate) (1- (car table-cell-info-rb-coordinate)))))
2748 (unless (table--cell-can-split-horizontally-p)
2749 (error "Can't split here"))
2750 (let ((table-inhibit-update t))
2751 (table-with-cache-buffer
2752 (setq cell-coordinate (table--get-coordinate))
2753 (save-excursion
2754 (goto-char (point-min))
2755 (setq cell-empty (null (re-search-forward "\\S " nil t))))
2756 (setq cell-contents (buffer-substring (point-min) (point-max)))
2757 (setq table-inhibit-auto-fill-paragraph t)))
2758 (setq contents-to
2759 (if cell-empty 'left
2760 (let* ((completion-ignore-case t)
2761 (default (car table-cell-split-contents-to-history)))
2762 (intern
2763 (if (member 'click (event-modifiers last-input-event))
2764 (x-popup-menu last-input-event
2765 '("Existing cell contents to:"
2766 ("Title"
2767 ("Split" . "split") ("Left" . "left") ("Right" . "right"))))
2768 (downcase (completing-read
2769 (format "Existing cell contents to (default %s): " default)
2770 '(("split") ("left") ("right"))
2771 nil t nil 'table-cell-split-contents-to-history default)))))))
2772 (unless (eq contents-to 'split)
2773 (table-with-cache-buffer
2774 (erase-buffer)
2775 (setq table-inhibit-auto-fill-paragraph t)))
2776 (table--update-cell 'now)
2777 (setq beg (table--goto-coordinate
2778 (cons point-x
2779 (1- (cdr table-cell-info-lu-coordinate)))))
2780 (setq end (table--goto-coordinate
2781 (cons (1+ point-x)
2782 (1+ (cdr table-cell-info-rb-coordinate)))))
2783 (setq rectangle (cons (char-to-string table-cell-intersection-char) nil))
2784 (let ((n table-cell-info-height))
2785 (while (prog1 (> n 0) (setq n (1- n)))
2786 (setq rectangle (cons (char-to-string table-cell-vertical-char) rectangle))))
2787 (setq rectangle (cons (char-to-string table-cell-intersection-char) rectangle))
2788 (if (eq contents-to 'split)
2789 (setq strip-rect (extract-rectangle beg end)))
2790 (delete-rectangle beg end)
2791 (goto-char beg)
2792 (table--insert-rectangle rectangle)
2793 (table--goto-coordinate o-coordinate)
2794 (if cell-empty
2795 (progn
2796 (forward-char 1)
2797 (if right-edge
2798 (table-widen-cell 1)))
2799 (unless (eq contents-to 'left)
2800 (forward-char 1))
2801 (table-recognize-cell 'force)
2802 (table-with-cache-buffer
2803 (if (eq contents-to 'split)
2804 ;; split inserts strip-rect after removing
2805 ;; top and bottom borders
2806 (let ((o-coord (table--get-coordinate))
2807 (l (setq strip-rect (cdr strip-rect))))
2808 (while (cddr l) (setq l (cdr l)))
2809 (setcdr l nil)
2810 ;; insert the strip only when it is not a completely blank one
2811 (unless (let ((cl (mapcar (lambda (s) (string= s " ")) strip-rect)))
2812 (and (car cl)
2813 (table--uniform-list-p cl)))
2814 (goto-char (point-min))
2815 (table--insert-rectangle strip-rect)
2816 (table--goto-coordinate o-coord)))
2817 ;; left or right inserts original contents
2818 (erase-buffer)
2819 (insert cell-contents)
2820 (table--goto-coordinate cell-coordinate)
2821 (table--fill-region (point-min) (point-max))
2822 ;; avoid unnecessary vertical cell expansion
2823 (and (looking-at "\\s *\\'")
2824 (re-search-backward "\\S \\(\\s *\\)\\=" nil t)
2825 (goto-char (match-beginning 1))))
2826 ;; in either case do not fill paragraph
2827 (setq table-inhibit-auto-fill-paragraph t))
2828 (table--update-cell 'now)) ;; can't defer this operation
2829 (table-recognize-cell 'force)))
2830
2831;;;###autoload
2832(defun table-split-cell (orientation)
2833 "Split current cell in ORIENTATION.
2834ORIENTATION is a symbol either horizontally or vertically."
2835 (interactive
2836 (list
2837 (let* ((dummy (barf-if-buffer-read-only))
2838 (completion-ignore-case t)
2839 (default (car table-cell-split-orientation-history)))
2840 (intern (downcase (completing-read
2841 (format "Split orientation (default %s): " default)
2842 '(("horizontally") ("vertically"))
2843 nil t nil 'table-cell-split-orientation-history default))))))
2844 (unless (memq orientation '(horizontally vertically))
2845 (error "Invalid orientation %s, must be horizontally or vertically"
2846 (symbol-name orientation)))
2847 (if (eq orientation 'horizontally)
2848 (table-split-cell-horizontally)
2849 (table-split-cell-vertically)))
2850
2851;;;###autoload
2852(defun table-justify (what justify)
2853 "Justify contents of a cell, a row of cells or a column of cells.
2854WHAT is a symbol 'cell, 'row or 'column. JUSTIFY is a symbol 'left,
2855'center, 'right, 'top, 'middle, 'bottom or 'none."
2856 (interactive
2857 (list (let* ((dummy (barf-if-buffer-read-only))
2858 (completion-ignore-case t)
2859 (default (car table-target-history)))
2860 (intern (downcase (completing-read
2861 (format "Justify what (default %s): " default)
2862 '(("cell") ("row") ("column"))
2863 nil t nil 'table-target-history default))))
2864 (table--query-justification)))
2865 (funcall (intern (concat "table-justify-" (symbol-name what))) justify))
2866
2867;;;###autoload
2868(defun table-justify-cell (justify &optional paragraph)
2869 "Justify cell contents.
2870JUSTIFY is a symbol 'left, 'center or 'right for horizontal, or 'top,
2871'middle, 'bottom or 'none for vertical. When optional PARAGRAPH is
2872non-nil the justify operation is limited to the current paragraph,
2873otherwise the entire cell contents is justified."
2874 (interactive
2875 (list (table--query-justification)))
2876 (table--finish-delayed-tasks)
2877 (table-recognize-cell 'force)
2878 (table--justify-cell-contents justify paragraph))
2879
2880;;;###autoload
2881(defun table-justify-row (justify)
2882 "Justify cells of a row.
2883JUSTIFY is a symbol 'left, 'center or 'right for horizontal, or top,
2884'middle, 'bottom or 'none for vertical."
2885 (interactive
2886 (list (table--query-justification)))
2887 (let((cell-list (table--horizontal-cell-list nil nil 'top)))
2888 (table--finish-delayed-tasks)
2889 (save-excursion
2890 (while cell-list
2891 (let ((cell (car cell-list)))
2892 (setq cell-list (cdr cell-list))
2893 (goto-char (car cell))
2894 (table-recognize-cell 'force)
2895 (table--justify-cell-contents justify))))))
2896
2897;;;###autoload
2898(defun table-justify-column (justify)
2899 "Justify cells of a column.
2900JUSTIFY is a symbol 'left, 'center or 'right for horizontal, or top,
2901'middle, 'bottom or 'none for vertical."
2902 (interactive
2903 (list (table--query-justification)))
2904 (let((cell-list (table--vertical-cell-list nil nil 'left)))
2905 (table--finish-delayed-tasks)
2906 (save-excursion
2907 (while cell-list
2908 (let ((cell (car cell-list)))
2909 (setq cell-list (cdr cell-list))
2910 (goto-char (car cell))
2911 (table-recognize-cell 'force)
2912 (table--justify-cell-contents justify))))))
2913
2914;;;###autoload
2915(defun table-fixed-width-mode (&optional arg)
2916 "Toggle fixing width mode.
2917In the fixed width mode, typing inside a cell never changes the cell
2918width where in the normal mode the cell width expands automatically in
2919order to prevent a word being folded into multiple lines."
2920 (interactive "P")
2921 (table--finish-delayed-tasks)
2922 (setq table-fixed-width-mode
2923 (if (null arg)
2924 (not table-fixed-width-mode)
2925 (> (prefix-numeric-value arg) 0)))
238240c9
RS
2926 (table--update-cell-face))
2927
2928;;;###autoload
2929(defun table-query-dimension (&optional where)
2930 "Return the dimension of the current cell and the current table.
2931The result is a list (cw ch tw th c r cells) where cw is the cell
2932width, ch is the cell height, tw is the table width, th is the table
2933height, c is the number of columns, r is the number of rows and cells
2934is the total number of cells. The cell dimension excludes the cell
2935frame while the table dimension includes the table frame. The columns
2936and the rows are counted by the number of cell boundaries. Therefore
2937the number tends to be larger than it appears for the tables with
2938non-uniform cell structure (heavily spanned and split). When optional
2939WHERE is provided the cell and table at that location is reported."
2940 (interactive)
2941 (save-excursion
2942 (if where (goto-char where))
2943 (let ((starting-cell (table--probe-cell))
2944 cell table-lu table-rb col-list row-list (cells 0))
2945 (if (null starting-cell) nil
2946 (setq table-lu (car starting-cell))
2947 (setq table-rb (cdr starting-cell))
2948 (setq col-list (cons (car (table--get-coordinate (car starting-cell))) nil))
2949 (setq row-list (cons (cdr (table--get-coordinate (car starting-cell))) nil))
32226619 2950 (and (called-interactively-p 'interactive)
238240c9
RS
2951 (message "Computing cell dimension..."))
2952 (while
2953 (progn
2954 (table-forward-cell 1 t)
2955 (setq cells (1+ cells))
2956 (and (setq cell (table--probe-cell))
2957 (not (equal cell starting-cell))))
2958 (if (< (car cell) table-lu)
2959 (setq table-lu (car cell)))
2960 (if (> (cdr cell) table-rb)
2961 (setq table-rb (cdr cell)))
2962 (let ((lu-coordinate (table--get-coordinate (car cell))))
2963 (if (memq (car lu-coordinate) col-list) nil
2964 (setq col-list (cons (car lu-coordinate) col-list)))
2965 (if (memq (cdr lu-coordinate) row-list) nil
2966 (setq row-list (cons (cdr lu-coordinate) row-list)))))
2967 (let* ((cell-lu-coordinate (table--get-coordinate (car starting-cell)))
2968 (cell-rb-coordinate (table--get-coordinate (cdr starting-cell)))
2969 (table-lu-coordinate (table--get-coordinate table-lu))
2970 (table-rb-coordinate (table--get-coordinate table-rb))
2971 (cw (- (car cell-rb-coordinate) (car cell-lu-coordinate)))
2972 (ch (1+ (- (cdr cell-rb-coordinate) (cdr cell-lu-coordinate))))
2973 (tw (+ 2 (- (car table-rb-coordinate) (car table-lu-coordinate))))
2974 (th (+ 3 (- (cdr table-rb-coordinate) (cdr table-lu-coordinate))))
2975 (c (length col-list))
2976 (r (length row-list)))
32226619 2977 (and (called-interactively-p 'interactive)
238240c9
RS
2978 (message "Cell: (%dw, %dh), Table: (%dw, %dh), Dim: (%dc, %dr), Total Cells: %d" cw ch tw th c r cells))
2979 (list cw ch tw th c r cells))))))
2980
2981;;;###autoload
2982(defun table-generate-source (language &optional dest-buffer caption)
2983 "Generate source of the current table in the specified language.
2984LANGUAGE is a symbol that specifies the language to describe the
2985structure of the table. It must be either 'html, 'latex or 'cals.
2986The resulted source text is inserted into DEST-BUFFER and the buffer
2987object is returned. When DEST-BUFFER is omitted or nil the default
2988buffer specified in `table-dest-buffer-name' is used. In this case
2989the content of the default buffer is erased prior to the generation.
2990When DEST-BUFFER is non-nil it is expected to be either a destination
2991buffer or a name of the destination buffer. In this case the
2992generated result is inserted at the current point in the destination
2993buffer and the previously existing contents in the buffer are
2994untouched.
2995
2996References used for this implementation:
2997
2998HTML:
855b42a2 2999 URL `http://www.w3.org'
238240c9
RS
3000
3001LaTeX:
855b42a2 3002 URL `http://www.maths.tcd.ie/~dwilkins/LaTeXPrimer/Tables.html'
238240c9
RS
3003
3004CALS (DocBook DTD):
855b42a2
GM
3005 URL `http://www.oasis-open.org/html/a502.htm'
3006 URL `http://www.oreilly.com/catalog/docbook/chapter/book/table.html#AEN114751'
238240c9
RS
3007"
3008 (interactive
3009 (let* ((dummy (unless (table--probe-cell) (error "Table not found here")))
3010 (completion-ignore-case t)
3011 (default (car table-source-language-history))
3012 (language (downcase (completing-read
3013 (format "Language (default %s): " default)
3014 (mapcar (lambda (s) (list (symbol-name s)))
3015 table-source-languages)
3016 nil t nil 'table-source-language-history default))))
3017 (list
3018 (intern language)
3019 (read-buffer "Destination buffer: " (concat table-dest-buffer-name "." language))
3020 (table--read-from-minibuffer '("Table Caption" . table-source-caption-history)))))
3021 (let ((default-buffer-name (concat table-dest-buffer-name "." (symbol-name language))))
32226619
JB
3022 (unless (or (called-interactively-p 'interactive) (table--probe-cell))
3023 (error "Table not found here"))
238240c9
RS
3024 (unless (bufferp dest-buffer)
3025 (setq dest-buffer (get-buffer-create (or dest-buffer default-buffer-name))))
3026 (if (string= (buffer-name dest-buffer) default-buffer-name)
3027 (with-current-buffer dest-buffer
3028 (erase-buffer)))
3029 (save-excursion
3030 (let ((starting-cell (table--probe-cell))
3031 cell origin-cell tail-cell col-list row-list (n 0) i)
3032 ;; first analyze the table structure and prepare:
3033 ;; 1. origin cell (left up corner cell)
3034 ;; 2. tail cell (right bottom corner cell)
3035 ;; 3. column boundary list
3036 ;; 4. row boundary list
3037 (setq origin-cell starting-cell)
3038 (setq tail-cell starting-cell)
3039 (setq col-list (cons (car (table--get-coordinate (car starting-cell))) nil))
3040 (setq row-list (cons (cdr (table--get-coordinate (car starting-cell))) nil))
3041 (setq i 0)
4fb81250 3042 (let ((wheel [?- ?\\ ?| ?/]))
238240c9
RS
3043 (while
3044 (progn
32226619 3045 (if (called-interactively-p 'interactive)
238240c9
RS
3046 (progn
3047 (message "Analyzing table...%c" (aref wheel i))
3048 (if (eq (setq i (1+ i)) (length wheel))
3049 (setq i 0))
3050 (setq n (1+ n))))
3051 (table-forward-cell 1 t)
3052 (and (setq cell (table--probe-cell))
3053 (not (equal cell starting-cell))))
3054 (if (< (car cell) (car origin-cell))
3055 (setq origin-cell cell))
3056 (if (> (cdr cell) (cdr tail-cell))
3057 (setq tail-cell cell))
3058 (let ((lu-coordinate (table--get-coordinate (car cell))))
3059 (unless (memq (car lu-coordinate) col-list)
3060 (setq col-list (cons (car lu-coordinate) col-list)))
3061 (unless (memq (cdr lu-coordinate) row-list)
3062 (setq row-list (cons (cdr lu-coordinate) row-list))))))
3063 (setq col-list (sort col-list '<))
3064 (setq row-list (sort row-list '<))
3065 (message "Generating source...")
3066 ;; clear the source generation property list
3067 (setplist 'table-source-info-plist nil)
3068 ;; prepare to start from the origin cell
3069 (goto-char (car origin-cell))
3070 ;; first put some header information
3071 (table--generate-source-prologue dest-buffer language caption col-list row-list)
3072 (cond
3073 ((eq language 'latex)
3074 ;; scan by character lines
3075 (table--generate-source-scan-lines dest-buffer language origin-cell tail-cell col-list row-list))
3076 (t
3077 ;; scan by table cells
3078 (table--generate-source-scan-rows dest-buffer language origin-cell col-list row-list)))
3079 ;; insert closing
3080 (table--generate-source-epilogue dest-buffer language col-list row-list))
3081 ;; lastly do some convenience work
32226619 3082 (if (called-interactively-p 'interactive)
238240c9
RS
3083 (save-selected-window
3084 (pop-to-buffer dest-buffer t)
3085 (goto-char (point-min))
3086 (and (string= (buffer-name dest-buffer) default-buffer-name)
3087 (buffer-file-name dest-buffer)
3088 (save-buffer))
3089 (message "Generating source...done")
3090 (let ((mode
3091 (if (memq language '(cals)) 'sgml-mode
3092 (intern (concat (symbol-name language) "-mode")))))
3093 (if (fboundp mode)
3094 (call-interactively mode)))
3095 )))
3096 dest-buffer))
3097
3098(defun table--generate-source-prologue (dest-buffer language caption col-list row-list)
3099 "Generate and insert source prologue into DEST-BUFFER."
3100 (with-current-buffer dest-buffer
3101 (cond
3102 ((eq language 'html)
3103 (insert (format "<!-- This HTML table template is generated by emacs %s -->\n" emacs-version)
e66ca63c 3104 (format "<table %s>\n" table-html-table-attribute)
238240c9
RS
3105 (if (and (stringp caption)
3106 (not (string= caption "")))
e66ca63c 3107 (format " <caption>%s</caption>\n" caption)
238240c9
RS
3108 "")))
3109 ((eq language 'latex)
3110 (insert (format "%% This LaTeX table template is generated by emacs %s\n" emacs-version)
3111 "\\begin{tabular}{|" (apply 'concat (make-list (length col-list) "l|")) "}\n"
3112 "\\hline\n"))
3113 ((eq language 'cals)
3114 (insert (format "<!-- This CALS table template is generated by emacs %s -->\n" emacs-version)
3115 "<table frame=\"all\">\n")
3116 (if (and (stringp caption)
3117 (not (string= caption "")))
3118 (insert " <title>" caption "</title>\n"))
3119 (insert (format " <tgroup cols=\"%d\" align=\"left\" colsep=\"1\" rowsep=\"1\">\n" (length col-list)))
3120 (table-put-source-info 'colspec-marker (point-marker))
3121 (table-put-source-info 'row-type (if (zerop table-cals-thead-rows) "tbody" "thead"))
3122 (set-marker-insertion-type (table-get-source-info 'colspec-marker) nil) ;; insert after
3123 (insert (format " <%s valign=\"top\">\n" (table-get-source-info 'row-type))))
3124 )))
3125
3126(defun table--generate-source-epilogue (dest-buffer language col-list row-list)
3127 "Generate and insert source epilogue into DEST-BUFFER."
3128 (with-current-buffer dest-buffer
3129 (cond
3130 ((eq language 'html)
e66ca63c 3131 (insert "</table>\n"))
238240c9
RS
3132 ((eq language 'latex)
3133 (insert "\\end{tabular}\n"))
3134 ((eq language 'cals)
3135 (set-marker-insertion-type (table-get-source-info 'colspec-marker) t) ;; insert before
3136 (save-excursion
3137 (goto-char (table-get-source-info 'colspec-marker))
4e454e5b 3138 (mapc
238240c9
RS
3139 (lambda (col)
3140 (insert (format " <colspec colnum=\"%d\" colname=\"c%d\"/>\n" col col)))
3141 (sort (table-get-source-info 'colnum-list) '<)))
3142 (insert (format " </%s>\n </tgroup>\n</table>\n" (table-get-source-info 'row-type))))
3143 )))
3144
3145(defun table--generate-source-scan-rows (dest-buffer language origin-cell col-list row-list)
3146 "Generate and insert source rows into DEST-BUFFER."
3147 (table-put-source-info 'current-row 1)
3148 (while row-list
3149 (with-current-buffer dest-buffer
3150 (cond
3151 ((eq language 'html)
e66ca63c 3152 (insert " <tr>\n"))
238240c9
RS
3153 ((eq language 'cals)
3154 (insert " <row>\n"))
3155 ))
3156 (table--generate-source-cells-in-a-row dest-buffer language col-list row-list)
3157 (with-current-buffer dest-buffer
3158 (cond
3159 ((eq language 'html)
e66ca63c 3160 (insert " </tr>\n"))
238240c9
RS
3161 ((eq language 'cals)
3162 (insert " </row>\n")
3163 (unless (/= (table-get-source-info 'current-row) table-cals-thead-rows)
db95369b 3164 (insert (format " </%s>\n" (table-get-source-info 'row-type)))
238240c9
RS
3165 (insert (format " <%s valign=\"top\">\n" (table-put-source-info 'row-type "tbody")))))))
3166 (table-put-source-info 'current-row (1+ (table-get-source-info 'current-row)))
3167 (setq row-list (cdr row-list))))
3168
3169(defun table--generate-source-cells-in-a-row (dest-buffer language col-list row-list)
3170 "Generate and insert source cells into DEST-BUFFER."
3171 (table-put-source-info 'current-column 1)
3172 (while col-list
3173 (let* ((cell (table--probe-cell))
3174 (lu (table--get-coordinate (car cell)))
3175 (rb (table--get-coordinate (cdr cell)))
3176 (alignment (table--get-cell-justify-property cell))
3177 (valign (table--get-cell-valign-property cell))
3178 (row-list row-list)
3179 (colspan 1)
3180 (rowspan 1))
3181 (if (< (car lu) (car col-list))
3182 (setq col-list nil)
3183 (while (and col-list
3184 (> (car lu) (car col-list)))
3185 (setq col-list (cdr col-list))
3186 (table-put-source-info 'current-column (1+ (table-get-source-info 'current-column))))
3187 (setq col-list (cdr col-list))
3188 (table-put-source-info 'next-column (1+ (table-get-source-info 'current-column)))
3189 (while (and col-list
3190 (> (1+ (car rb)) (car col-list)))
3191 (setq colspan (1+ colspan))
3192 (setq col-list (cdr col-list))
3193 (table-put-source-info 'next-column (1+ (table-get-source-info 'next-column))))
3194 (setq row-list (cdr row-list))
3195 (while (and row-list
3196 (> (+ (cdr rb) 2) (car row-list)))
3197 (setq rowspan (1+ rowspan))
3198 (setq row-list (cdr row-list)))
3199 (with-current-buffer dest-buffer
3200 (cond
3201 ((eq language 'html)
3202 (insert (format " <%s"
3203 (table-put-source-info
3204 'cell-type
3205 (if (or (<= (table-get-source-info 'current-row) table-html-th-rows)
3206 (<= (table-get-source-info 'current-column) table-html-th-columns))
e66ca63c 3207 "th" "td"))))
238240c9
RS
3208 (if (and table-html-cell-attribute (not (string= table-html-cell-attribute "")))
3209 (insert " " table-html-cell-attribute))
3210 (if (> colspan 1) (insert (format " colspan=\"%d\"" colspan)))
3211 (if (> rowspan 1) (insert (format " rowspan=\"%d\"" rowspan)))
3212 (insert (format " align=\"%s\"" (if alignment (symbol-name alignment) "left")))
3213 (insert (format " valign=\"%s\"" (if valign (symbol-name valign) "top")))
3214 (insert ">\n"))
3215 ((eq language 'cals)
3216 (insert " <entry")
3217 (if (> colspan 1)
3218 (let ((scol (table-get-source-info 'current-column))
3219 (ecol (+ (table-get-source-info 'current-column) colspan -1)))
4e454e5b
JB
3220 (mapc (lambda (col)
3221 (unless (memq col (table-get-source-info 'colnum-list))
3222 (table-put-source-info 'colnum-list
3223 (cons col (table-get-source-info 'colnum-list)))))
3224 (list scol ecol))
238240c9
RS
3225 (insert (format " namest=\"c%d\" nameend=\"c%d\"" scol ecol))))
3226 (if (> rowspan 1) (insert (format " morerows=\"%d\"" (1- rowspan))))
3227 (if (and alignment
3228 (not (memq alignment '(left none))))
3229 (insert " align=\"" (symbol-name alignment) "\""))
3230 (if (and valign
3231 (not (memq valign '(top none))))
3232 (insert " valign=\"" (symbol-name valign) "\""))
3233 (insert ">\n"))
3234 ))
3235 (table--generate-source-cell-contents dest-buffer language cell)
3236 (with-current-buffer dest-buffer
3237 (cond
3238 ((eq language 'html)
3239 (insert (format" </%s>\n" (table-get-source-info 'cell-type))))
3240 ((eq language 'cals)
3241 (insert " </entry>\n"))
3242 ))
3243 (table-forward-cell 1 t)
3244 (table-put-source-info 'current-column (table-get-source-info 'next-column))
3245 ))))
3246
3247(defun table--generate-source-cell-contents (dest-buffer language cell)
3248 "Generate and insert source cell contents of a CELL into DEST-BUFFER."
3249 (let ((cell-contents (extract-rectangle (car cell) (cdr cell))))
3250 (with-temp-buffer
3251 (table--insert-rectangle cell-contents)
3252 (table--remove-cell-properties (point-min) (point-max))
3253 (goto-char (point-min))
3254 (cond
3255 ((eq language 'html)
3256 (if table-html-delegate-spacing-to-user-agent
3257 (progn
3258 (table--remove-eol-spaces (point-min) (point-max))
3259 (if (re-search-forward "\\s +\\'" nil t)
3260 (replace-match "")))
3261 (while (search-forward " " nil t)
3262 (replace-match "&nbsp;"))
3263 (goto-char (point-min))
3264 (while (and (re-search-forward "$" nil t)
3265 (not (eobp)))
e66ca63c 3266 (insert "<br />")
238240c9
RS
3267 (forward-char 1)))
3268 (unless (and table-html-delegate-spacing-to-user-agent
3269 (progn
3270 (goto-char (point-min))
3271 (looking-at "\\s *\\'")))))
3272 ((eq language 'cals)
3273 (table--remove-eol-spaces (point-min) (point-max))
3274 (if (re-search-forward "\\s +\\'" nil t)
3275 (replace-match "")))
3276 )
3277 (setq cell-contents (buffer-substring (point-min) (point-max))))
3278 (with-current-buffer dest-buffer
3279 (let ((beg (point)))
3280 (insert cell-contents)
3281 (indent-rigidly beg (point)
3282 (cond
3283 ((eq language 'html) 6)
3284 ((eq language 'cals) 10)))
3285 (insert ?\n)))))
3286
e99add21
JB
3287(defun table--cell-horizontal-char-p (c)
3288 "Test if character C is one of the horizontal characters"
3289 (memq c (string-to-list table-cell-horizontal-chars)))
3290
238240c9
RS
3291(defun table--generate-source-scan-lines (dest-buffer language origin-cell tail-cell col-list row-list)
3292 "Scan the table line by line.
3293Currently this method is for LaTeX only."
3294 (let* ((lu-coord (table--get-coordinate (car origin-cell)))
3295 (rb-coord (table--get-coordinate (cdr tail-cell)))
3296 (x0 (car lu-coord))
3297 (x1 (car rb-coord))
3298 (y (cdr lu-coord))
3299 (y1 (cdr rb-coord)))
3300 (while (<= y y1)
3301 (let* ((border-p (memq (1+ y) row-list))
3302 (border-char-list
3303 (mapcar (lambda (x)
3304 (if border-p (char-after (table--goto-coordinate (cons x y)))
3305 (char-before (table--goto-coordinate (cons x y)))))
3306 col-list))
3307 start i c)
3308 (if border-p
3309 ;; horizontal cell border processing
e99add21 3310 (if (and (table--cell-horizontal-char-p (car border-char-list))
238240c9
RS
3311 (table--uniform-list-p border-char-list))
3312 (with-current-buffer dest-buffer
3313 (insert "\\hline\n"))
3314 (setq i 0)
3315 (while (setq c (nth i border-char-list))
e99add21 3316 (if (and start (not (table--cell-horizontal-char-p c)))
238240c9
RS
3317 (progn
3318 (with-current-buffer dest-buffer
3319 (insert (format "\\cline{%d-%d}\n" (1+ start) i)))
3320 (setq start nil)))
e99add21 3321 (if (and (not start) (table--cell-horizontal-char-p c))
238240c9
RS
3322 (setq start i))
3323 (setq i (1+ i)))
3324 (if start
3325 (with-current-buffer dest-buffer
3326 (insert (format "\\cline{%d-%d}\n" (1+ start) i)))))
3327 ;; horizontal cell contents processing
3328 (let* ((span 1) ;; spanning length
3329 (first-p t) ;; first in a row
3330 (insert-column ;; a function that processes one column/multicolumn
3331 (function
3332 (lambda (from to)
3333 (let ((line (table--buffer-substring-and-trim
3334 (table--goto-coordinate (cons from y))
3335 (table--goto-coordinate (cons to y)))))
3336 ;; escape special characters
3337 (with-temp-buffer
3338 (insert line)
3339 (goto-char (point-min))
3340 (while (re-search-forward "\\([#$~_^%{}]\\)\\|\\(\\\\\\)\\|\\([<>|]\\)" nil t)
3341 (if (match-beginning 1)
3342 (save-excursion
3343 (goto-char (match-beginning 1))
3344 (insert "\\"))
3345 (if (match-beginning 2)
3346 (replace-match "$\\backslash$" t t)
3347 (replace-match (concat "$" (match-string 3) "$")) t t)))
3348 (setq line (buffer-substring (point-min) (point-max))))
3349 ;; insert a column separator and column/multicolumn contents
3350 (with-current-buffer dest-buffer
3351 (unless first-p
ec85195e 3352 (insert (if (eq (char-before) ?\s) "" " ") "& "))
238240c9
RS
3353 (if (> span 1)
3354 (insert (format "\\multicolumn{%d}{%sl|}{%s}" span (if first-p "|" "") line))
3355 (insert line)))
3356 (setq first-p nil)
3357 (setq span 1)
3358 (setq start (nth i col-list)))))))
3359 (setq start x0)
3360 (setq i 1)
3361 (while (setq c (nth i border-char-list))
3362 (if (eq c table-cell-vertical-char)
3363 (funcall insert-column start (1- (nth i col-list)))
3364 (setq span (1+ span)))
3365 (setq i (1+ i)))
3366 (funcall insert-column start x1))
3367 (with-current-buffer dest-buffer
ec85195e 3368 (insert (if (eq (char-before) ?\s) "" " ") "\\\\\n"))))
238240c9
RS
3369 (setq y (1+ y)))
3370 (with-current-buffer dest-buffer
3371 (insert "\\hline\n"))
3372 ))
3373
3374;;;###autoload
3375(defun table-insert-sequence (str n increment interval justify)
3376 "Travel cells forward while inserting a specified sequence string in each cell.
3377STR is the base string from which the sequence starts. When STR is an
3378empty string then each cell content is erased. When STR ends with
3379numerical characters (they may optionally be surrounded by a pair of
3380parentheses) they are incremented as a decimal number. Otherwise the
3381last character in STR is incremented in ASCII code order. N is the
3382number of sequence elements to insert. When N is negative the cell
3383traveling direction is backward. When N is zero it travels forward
3384entire table. INCREMENT is the increment between adjacent sequence
3385elements and can be a negative number for effectively decrementing.
3386INTERVAL is the number of cells to travel between sequence element
3387insertion which is normally 1. When zero or less is given for
3388INTERVAL it is interpreted as number of cells per row so that sequence
3389is placed straight down vertically as long as the table's cell
3390structure is uniform. JUSTIFY is one of the symbol 'left, 'center or
3391'right, that specifies justification of the inserted string.
3392
3393Example:
3394
3395 (progn
3396 (table-insert 16 3 5 1)
3397 (table-forward-cell 15)
3398 (table-insert-sequence \"D0\" -16 1 1 'center)
3399 (table-forward-cell 16)
3400 (table-insert-sequence \"A[0]\" -16 1 1 'center)
3401 (table-forward-cell 1)
3402 (table-insert-sequence \"-\" 16 0 1 'center))
3403
3404 (progn
3405 (table-insert 16 8 5 1)
3406 (table-insert-sequence \"@\" 0 1 2 'right)
3407 (table-forward-cell 1)
3408 (table-insert-sequence \"64\" 0 1 2 'left))
3409"
3410 (interactive
3411 (progn
3412 (barf-if-buffer-read-only)
3413 (unless (table--probe-cell) (error "Table not found here"))
3414 (list (read-from-minibuffer
3415 "Sequence base string: " (car table-sequence-string-history) nil nil 'table-sequence-string-history)
3416 (string-to-number
3417 (table--read-from-minibuffer
3418 '("How many elements (0: maximum, negative: backward traveling)" . table-sequence-count-history)))
3419 (string-to-number
3420 (table--read-from-minibuffer
3421 '("Increment element by" . table-sequence-increment-history)))
3422 (string-to-number
3423 (table--read-from-minibuffer
3424 '("Cell interval (0: vertical, 1:horizontal)" . table-sequence-interval-history)))
3425 (let* ((completion-ignore-case t)
3426 (default (car table-sequence-justify-history)))
3427 (intern (downcase (completing-read
3428 (format "Justify (default %s): " default)
3429 '(("left") ("center") ("right"))
3430 nil t nil 'table-sequence-justify-history default)))))))
32226619
JB
3431 (unless (or (called-interactively-p 'interactive) (table--probe-cell))
3432 (error "Table not found here"))
238240c9 3433 (string-match "\\([0-9]*\\)\\([]})>]*\\)\\'" str)
32226619 3434 (if (called-interactively-p 'interactive)
238240c9
RS
3435 (message "Sequencing..."))
3436 (let* ((prefix (substring str 0 (match-beginning 1)))
3437 (index (match-string 1 str))
3438 (fmt (format "%%%s%dd" (if (eq (string-to-char index) ?0) "0" "") (length index)))
3439 (postfix (match-string 2 str))
3440 (dim (table-query-dimension))
3441 (cells (nth 6 dim))
3442 (direction (if (< n 0) -1 1))
3443 (interval-count 0))
3444 (if (string= index "")
3445 (progn
3446 (setq index nil)
3447 (if (string= prefix "")
3448 (setq prefix nil)))
3449 (setq index (string-to-number index)))
3450 (if (< n 0) (setq n (- n)))
3451 (if (or (zerop n) (> n cells)) (setq n cells))
3452 (if (< interval 0) (setq interval (- interval)))
3453 (if (zerop interval) (setq interval (nth 4 dim)))
3454 (save-excursion
3455 (while (progn
3456 (if (> interval-count 0) nil
3457 (setq interval-count interval)
3458 (table-with-cache-buffer
3459 (goto-char (point-min))
3460 (if (not (or prefix index))
3461 (erase-buffer)
3462 (insert prefix)
3463 (if index (insert (format fmt index)))
3464 (insert postfix)
3465 (table--fill-region (point-min) (point) table-cell-info-width justify)
3466 (setq table-cell-info-justify justify))
3467 (setq table-inhibit-auto-fill-paragraph t))
3468 (table--update-cell 'now)
3469 (if index
3470 (setq index (+ index increment))
3471 (if (and prefix (string= postfix ""))
3472 (let ((len-1 (1- (length prefix))))
3473 (setq prefix (concat (substring prefix 0 len-1)
3474 (char-to-string
3475 (+ (string-to-char (substring prefix len-1)) increment)))))))
3476 (setq n (1- n)))
3477 (table-forward-cell direction t)
3478 (setq interval-count (1- interval-count))
3479 (setq cells (1- cells))
3480 (and (> n 0) (> cells 0)))))
3481 (table-recognize-cell 'force)
32226619 3482 (if (called-interactively-p 'interactive)
238240c9
RS
3483 (message "Sequencing...done"))
3484 ))
3485
3486;;;###autoload
3487(defun table-delete-row (n)
3488 "Delete N row(s) of cells.
3489Delete N rows of cells from current row. The current row is the row
3490contains the current cell where point is located. Each row must
3491consists from cells of same height."
3492 (interactive "*p")
3493 (let ((orig-coord (table--get-coordinate))
3494 (bt-coord (table--get-coordinate (cdr (table--vertical-cell-list nil 'first-only))))
3495 lu-coord rb-coord rect)
3496 ;; determine the area to delete while testing row height uniformity
3497 (while (> n 0)
3498 (setq n (1- n))
3499 (unless (table--probe-cell)
3500 (error "Table not found"))
3501 (let ((cell-list (table--horizontal-cell-list 'left-to-right)))
3502 (unless
3503 (and (table--uniform-list-p
3504 (mapcar (lambda (cell) (cdr (table--get-coordinate (car cell)))) cell-list))
3505 (table--uniform-list-p
3506 (mapcar (lambda (cell) (cdr (table--get-coordinate (cdr cell)))) cell-list)))
3507 (error "Cells in this row are not in uniform height"))
3508 (unless lu-coord
3509 (setq lu-coord (table--get-coordinate (caar cell-list))))
3510 (setq rb-coord (table--get-coordinate (cdar (last cell-list))))
3511 (table--goto-coordinate (cons (car orig-coord) (+ 2 (cdr rb-coord))))))
3512 ;; copy the remaining area (below the deleting area)
3513 (setq rect (extract-rectangle
3514 (table--goto-coordinate (cons (1- (car lu-coord)) (1+ (cdr rb-coord))))
3515 (table--goto-coordinate (cons (1+ (car rb-coord)) (1+ (cdr bt-coord))))))
3516 ;; delete the deleting area and below together
3517 (delete-rectangle
3518 (table--goto-coordinate (cons (1- (car lu-coord)) (1- (cdr lu-coord))))
3519 (table--goto-coordinate (cons (1+ (car rb-coord)) (1+ (cdr bt-coord)))))
3520 (table--goto-coordinate (cons (1- (car lu-coord)) (1- (cdr lu-coord))))
3521 ;; insert the remaining area while appending blank lines below it
3522 (table--insert-rectangle
3523 (append rect (make-list (+ 2 (- (cdr rb-coord) (cdr lu-coord)))
ec85195e 3524 (make-string (+ 2 (- (car rb-coord) (car lu-coord))) ?\s))))
238240c9
RS
3525 ;; remove the appended blank lines below the table if they are unnecessary
3526 (table--goto-coordinate (cons 0 (- (cdr bt-coord) (- (cdr rb-coord) (cdr lu-coord)))))
3527 (table--remove-blank-lines (+ 2 (- (cdr rb-coord) (cdr lu-coord))))
3528 ;; fix up intersections
3529 (let ((coord (cons (car lu-coord) (1- (cdr lu-coord))))
3530 (n (1+ (- (car rb-coord) (car lu-coord)))))
3531 (while (> n 0)
3532 (table--goto-coordinate coord)
3533 (if (save-excursion
3534 (or (and (table--goto-coordinate (cons (car coord) (1- (cdr coord))) 'no-extension)
3535 (looking-at (regexp-quote (char-to-string table-cell-vertical-char))))
3536 (and (table--goto-coordinate (cons (car coord) (1+ (cdr coord))) 'no-extension)
3537 (looking-at (regexp-quote (char-to-string table-cell-vertical-char))))))
3538 (progn
3539 (delete-char 1)
3540 (insert table-cell-intersection-char))
3541 (delete-char 1)
e99add21 3542 (insert (string-to-char table-cell-horizontal-chars)))
238240c9
RS
3543 (setq n (1- n))
3544 (setcar coord (1+ (car coord)))))
3545 ;; goto appropriate end point
3546 (table--goto-coordinate (cons (car orig-coord) (cdr lu-coord)))))
3547
3548;;;###autoload
3549(defun table-delete-column (n)
3550 "Delete N column(s) of cells.
3551Delete N columns of cells from current column. The current column is
3552the column contains the current cell where point is located. Each
3553column must consists from cells of same width."
3554 (interactive "*p")
3555 (let ((orig-coord (table--get-coordinate))
3556 lu-coord rb-coord)
3557 ;; determine the area to delete while testing column width uniformity
3558 (while (> n 0)
3559 (setq n (1- n))
3560 (unless (table--probe-cell)
3561 (error "Table not found"))
3562 (let ((cell-list (table--vertical-cell-list 'top-to-bottom)))
3563 (unless
3564 (and (table--uniform-list-p
3565 (mapcar (function (lambda (cell) (car (table--get-coordinate (car cell))))) cell-list))
3566 (table--uniform-list-p
3567 (mapcar (function (lambda (cell) (car (table--get-coordinate (cdr cell))))) cell-list)))
3568 (error "Cells in this column are not in uniform width"))
3569 (unless lu-coord
3570 (setq lu-coord (table--get-coordinate (caar cell-list))))
3571 (setq rb-coord (table--get-coordinate (cdar (last cell-list))))
3572 (table--goto-coordinate (cons (1+ (car rb-coord)) (cdr orig-coord)))))
3573 ;; delete the area
3574 (delete-rectangle
3575 (table--goto-coordinate (cons (car lu-coord) (1- (cdr lu-coord))))
3576 (table--goto-coordinate (cons (1+ (car rb-coord)) (1+ (cdr rb-coord)))))
3577 ;; fix up the intersections
3578 (let ((coord (cons (1- (car lu-coord)) (cdr lu-coord)))
3579 (n (1+ (- (cdr rb-coord) (cdr lu-coord)))))
3580 (while (> n 0)
3581 (table--goto-coordinate coord)
3582 (if (save-excursion
3583 (or (and (table--goto-coordinate (cons (1- (car coord)) (cdr coord)) 'no-extension)
e99add21
JB
3584 (looking-at (regexp-opt-charset
3585 (string-to-list table-cell-horizontal-chars))))
238240c9 3586 (and (table--goto-coordinate (cons (1+ (car coord)) (cdr coord)) 'no-extension)
e99add21
JB
3587 (looking-at (regexp-opt-charset
3588 (string-to-list table-cell-horizontal-chars))))))
238240c9
RS
3589 (progn
3590 (delete-char 1)
3591 (insert table-cell-intersection-char))
3592 (delete-char 1)
3593 (insert table-cell-vertical-char))
3594 (setq n (1- n))
3595 (setcdr coord (1+ (cdr coord)))))
3596 ;; goto appropriate end point
3597 (table--goto-coordinate (cons (car lu-coord) (cdr orig-coord)))))
3598
3599;;;###autoload
3600(defun table-capture (beg end &optional col-delim-regexp row-delim-regexp justify min-cell-width columns)
3601 "Convert plain text into a table by capturing the text in the region.
3602Create a table with the text in region as cell contents. BEG and END
3603specify the region. The text in the region is replaced with a table.
3604The removed text is inserted in the table. When optional
3605COL-DELIM-REGEXP and ROW-DELIM-REGEXP are provided the region contents
3606is parsed and separated into individual cell contents by using the
3607delimiter regular expressions. This parsing determines the number of
3608columns and rows of the table automatically. If COL-DELIM-REGEXP and
3609ROW-DELIM-REGEXP are omitted the result table has only one cell and
3610the entire region contents is placed in that cell. Optional JUSTIFY
3611is one of 'left, 'center or 'right, which specifies the cell
3612justification. Optional MIN-CELL-WIDTH specifies the minimum cell
3613width. Optional COLUMNS specify the number of columns when
3614ROW-DELIM-REGEXP is not specified.
3615
3616
3617Example 1:
3618
36191, 2, 3, 4
36205, 6, 7, 8
3621, 9, 10
3622
3623Running `table-capture' on above 3 line region with COL-DELIM-REGEXP
3624\",\" and ROW-DELIM-REGEXP \"\\n\" creates the following table. In
3625this example the cells are centered and minimum cell width is
3626specified as 5.
3627
3628+-----+-----+-----+-----+
3629| 1 | 2 | 3 | 4 |
3630+-----+-----+-----+-----+
3631| 5 | 6 | 7 | 8 |
3632+-----+-----+-----+-----+
3633| | 9 | 10 | |
3634+-----+-----+-----+-----+
3635
3636Note:
3637
3638In case the function is called interactively user must use \\[quoted-insert] `quoted-insert'
3639in order to enter \"\\n\" successfully. COL-DELIM-REGEXP at the end
3640of each row is optional.
3641
3642
3643Example 2:
3644
3645This example shows how a table can be used for text layout editing.
3646Let `table-capture' capture the following region starting from
3647-!- and ending at -*-, that contains three paragraphs and two item
3648name headers. This time specify empty string for both
3649COL-DELIM-REGEXP and ROW-DELIM-REGEXP.
3650
3651-!-`table-capture' is a powerful command however mastering its power
3652requires some practice. Here is a list of items what it can do.
3653
3654Parse Cell Items By using column delimiter regular
3655 expression and raw delimiter regular
3656 expression, it parses the specified text
3657 area and extracts cell items from
3658 non-table text and then forms a table out
3659 of them.
3660
3661Capture Text Area When no delimiters are specified it
3662 creates a single cell table. The text in
3663 the specified region is placed in that
3664 cell.-*-
3665
3666Now the entire content is captured in a cell which is itself a table
3667like this.
3668
3669+-----------------------------------------------------------------+
3670|`table-capture' is a powerful command however mastering its power|
3671|requires some practice. Here is a list of items what it can do. |
3672| |
3673|Parse Cell Items By using column delimiter regular |
3674| expression and raw delimiter regular |
3675| expression, it parses the specified text |
3676| area and extracts cell items from |
3677| non-table text and then forms a table out |
3678| of them. |
3679| |
3680|Capture Text Area When no delimiters are specified it |
3681| creates a single cell table. The text in |
3682| the specified region is placed in that |
3683| cell. |
3684+-----------------------------------------------------------------+
3685
3686By splitting the cell appropriately we now have a table consisting of
3687paragraphs occupying its own cell. Each cell can now be edited
3688independently.
3689
3690+-----------------------------------------------------------------+
3691|`table-capture' is a powerful command however mastering its power|
3692|requires some practice. Here is a list of items what it can do. |
3693+---------------------+-------------------------------------------+
3694|Parse Cell Items |By using column delimiter regular |
3695| |expression and raw delimiter regular |
3696| |expression, it parses the specified text |
3697| |area and extracts cell items from |
3698| |non-table text and then forms a table out |
3699| |of them. |
3700+---------------------+-------------------------------------------+
3701|Capture Text Area |When no delimiters are specified it |
3702| |creates a single cell table. The text in |
3703| |the specified region is placed in that |
3704| |cell. |
3705+---------------------+-------------------------------------------+
3706
3707By applying `table-release', which does the opposite process, the
3708contents become once again plain text. `table-release' works as
3709companion command to `table-capture' this way.
3710"
3711 (interactive
3712 (let ((col-delim-regexp)
3713 (row-delim-regexp))
3714 (barf-if-buffer-read-only)
3715 (if (table--probe-cell)
3716 (error "Can't insert a table inside a table"))
3717 (list
3718 (mark) (point)
3719 (setq col-delim-regexp
3720 (read-from-minibuffer "Column delimiter regexp: "
3721 (car table-col-delim-regexp-history) nil nil 'table-col-delim-regexp-history))
3722 (setq row-delim-regexp
3723 (read-from-minibuffer "Row delimiter regexp: "
3724 (car table-row-delim-regexp-history) nil nil 'table-row-delim-regexp-history))
3725 (let* ((completion-ignore-case t)
3726 (default (car table-capture-justify-history)))
3727 (if (and (string= col-delim-regexp "") (string= row-delim-regexp "")) 'left
3728 (intern
3729 (downcase (completing-read
3730 (format "Justify (default %s): " default)
3731 '(("left") ("center") ("right"))
3732 nil t nil 'table-capture-justify-history default)))))
3733 (if (and (string= col-delim-regexp "") (string= row-delim-regexp "")) "1"
3734 (table--read-from-minibuffer '("Minimum cell width" . table-capture-min-cell-width-history)))
3735 (if (and (not (string= col-delim-regexp "")) (string= row-delim-regexp ""))
3736 (string-to-number
ba952214 3737 (table--read-from-minibuffer '("Number of columns" . table-capture-columns-history)))
238240c9
RS
3738 nil)
3739 )))
3740 (if (> beg end) (let ((tmp beg)) (setq beg end) (setq end tmp)))
3741 (if (string= col-delim-regexp "") (setq col-delim-regexp nil))
3742 (if (string= row-delim-regexp "") (setq row-delim-regexp nil))
3743 (if (and columns (< columns 1)) (setq columns nil))
3744 (unless min-cell-width (setq min-cell-width "5"))
3745 (let ((contents (buffer-substring beg end))
3746 (cols 0) (rows 0) c r cell-list
3747 (delim-pattern
3748 (if (and col-delim-regexp row-delim-regexp)
3749 (format "\\(\\(%s\\)?\\s *\\(%s\\)\\s *\\)\\|\\(\\(%s\\)\\s *\\)"
3750 col-delim-regexp row-delim-regexp col-delim-regexp)
3751 (if col-delim-regexp
3752 (format "\\(\\)\\(\\)\\(\\)\\(\\(%s\\)\\s *\\)" col-delim-regexp))))
3753 (contents-list))
3754 ;; when delimiters are specified extract cells and determine the cell dimension
3755 (if delim-pattern
3756 (with-temp-buffer
3757 (insert contents)
3758 ;; make sure the contents ends with a newline
3759 (goto-char (point-max))
3760 (unless (zerop (current-column))
3761 (insert ?\n))
3762 ;; skip the preceding white spaces
3763 (goto-char (point-min))
3764 (if (looking-at "\\s +")
3765 (goto-char (match-end 0)))
3766 ;; extract cell contents
3767 (let ((from (point)))
3768 (setq cell-list nil)
3769 (setq c 0)
3770 (while (and (re-search-forward delim-pattern nil t)
3771 (cond
3772 ;; row delimiter
3773 ((and (match-string 1) (not (string= (match-string 1) "")))
3774 (setq rows (1+ rows))
3775 (setq cell-list
3776 (append cell-list (list (buffer-substring from (match-beginning 1)))))
3777 (setq from (match-end 1))
3778 (setq contents-list
3779 (append contents-list (list cell-list)))
3780 (setq cell-list nil)
3781 (setq c (1+ c))
3782 (if (> c cols) (setq cols c))
3783 (setq c 0)
3784 t)
3785 ;; column delimiter
3786 ((and (match-string 4) (not (string= (match-string 4) "")))
3787 (setq cell-list
3788 (append cell-list (list (buffer-substring from (match-beginning 4)))))
3789 (setq from (match-end 4))
3790 (setq c (1+ c))
3791 (if (> c cols) (setq cols c))
3792 t)
3793 (t nil))))
3794 ;; take care of the last element without a post delimiter
3795 (unless (null (looking-at ".+$"))
3796 (setq cell-list
3797 (append cell-list (list (match-string 0))))
3798 (setq cols (1+ cols)))
3799 ;; take care of the last row without a terminating delimiter
3800 (unless (null cell-list)
3801 (setq rows (1+ rows))
3802 (setq contents-list
3803 (append contents-list (list cell-list)))))))
3804 ;; finalize the table dimension
3805 (if (and columns contents-list)
3806 ;; when number of columns are specified and cells are parsed determine the dimension
3807 (progn
3808 (setq cols columns)
3809 (setq rows (/ (+ (length (car contents-list)) columns -1) columns)))
3810 ;; when dimensions are not specified default to a single cell table
3811 (if (zerop rows) (setq rows 1))
3812 (if (zerop cols) (setq cols 1)))
3813 ;; delete the region and reform line breaks
3814 (delete-region beg end)
3815 (goto-char beg)
3816 (unless (zerop (current-column))
3817 (insert ?\n))
3818 (unless (looking-at "\\s *$")
3819 (save-excursion
3820 (insert ?\n)))
db95369b 3821 ;; insert the table
238240c9
RS
3822 ;; insert the cell contents
3823 (if (null contents-list)
3824 ;; single cell
3825 (let ((width) (height))
3826 (with-temp-buffer
3827 (insert contents)
3828 (table--remove-eol-spaces (point-min) (point-max))
3829 (table--untabify (point-min) (point-max))
3830 (setq width (table--measure-max-width))
3831 (setq height (1+ (table--current-line (point-max))))
3832 (setq contents (buffer-substring (point-min) (point-max))))
3833 (table-insert cols rows width height)
3834 (table-with-cache-buffer
3835 (insert contents)
3836 (setq table-inhibit-auto-fill-paragraph t)))
3837 ;; multi cells
3838 (table-insert cols rows min-cell-width 1)
3839 (setq r 0)
3840 (setq cell-list nil)
3841 (while (< r rows)
3842 (setq r (1+ r))
3843 (setq c 0)
3844 (unless cell-list
3845 (setq cell-list (car contents-list))
3846 (setq contents-list (cdr contents-list)))
3847 (while (< c cols)
3848 (setq c (1+ c))
3849 (if (car cell-list)
3850 (table-with-cache-buffer
3851 (insert (car cell-list))
3852 (setq cell-list (cdr cell-list))
3853 (setq table-cell-info-justify justify)))
3854 (table-forward-cell 1))))))
3855
3856;;;###autoload
3857(defun table-release ()
3858 "Convert a table into plain text by removing the frame from a table.
e9a452d9 3859Remove the frame from a table and deactivate the table. This command
238240c9
RS
3860converts a table into plain text without frames. It is a companion to
3861`table-capture' which does the opposite process."
3862 (interactive)
3863 (let ((origin-cell (table--probe-cell))
3864 table-lu table-rb)
3865 (if origin-cell
3866 (let ((old-point (point-marker)))
3867 ;; save-excursion is not sufficient for this
3868 ;; because untabify operation moves point
3869 (set-marker-insertion-type old-point t)
3870 (unwind-protect
3871 (progn
3872 (while
3873 (progn
3874 (table-forward-cell 1 nil 'unrecognize)
3875 (let ((cell (table--probe-cell)))
3876 (if (or (null table-lu)
3877 (< (car cell) table-lu))
3878 (setq table-lu (car cell)))
3879 (if (or (null table-rb)
3880 (> (cdr cell) table-rb))
3881 (setq table-rb (cdr cell)))
3882 (and cell (not (equal cell origin-cell))))))
3883 (let* ((lu-coord (table--get-coordinate table-lu))
3884 (rb-coord (table--get-coordinate table-rb))
3885 (lu (table--goto-coordinate (table--offset-coordinate lu-coord '(-1 . -1)))))
3886 (table--spacify-frame)
3887 (setcdr rb-coord (1+ (cdr rb-coord)))
3888 (delete-rectangle lu (table--goto-coordinate (cons (car lu-coord) (cdr rb-coord))))
3889 (table--remove-eol-spaces
3890 (table--goto-coordinate (cons 0 (1- (cdr lu-coord))))
3891 (table--goto-coordinate rb-coord) nil t)))
3892 (goto-char old-point))))))
3893
3894;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3895;;
3896;; Worker functions (executed implicitly)
3897;;
3898
3899(defun table--make-cell-map ()
3900 "Make the table cell keymap if it does not exist yet."
3901 ;; this is irrelevant to keymap but good place to make sure to be executed
3902 (table--update-cell-face)
3903 (unless table-cell-map
3904 (let ((map (make-sparse-keymap))
3905 (remap-alist table-command-remap-alist))
3906 ;; table-command-prefix mode specific bindings
3907 (if (vectorp table-command-prefix)
4e454e5b
JB
3908 (mapc (lambda (binding)
3909 (let ((seq (copy-sequence (car binding))))
3910 (and (vectorp seq)
3911 (listp (aref seq 0))
3912 (eq (car (aref seq 0)) 'control)
3913 (progn
3914 (aset seq 0 (cadr (aref seq 0)))
3915 (define-key map (vconcat table-command-prefix seq) (cdr binding))))))
3916 table-cell-bindings))
238240c9 3917 ;; shorthand control bindings
4e454e5b
JB
3918 (mapc (lambda (binding)
3919 (define-key map (car binding) (cdr binding)))
3920 table-cell-bindings)
238240c9
RS
3921 ;; remap normal commands to table specific version
3922 (while remap-alist
3923 (define-key map (vector 'remap (caar remap-alist)) (cdar remap-alist))
3924 (setq remap-alist (cdr remap-alist)))
3925 ;;
3926 (setq table-cell-map map)
3927 (fset 'table-cell-map map)))
3928 ;; add menu for table cells
3929 (unless table-disable-menu
3930 (easy-menu-define table-cell-menu-map table-cell-map "Table cell menu" table-cell-menu)
3931 (if (featurep 'xemacs)
3932 (easy-menu-add table-cell-menu)))
3933 (run-hooks 'table-cell-map-hook))
3934
3935;; Create the keymap after running the user init file so that the user
3936;; modification to the global-map is accounted.
3937(add-hook 'after-init-hook 'table--make-cell-map t)
3938
3939(defun *table--cell-self-insert-command ()
3940 "Table cell version of `self-insert-command'."
3941 (interactive "*")
66bb8485 3942 (let ((char last-command-event))
238240c9
RS
3943 (if (eq buffer-undo-list t) nil
3944 (if (not (eq last-command this-command))
3945 (setq table-cell-self-insert-command-count 0)
3946 (if (car buffer-undo-list) nil
3947 (if (>= table-cell-self-insert-command-count 19)
3948 (setq table-cell-self-insert-command-count 0)
3949 (setq buffer-undo-list (cdr buffer-undo-list))
3950 (setq table-cell-self-insert-command-count (1+ table-cell-self-insert-command-count))))))
3951 (table--cell-insert-char char overwrite-mode)))
3952
3953(defun *table--cell-delete-backward-char (n)
3954 "Table cell version of `delete-backward-char'."
3955 (interactive "*p")
3956 (*table--cell-delete-char (- n)))
3957
3958(defun *table--cell-newline (&optional indent)
3959 "Table cell version of `newline'."
3960 (interactive "*")
3961 (table-with-cache-buffer
3962 (let ((column (current-column)))
3963 (insert ?\n)
3964 (if indent (indent-to-column column))
3965 ;; fill only when at the beginning of paragraph
3966 (if (= (point)
3967 (save-excursion
3968 (forward-paragraph -1)
3969 (if (looking-at "\\s *$")
3970 (forward-line 1))
3971 (point)))
3972 nil ; yes, at the beginning of the paragraph
3973 (setq table-inhibit-auto-fill-paragraph t)))))
3974
3975(defun *table--cell-open-line (n)
3976 "Table cell version of `open-line'."
3977 (interactive "*p")
3978 (table-with-cache-buffer
3979 (save-excursion
3980 (insert (make-string n ?\n))
3981 (table--fill-region (point) (point))
3982 (setq table-inhibit-auto-fill-paragraph t))))
3983
3984(defun *table--cell-newline-and-indent ()
3985 "Table cell version of `newline-and-indent'."
3986 (interactive)
3987 (*table--cell-newline t))
3988
3989(defun *table--cell-delete-char (n)
3990 "Table cell version of `delete-char'."
3991 (interactive "*p")
3992 (let ((overwrite overwrite-mode))
3993 (table-with-cache-buffer
3994 (if (and overwrite (< n 0))
3995 (progn
3996 (while (not (zerop n))
3997 (let ((coordinate (table--get-coordinate)))
3998 (if (zerop (car coordinate))
3999 (unless (zerop (cdr coordinate))
4000 (table--goto-coordinate (cons (1- table-cell-info-width) (1- (cdr coordinate))))
4001 (unless (eolp)
4002 (delete-char 1)))
4003 (delete-char -1)
ec85195e 4004 (insert ?\s)
238240c9
RS
4005 (forward-char -1)))
4006 (setq n (1+ n)))
4007 (setq table-inhibit-auto-fill-paragraph t))
4008 (let ((coordinate (table--get-coordinate))
4009 (end-marker (copy-marker (+ (point) n)))
4010 (deleted))
4011 (if (or (< end-marker (point-min))
4012 (> end-marker (point-max))) nil
4013 (table--remove-eol-spaces (point-min) (point-max))
4014 (setq deleted (buffer-substring (point) end-marker))
4015 (delete-char n)
4016 ;; in fixed width mode when two lines are concatenated
4017 ;; remove continuation character if there is one.
4018 (and table-fixed-width-mode
4019 (string-match "^\n" deleted)
4020 (equal (char-before) table-word-continuation-char)
4021 (delete-char -2))
4022 ;; see if the point is placed at the right tip of the previous
4023 ;; blank line, if so get rid of the preceding blanks.
4024 (if (and (not (bolp))
4025 (/= (cdr coordinate) (cdr (table--get-coordinate)))
4026 (let ((end (point)))
4027 (save-excursion
4028 (beginning-of-line)
4029 (re-search-forward "\\s +" end t)
4030 (= (point) end))))
4031 (replace-match ""))
4032 ;; do not fill the paragraph if the point is already at the end
4033 ;; of this paragraph and is following a blank character
4034 ;; (otherwise the filling squeezes the preceding blanks)
4035 (if (and (looking-at "\\s *$")
4036 (or (bobp)
4037 (save-excursion
4038 (backward-char)
4039 (looking-at "\\s "))))
4040 (setq table-inhibit-auto-fill-paragraph t))
4041 )
4042 (set-marker end-marker nil))))))
4043
4044(defun *table--cell-quoted-insert (arg)
4045 "Table cell version of `quoted-insert'."
4046 (interactive "*p")
66bb8485 4047 (let ((char (read-quoted-char)))
238240c9
RS
4048 (while (> arg 0)
4049 (table--cell-insert-char char nil)
4050 (setq arg (1- arg)))))
4051
4052(defun *table--cell-describe-mode ()
4053 "Table cell version of `describe-mode'."
4054 (interactive)
4055 (if (not (table--point-in-cell-p))
4056 (call-interactively 'describe-mode)
4057 (with-output-to-temp-buffer "*Help*"
4058 (princ "Table mode: (in ")
48d33090 4059 (princ (format-mode-line mode-name nil nil (current-buffer)))
238240c9
RS
4060 (princ " mode)
4061
4062Table is not a mode technically. You can regard it as a pseudo mode
4063which exists locally within a buffer. It overrides some standard
4064editing behaviors. Editing operations in a table produces confined
4065effects to the current cell. It may grow the cell horizontally and/or
4066vertically depending on the newly entered or deleted contents of the
4067cell, and also depending on the current mode of cell.
4068
4069In the normal mode the table preserves word continuity. Which means
4070that a word never gets folded into multiple lines. For this purpose
4071table will occasionally grow the cell width. On the other hand, when
4072in a fixed width mode all cell width are fixed. When a word can not
4073fit in the cell width the word is folded into the next line. The
4074folded location is marked by a continuation character which is
4075specified in the variable `table-word-continuation-char'.
4076")
d5d105e8 4077 (help-print-return-message))))
238240c9
RS
4078
4079(defun *table--cell-describe-bindings ()
4080 "Table cell version of `describe-bindings'."
4081 (interactive)
4082 (if (not (table--point-in-cell-p))
4083 (call-interactively 'describe-bindings)
4084 (with-output-to-temp-buffer "*Help*"
4085 (princ "Table Bindings:
4086key binding
4087--- -------
4088
4089")
4e454e5b
JB
4090 (mapc (lambda (binding)
4091 (princ (format "%-16s%s\n"
4092 (key-description (car binding))
4093 (cdr binding))))
4094 table-cell-bindings)
d5d105e8 4095 (help-print-return-message))))
238240c9
RS
4096
4097(defun *table--cell-dabbrev-expand (arg)
4098 "Table cell version of `dabbrev-expand'."
4099 (interactive "*P")
4100 (let ((dabbrev-abbrev-char-regexp (concat "[^"
4101 (char-to-string table-cell-vertical-char)
4102 (char-to-string table-cell-intersection-char)
4103 " \n]")))
4104 (table-with-cache-buffer
4105 (dabbrev-expand arg))))
4106
4107(defun *table--cell-dabbrev-completion (&optional arg)
4108 "Table cell version of `dabbrev-completion'."
4109 (interactive "*P")
4110 (error "`dabbrev-completion' is incompatible with table")
4111 (let ((dabbrev-abbrev-char-regexp (concat "[^"
4112 (char-to-string table-cell-vertical-char)
4113 (char-to-string table-cell-intersection-char)
4114 " \n]")))
4115 (table-with-cache-buffer
4116 (dabbrev-completion arg))))
4117
4118(defun *table--present-cell-popup-menu (event)
4119 "Present and handle cell popup menu."
4120 (interactive "e")
4121 (unless table-disable-menu
4122 (select-window (posn-window (event-start event)))
4123 (goto-char (posn-point (event-start event)))
4124 (let ((item-list (x-popup-menu event table-cell-menu-map))
4125 (func table-cell-menu-map))
4126 (while item-list
4127 (setq func (nth 3 (assoc (car item-list) func)))
4128 (setq item-list (cdr item-list)))
4129 (if (and (symbolp func) (fboundp func))
4130 (call-interactively func)))))
4131
4132;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4133;;
4134;; Cell updating functions
4135;;
4136
4137(defun table--update-cell (&optional now)
4138 "Update the table cell contents.
4139When the optional parameter NOW is nil it only sets up the update
4140timer. If it is non-nil the function copies the contents of the cell
4141cache buffer into the designated cell in the table buffer."
4142 (if (null table-update-timer) nil
4143 (table--cancel-timer table-update-timer)
4144 (setq table-update-timer nil))
4145 (if (or (not now)
4146 (and (boundp 'quail-converting)
4147 quail-converting) ;; defer operation while current quail work is not finished.
4148 (and (boundp 'quail-translating)
4149 quail-translating))
4150 (setq table-update-timer
4151 (table--set-timer table-time-before-update
4152 (function table--update-cell)
4153 'now))
4154 (save-current-buffer
4155 (set-buffer table-cell-buffer)
4156 (let ((cache-buffer (get-buffer-create table-cache-buffer-name))
4157 (org-coord (table--get-coordinate))
4158 (in-cell (equal (table--cell-to-coord (table--probe-cell))
4159 (cons table-cell-info-lu-coordinate table-cell-info-rb-coordinate)))
4160 rectangle)
4161 (set-buffer cache-buffer)
4162 (setq rectangle
4163 (extract-rectangle
4164 1
4165 (table--goto-coordinate (cons table-cell-info-width (1- table-cell-info-height)))))
4166 (set-buffer table-cell-buffer)
4167 (delete-rectangle (table--goto-coordinate table-cell-info-lu-coordinate)
4168 (table--goto-coordinate table-cell-info-rb-coordinate))
4169 (table--goto-coordinate table-cell-info-lu-coordinate)
4170 (table--insert-rectangle rectangle)
4171 (let* ((cell (table--probe-cell))) ; must probe again in case of wide characters
4172 (table--put-cell-property cell)
4173 (table--put-cell-justify-property cell table-cell-info-justify)
4174 (table--put-cell-valign-property cell table-cell-info-valign))
4175 (table--goto-coordinate
4176 (if in-cell
4177 (table--transcoord-cache-to-table table-cell-cache-point-coordinate)
4178 org-coord))))
4179 ;; simulate undo behavior under overwrite-mode
4180 (if (and overwrite-mode (not (eq buffer-undo-list t)))
4181 (setq buffer-undo-list (cons nil buffer-undo-list)))))
4182
4183(defun table--update-cell-widened (&optional now)
4184 "Update the contents of the cells that are affected by widening operation."
4185 (if (null table-widen-timer) nil
4186 (table--cancel-timer table-widen-timer)
4187 (setq table-widen-timer nil))
4188 (if (not now)
4189 (setq table-widen-timer
4190 (table--set-timer (+ table-time-before-update table-time-before-reformat)
4191 (function table--update-cell-widened)
4192 'now))
4193 (save-current-buffer
4194 (if table-update-timer
4195 (table--update-cell 'now))
4196 (set-buffer table-cell-buffer)
4197 (let* ((current-coordinate (table--get-coordinate))
4198 (current-cell-coordinate (table--cell-to-coord (table--probe-cell)))
4199 (cell-coord-list (progn
4200 (table--goto-coordinate table-cell-info-lu-coordinate)
4201 (table--cell-list-to-coord-list (table--vertical-cell-list)))))
4202 (while cell-coord-list
4203 (let* ((cell-coord (prog1 (car cell-coord-list) (setq cell-coord-list (cdr cell-coord-list))))
4204 (currentp (equal cell-coord current-cell-coordinate)))
4205 (if currentp (table--goto-coordinate current-coordinate)
4206 (table--goto-coordinate (car cell-coord)))
4207 (table-recognize-cell 'froce)
4208 (let ((table-inhibit-update t))
4209 (table-with-cache-buffer
4210 (let ((sticky (and currentp
4211 (save-excursion
4212 (unless (bolp) (forward-char -1))
4213 (looking-at ".*\\S ")))))
4214 (table--fill-region (point-min) (point-max))
4215 (if sticky
4216 (setq current-coordinate (table--transcoord-cache-to-table))))))
4217 (table--update-cell 'now)
4218 ))
4219 (table--goto-coordinate current-coordinate)
4220 (table-recognize-cell 'froce)))))
4221
4222(defun table--update-cell-heightened (&optional now)
4223 "Update the contents of the cells that are affected by heightening operation."
4224 (if (null table-heighten-timer) nil
4225 (table--cancel-timer table-heighten-timer)
4226 (setq table-heighten-timer nil))
4227 (if (not now)
4228 (setq table-heighten-timer
4229 (table--set-timer (+ table-time-before-update table-time-before-reformat)
4230 (function table--update-cell-heightened)
4231 'now))
4232 (save-current-buffer
4233 (if table-update-timer
4234 (table--update-cell 'now))
4235 (if table-widen-timer
4236 (table--update-cell-widened 'now))
4237 (set-buffer table-cell-buffer)
4238 (let* ((current-coordinate (table--get-coordinate))
4239 (current-cell-coordinate (table--cell-to-coord (table--probe-cell)))
4240 (cell-coord-list (progn
4241 (table--goto-coordinate table-cell-info-lu-coordinate)
4242 (table--cell-list-to-coord-list (table--horizontal-cell-list)))))
4243 (while cell-coord-list
4244 (let* ((cell-coord (prog1 (car cell-coord-list) (setq cell-coord-list (cdr cell-coord-list))))
4245 (currentp (equal cell-coord current-cell-coordinate)))
4246 (if currentp (table--goto-coordinate current-coordinate)
4247 (table--goto-coordinate (car cell-coord)))
4248 (table-recognize-cell 'froce)
4249 (let ((table-inhibit-update t))
4250 (table-with-cache-buffer
4251 (let ((sticky (and currentp
4252 (save-excursion
4253 (unless (bolp) (forward-char -1))
4254 (looking-at ".*\\S ")))))
4255 (table--valign)
4256 (if sticky
4257 (setq current-coordinate (table--transcoord-cache-to-table))))))
4258 (table--update-cell 'now)
4259 ))
4260 (table--goto-coordinate current-coordinate)
4261 (table-recognize-cell 'froce)))))
4262
4263;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4264;;
4265;; Service functions (for external packages)
4266;;
4267
4268(defun table-goto-top-left-corner ()
4269 "Move point to top left corner of the current table and return the char position."
4270 (table--goto-coordinate
4271 (cons
4272 (1- (car (table--get-coordinate (car (table--horizontal-cell-list t t)))))
4273 (1- (cdr (table--get-coordinate (car (table--vertical-cell-list t t))))))))
4274
4275(defun table-goto-top-right-corner ()
4276 "Move point to top right corner of the current table and return the char position."
4277 (table--goto-coordinate
4278 (cons
4279 (car (table--get-coordinate (cdr (table--horizontal-cell-list nil t))))
4280 (1- (cdr (table--get-coordinate (car (table--vertical-cell-list t t))))))))
4281
4282(defun table-goto-bottom-left-corner ()
4283 "Move point to bottom left corner of the current table and return the char position."
4284 (table--goto-coordinate
4285 (cons
4286 (1- (car (table--get-coordinate (car (table--horizontal-cell-list t t)))))
4287 (1+ (cdr (table--get-coordinate (cdr (table--vertical-cell-list nil t))))))))
4288
4289(defun table-goto-bottom-right-corner ()
4290 "Move point to bottom right corner of the current table and return the char position."
4291 (table--goto-coordinate
4292 (cons
4293 (car (table--get-coordinate (cdr (table--horizontal-cell-list nil t))))
4294 (1+ (cdr (table--get-coordinate (cdr (table--vertical-cell-list nil t))))))))
4295
c80e3b4a 4296(defun table-call-interactively (function &optional record-flag keys)
238240c9
RS
4297 "Call FUNCTION, or a table version of it if applicable.
4298See `call-interactively' for full description of the arguments."
4299 (let ((table-func (intern-soft (format "*table--cell-%s" function))))
4300 (call-interactively
4301 (if (and table-func
4302 (table--point-in-cell-p))
4303 table-func
c80e3b4a 4304 function) record-flag keys)))
238240c9
RS
4305
4306(defun table-funcall (function &rest arguments)
4307 "Call FUNCTION, or a table version of it if applicable.
4308See `funcall' for full description of the arguments."
4309 (let ((table-func (intern-soft (format "*table--cell-%s" function))))
4310 (apply
4311 (if (and table-func
4312 (table--point-in-cell-p))
4313 table-func
4314 function)
4315 arguments)))
4316
4317(defmacro table-apply (function &rest arguments)
4318 "Call FUNCTION, or a table version of it if applicable.
4319See `apply' for full description of the arguments."
4320 (let ((table-func (make-symbol "table-func")))
4321 `(let ((,table-func (intern-soft (format "*table--cell-%s" ,function))))
4322 (apply
4323 (if (and ,table-func
4324 (table--point-in-cell-p))
4325 ,table-func
4326 ,function)
4327 ,@arguments))))
4328
4329;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
4330;;
4331;; Utility functions
4332;;
4333
4334(defun table--read-from-minibuffer (prompt-history)
4335 "A wrapper to `read-from-minibuffer'.
4336PROMPT-HISTORY is a cons cell which car is the prompt string and the
4337cdr is the history symbol."
4338 (let ((default (car (symbol-value (cdr prompt-history)))))
4339 (read-from-minibuffer
4340 (format "%s (default %s): " (car prompt-history) default)
4341 "" nil nil (cdr prompt-history) default))
4342 (and (featurep 'xemacs)
4343 (equal (car (symbol-value (cdr prompt-history))) "")
4344 (set (cdr prompt-history)
4345 (cdr (symbol-value (cdr prompt-history)))))
4346 (car (symbol-value (cdr prompt-history))))
4347
238240c9
RS
4348(defun table--buffer-substring-and-trim (beg end)
4349 "Extract buffer substring and remove blanks from front and the rear of it."
4350 (save-excursion
4351 (save-restriction
4352 (narrow-to-region (goto-char beg) end)
4353 (if (re-search-forward "\\s *")
4354 (setq beg (match-end 0)))
4355 (if (re-search-forward "\\s *\\'" end t)
4356 (setq end (match-beginning 0)))
4357 (table--remove-cell-properties
4358 0 (- end beg)
4359 (buffer-substring beg end)))))
4360
4361(defun table--valign ()
4362 "Vertically align the cache cell contents.
4363Current buffer must be the cache buffer at the entry to this function.
4364Returns the coordinate of the final point location."
4365 (if (or (null table-cell-info-valign)
4366 (eq table-cell-info-valign 'none))
4367 (table--get-coordinate)
4368 (let ((saved-point (point-marker)))
4369 ;;(set-marker-insertion-type saved-point t)
4370 (goto-char (point-min))
4371 (let* ((from (and (re-search-forward "^.*\\S " nil t)
4372 (table--current-line)))
4373 (to (let ((tmp from))
4374 (while (re-search-forward "^.*\\S " nil t)
4375 (setq tmp (table--current-line)))
4376 tmp))
4377 (content-height (and from to (1+ (- to from)))))
4378 (unless (null content-height)
4379 (goto-char (point-min))
4380 (if (looking-at "\\s *\n")
4381 (replace-match ""))
4382 (cond ((eq table-cell-info-valign 'middle)
4383 (insert (make-string (/ (- table-cell-info-height content-height) 2) ?\n)))
4384 ((eq table-cell-info-valign 'bottom)
4385 (insert (make-string (- table-cell-info-height content-height) ?\n))))
4386 (table--goto-coordinate (cons table-cell-info-width (1- table-cell-info-height)))
4387 (if (re-search-forward "\\s +\\'" nil t)
4388 (replace-match ""))))
4389 (goto-char saved-point)
4390 (set-marker saved-point nil)
4391 (let ((coord (table--get-coordinate)))
4392 (unless (< (cdr coord) table-cell-info-height)
4393 (setcdr coord (1- table-cell-info-height))
4394 (table--goto-coordinate coord))
4395 coord))))
4396
4397(defun table--query-justification ()
4398 (barf-if-buffer-read-only)
4399 (let* ((completion-ignore-case t)
4400 (default (car table-justify-history)))
4401 (intern (downcase (completing-read
4402 (format "Justify (default %s): " default)
4403 '(("left") ("center") ("right") ("top") ("middle") ("bottom") ("none"))
4404 nil t nil 'table-justify-history default)))))
4405
4406(defun table--spacify-frame ()
4407 "Spacify table frame.
4408Replace frame characters with spaces."
e99add21
JB
4409 (let ((frame-char
4410 (append (string-to-list table-cell-horizontal-chars)
4411 (list table-cell-intersection-char table-cell-vertical-char))))
238240c9
RS
4412 (while
4413 (progn
4414 (cond
4415 ((eq (char-after) table-cell-intersection-char)
4416 (save-excursion
4417 (let ((col (current-column)))
4418 (and (zerop (forward-line 1))
4419 (zerop (current-column))
4420 (move-to-column col)
4421 (table--spacify-frame))))
4422 (delete-char 1)
ec85195e 4423 (insert-before-markers ?\s))
e99add21 4424 ((table--cell-horizontal-char-p (char-after))
238240c9
RS
4425 (while (progn
4426 (delete-char 1)
ec85195e 4427 (insert-before-markers ?\s)
e99add21 4428 (table--cell-horizontal-char-p (char-after)))))
238240c9
RS
4429 ((eq (char-after) table-cell-vertical-char)
4430 (while (let ((col (current-column)))
4431 (delete-char 1)
ec85195e 4432 (insert-before-markers ?\s)
238240c9
RS
4433 (and (zerop (forward-line 1))
4434 (zerop (current-column))
4435 (move-to-column col)
4436 (eq (char-after) table-cell-vertical-char))))))
4437 (memq (char-after) frame-char)))))
4438
4439(defun table--remove-blank-lines (n)
4440 "Delete N blank lines from the current line.
4441For adjusting below area of the table when the table is shortened."
4442 (move-to-column 0)
4443 (let ((first-blank t))
4444 (while (> n 0)
4445 (setq n (1- n))
4446 (cond ((looking-at "\\s *\\'")
4447 (delete-region (match-beginning 0) (match-end 0))
4448 (setq n 0))
4449 ((and (looking-at "\\([ \t]*\n[ \t]*\\)\n") first-blank)
4450 (delete-region (match-beginning 1) (match-end 1)))
4451 ((looking-at "[ \t]*$")
4452 (delete-region (match-beginning 0) (match-end 0))
4453 (forward-line 1))
4454 (t
4455 (setq first-blank nil)
4456 (forward-line 1))))))
4457
4458(defun table--uniform-list-p (l)
4459 "Return nil when LIST contains non equal elements. Otherwise return t."
4460 (if (null l) t
4461 (catch 'end
4462 (while (cdr l)
4463 (if (not (equal (car l) (cadr l))) (throw 'end nil))
4464 (setq l (cdr l)))
4465 t)))
4466
4467(defun table--detect-cell-alignment (cell)
4468 "Detect CELL contents alignment.
4469Guess CELL contents alignment both horizontally and vertically by
4470looking at the appearance of the CELL contents."
4471 (let ((cell-contents (extract-rectangle (car cell) (cdr cell)))
4472 (left-margin 0)
4473 (right-margin 0)
4474 (top-margin 0)
4475 (bottom-margin 0)
4476 (margin-diff 0)
4477 (margin-info-available nil)
4478 justify valign)
4479 (with-temp-buffer
4480 (table--insert-rectangle cell-contents)
4481 ;; determine the horizontal justification
4482 (goto-char (point-min))
4483 (while (re-search-forward "^\\( *\\).*[^ \n]\\( *\\)$" nil t)
4484 (setq margin-info-available t)
4485 (let* ((lm (- (match-end 1) (match-beginning 1)))
4486 (rm (- (match-end 2) (match-beginning 2)))
4487 (md (abs (- lm rm))))
4488 (if (> lm left-margin)
4489 (setq left-margin lm))
4490 (if (> rm right-margin)
4491 (setq right-margin rm))
4492 (if (> md margin-diff)
4493 (setq margin-diff md))))
4494 (setq justify
4495 (cond
4496 ((and margin-info-available
4497 (<= margin-diff 1)
4498 (> left-margin 0)) 'center)
4499 ((and margin-info-available
4500 (zerop right-margin)
4501 (> left-margin 0)) 'right)
4502 (t 'left)))
4503 ;; determine the vertical justification
4504 (goto-char (point-min))
4505 (if (and (re-search-forward "\\s *\\S " nil t)
4506 (/= (match-beginning 0) (match-end 0)))
4507 (setq top-margin (1- (count-lines (match-beginning 0) (match-end 0)))))
4508 (if (and (re-search-forward "\\s *\\'" nil t)
4509 (/= (match-beginning 0) (match-end 0)))
4510 (setq bottom-margin (1- (count-lines (match-beginning 0) (match-end 0)))))
4511 (setq valign
4512 (cond
4513 ((and (> top-margin 0)
4514 (> bottom-margin 0)
4515 (<= (abs (- top-margin bottom-margin)) 1)) 'middle)
4516 ((and (> top-margin 0)
4517 (zerop bottom-margin)) 'bottom)
4518 (t nil))))
4519 (table--put-cell-justify-property cell justify)
4520 (table--put-cell-valign-property cell valign)))
4521
4522(defun table--string-to-number-list (str)
4523 "Return a list of numbers in STR."
4524 (let ((idx 0)
4525 (nl nil))
4526 (while (string-match "[-0-9.]+" str idx)
4527 (setq idx (match-end 0))
4528 (setq nl (cons (string-to-number (match-string 0 str)) nl)))
4529 (nreverse nl)))
4530
4531(defun table--justify-cell-contents (justify &optional paragraph)
4532 "Justify the current cell contents.
4533JUSTIFY is a symbol 'left, 'center or 'right for horizontal, or 'top,
4534'middle, 'bottom or 'none for vertical. When PARAGRAPH is non-nil the
4535justify operation is limited to the current paragraph."
4536 (table-with-cache-buffer
4537 (let ((beg (point-min))
4538 (end (point-max-marker))
4539 (fill-column table-cell-info-width)
4540 (adaptive-fill-mode nil)
4541 (valign-symbols '(top middle bottom none)))
4542 (unless paragraph
4543 (if (memq justify valign-symbols)
4544 (setq table-cell-info-valign
4545 (if (eq justify 'none) nil justify))
4546 (setq table-cell-info-justify justify)))
4547 (save-excursion
4548 (if paragraph
4549 (let ((paragraph-start "\n"))
4550 (forward-paragraph)
4551 (or (bolp) (newline 1))
4552 (set-marker end (point))
4553 (setq beg (progn (forward-paragraph -1) (point)))))
4554 (if (memq justify valign-symbols)
4555 (table--valign)
4556 (table--remove-eol-spaces beg end 'bol)
4557 (let ((paragraph-start table-paragraph-start))
4558 (fill-region beg end table-cell-info-justify))))
4559 (setq table-inhibit-auto-fill-paragraph t)
4560 (set-marker end nil)))
4561 (table--update-cell 'now))
4562
4563(defun table--horizontally-shift-above-and-below (columns-to-extend top-to-bottom-coord-list)
4564 "Horizontally shift outside contents right above and right below of the table.
4565This function moves the surrounding text outside of the table so that
4566they match the horizontal growth/shrink of the table. It also
4567untabify the shift affected area including the right side of the table
4568so that tab related uneven shifting is avoided. COLUMNS-TO-EXTEND
4569specifies the number of columns the table grows, or shrinks if
4570negative. TOP-TO-BOTTOM-COORD-LIST is the vertical cell coordinate
4571list. This list can be any vertical list within the table."
4572 (save-excursion
4573 (let (beg-coord end-coord)
4574 (table--goto-coordinate (caar top-to-bottom-coord-list))
4575 (let* ((cell (table--horizontal-cell-list nil 'first-only 'top))
4576 (coord (cons (car (table--get-coordinate (cdr cell)))
4577 (cdr (table--get-coordinate (car cell))))))
4578 (setcar coord (1+ (car coord)))
4579 (setcdr coord (- (cdr coord) 2))
4580 (setq beg-coord (cons (car coord) (1+ (cdr coord))))
4581 (while (and (table--goto-coordinate coord 'no-extension)
4582 (not (looking-at "\\s *$")))
4583 (if (< columns-to-extend 0)
4584 (progn
4585 (table--untabify-line)
4586 (delete-char columns-to-extend))
4587 (table--untabify-line (point))
ec85195e 4588 (insert (make-string columns-to-extend ?\s)))
238240c9
RS
4589 (setcdr coord (1- (cdr coord)))))
4590 (table--goto-coordinate (caar (last top-to-bottom-coord-list)))
4591 (let ((coord (table--get-coordinate (cdr (table--horizontal-cell-list nil 'first-only 'bottom)))))
4592 (setcar coord (1+ (car coord)))
4593 (setcdr coord (+ (cdr coord) 2))
4594 (setq end-coord (cons (car coord) (1- (cdr coord))))
4595 (while (and (table--goto-coordinate coord 'no-extension)
4596 (not (looking-at "\\s *$")))
4597 (if (< columns-to-extend 0)
4598 (progn
4599 (table--untabify-line)
4600 (delete-char columns-to-extend))
4601 (table--untabify-line (point))
ec85195e 4602 (insert (make-string columns-to-extend ?\s)))
238240c9
RS
4603 (setcdr coord (1+ (cdr coord)))))
4604 (while (<= (cdr beg-coord) (cdr end-coord))
4605 (table--untabify-line (table--goto-coordinate beg-coord 'no-extension))
4606 (setcdr beg-coord (1+ (cdr beg-coord)))))))
4607
4608(defun table--create-growing-space-below (lines-to-extend left-to-right-coord-list bottom-border-y)
4609 "Create growing space below the table.
4610This function creates growing space below the table slightly
4611intelligent fashion. Following is the cases it handles for each
4612growing line:
4613 1. When the first line below the table is a complete blank line it
4614inserts a blank line.
4615 2. When the line starts with a prefix that matches the prefix of the
4616bottom line of the table it inserts a line consisting of prefix alone.
4617 3. Otherwise it deletes the rectangular contents where table will
4618grow into."
4619 (save-excursion
4620 (let ((i 0)
4621 (prefix (and (table--goto-coordinate (cons 0 bottom-border-y))
4622 (re-search-forward
4623 ".*\\S "
4624 (save-excursion
4625 (table--goto-coordinate
4626 (cons (1- (caar (car left-to-right-coord-list))) bottom-border-y)))
4627 t)
4628 (buffer-substring (match-beginning 0) (match-end 0)))))
4629 (while (< i lines-to-extend)
4630 (let ((y (+ i bottom-border-y 1)))
4631 (table--goto-coordinate (cons 0 y))
4632 (cond
4633 ((looking-at "\\s *$")
4634 (insert ?\n))
4635 ((and prefix (looking-at (concat (regexp-quote prefix) "\\s *$")))
4636 (insert prefix ?\n))
4637 (t
4638 (delete-rectangle
4639 (table--goto-coordinate (cons (1- (caar (car left-to-right-coord-list))) y))
4640 (table--goto-coordinate (cons (1+ (cadr (car (last left-to-right-coord-list)))) y))))))
4641 (setq i (1+ i))))))
4642
4643(defun table--untabify-line (&optional from)
4644 "Untabify current line.
4645Unlike save-excursion this guarantees preserving the cursor location
4646even when the point is on a tab character which is to be removed.
4647Optional FROM narrows the subject operation from this point to the end
4648of line."
4649 (let ((current-coordinate (table--get-coordinate)))
4650 (table--untabify (or from (progn (beginning-of-line) (point)))
4651 (progn (end-of-line) (point)))
4652 (table--goto-coordinate current-coordinate)))
4653
4654(defun table--untabify (beg end)
4655 "Wrapper to raw untabify."
4656 (untabify beg end)
4657 (if (featurep 'xemacs)
4658 ;; Cancel strange behavior of xemacs
4659 (message "")))
4660
4661(defun table--multiply-string (string multiplier)
4662 "Multiply string and return it."
4663 (let ((ret-str ""))
4664 (while (> multiplier 0)
4665 (setq ret-str (concat ret-str string))
4666 (setq multiplier (1- multiplier)))
4667 ret-str))
4668
951f97e6
SM
4669(defun table--line-column-position (line column)
4670 "Return the location of LINE forward at COLUMN."
4671 (save-excursion
4672 (forward-line line)
4673 (move-to-column column)
4674 (point)))
4675
4676(defun table--row-column-insertion-point-p (&optional columnp)
9861d11e 4677 "Return non-nil if it makes sense to insert a row or a column at point."
951f97e6
SM
4678 (and (not buffer-read-only)
4679 (or (get-text-property (point) 'table-cell)
4680 (let ((column (current-column)))
4681 (if columnp
4682 (or (text-property-any (line-beginning-position 0)
4683 (table--line-column-position -1 column)
4684 'table-cell t)
4685 (text-property-any (line-beginning-position) (point) 'table-cell t)
4686 (text-property-any (line-beginning-position 2)
4687 (table--line-column-position 1 column)
4688 'table-cell t))
4689 (text-property-any (table--line-column-position -2 column)
4690 (table--line-column-position -2 (+ 2 column))
4691 'table-cell t))))))
4692
238240c9
RS
4693(defun table--find-row-column (&optional columnp no-error)
4694 "Search table and return a cell coordinate list of row or column."
4695 (let ((current-coordinate (table--get-coordinate)))
4696 (catch 'end
4697 (catch 'error
4698 (let ((coord (table--get-coordinate)))
4699 (while
4700 (progn
4701 (if columnp (setcar coord (1- (car coord)))
4702 (setcdr coord (1- (cdr coord))))
4703 (>= (if columnp (car coord) (cdr coord)) 0))
4704 (while (progn
4705 (table--goto-coordinate coord 'no-extension 'no-tab-expansion)
e99add21
JB
4706 (not (looking-at (format "[%s%c%c]"
4707 table-cell-horizontal-chars
238240c9
RS
4708 table-cell-vertical-char
4709 table-cell-intersection-char))))
4710 (if columnp (setcar coord (1- (car coord)))
4711 (setcdr coord (1- (cdr coord))))
4712 (if (< (if columnp (car coord) (cdr coord)) 0)
4713 (throw 'error nil)))
4714 (if (table--probe-cell)
4715 (throw 'end (table--cell-list-to-coord-list (if columnp
4716 (table--vertical-cell-list t nil 'left)
4717 (table--horizontal-cell-list t nil 'top))))
4718 (table--goto-coordinate (table--offset-coordinate coord (if columnp '(0 . 1) '(1 . 0)))
4719 'no-extension 'no-tab-expansion)
4720 (if (table--probe-cell)
4721 (throw 'end (table--cell-list-to-coord-list (if columnp
4722 (table--vertical-cell-list t nil 'left)
4723 (table--horizontal-cell-list t nil 'top)))))))))
4724 (table--goto-coordinate current-coordinate)
4725 (if no-error nil
4726 (error "Table not found")))))
4727
4728(defun table--min-coord-list (coord-list)
4729 "Return minimum cell dimension of COORD-LIST.
4730COORD-LIST is a list of coordinate pairs (lu-coord . rb-coord), where
4731each pair in the list represents a cell. lu-coord is the left upper
4732coordinate of a cell and rb-coord is the right bottom coordinate of a
4733cell. A coordinate is a pair of x and y axis coordinate values. The
4734return value is a cons cell (min-w . min-h), where min-w and min-h are
4735respectively the minimum width and the minimum height of all the cells
4736in the list."
4737 (if (null coord-list) nil
4738 (let ((min-width 134217727)
4739 (min-height 134217727))
4740 (while coord-list
4741 (let* ((coord (prog1 (car coord-list) (setq coord-list (cdr coord-list))))
4742 (width (- (cadr coord) (caar coord)))
4743 (height (1+ (- (cddr coord) (cdar coord)))))
4744 (if (< width min-width) (setq min-width width))
4745 (if (< height min-height) (setq min-height height))))
4746 (cons min-width min-height))))
4747
4748(defun table--cell-can-split-horizontally-p ()
4749 "Test if a cell can split at current location horizontally."
4750 (and (not buffer-read-only)
4751 (let ((point-x (car (table--get-coordinate))))
4752 (table-recognize-cell 'force)
4753 (and (> point-x (car table-cell-info-lu-coordinate))
4754 (<= point-x (1- (car table-cell-info-rb-coordinate)))))))
4755
4756(defun table--cell-can-split-vertically-p ()
4757 "Test if a cell can split at current location vertically."
4758 (and (not buffer-read-only)
4759 (let ((point-y (cdr (table--get-coordinate))))
4760 (table-recognize-cell 'force)
4761 (and (> point-y (cdr table-cell-info-lu-coordinate))
4762 (<= point-y (cdr table-cell-info-rb-coordinate))))))
4763
4764(defun table--cell-can-span-p (direction)
4765 "Test if the current cell can span to DIRECTION."
4766 (table-recognize-cell 'force)
4767 (and (not buffer-read-only)
4768 (table--probe-cell)
4769 ;; get two adjacent cells from each corner
4770 (let ((cell (save-excursion
4771 (and
4772 (table--goto-coordinate
4773 (cons (cond ((eq direction 'right) (1+ (car table-cell-info-rb-coordinate)))
4774 ((eq direction 'left) (1- (car table-cell-info-lu-coordinate)))
4775 (t (car table-cell-info-lu-coordinate)))
4776 (cond ((eq direction 'above) (- (cdr table-cell-info-lu-coordinate) 2))
4777 ((eq direction 'below) (+ (cdr table-cell-info-rb-coordinate) 2))
4778 (t (cdr table-cell-info-lu-coordinate)))) 'no-extension)
4779 (table--probe-cell))))
4780 (cell2 (save-excursion
4781 (and
4782 (table--goto-coordinate
4783 (cons (cond ((eq direction 'right) (1+ (car table-cell-info-rb-coordinate)))
4784 ((eq direction 'left) (1- (car table-cell-info-lu-coordinate)))
4785 (t (car table-cell-info-rb-coordinate)))
4786 (cond ((eq direction 'above) (- (cdr table-cell-info-lu-coordinate) 2))
4787 ((eq direction 'below) (+ (cdr table-cell-info-rb-coordinate) 2))
4788 (t (cdr table-cell-info-rb-coordinate)))) 'no-extension)
4789 (table--probe-cell)))))
4790 ;; make sure the two cells exist, and they are identical, that cell's size matches the current one
4791 (and cell
4792 (equal cell cell2)
4793 (if (or (eq direction 'right) (eq direction 'left))
4794 (and (= (cdr (table--get-coordinate (car cell)))
4795 (cdr table-cell-info-lu-coordinate))
4796 (= (cdr (table--get-coordinate (cdr cell)))
4797 (cdr table-cell-info-rb-coordinate)))
4798 (and (= (car (table--get-coordinate (car cell)))
4799 (car table-cell-info-lu-coordinate))
4800 (= (car (table--get-coordinate (cdr cell)))
4801 (car table-cell-info-rb-coordinate))))))))
4802
4803(defun table--cell-insert-char (char &optional overwrite)
4804 "Insert CHAR inside a table cell."
4805 (let ((delete-selection-p (and (boundp 'delete-selection-mode)
4806 delete-selection-mode
4807 transient-mark-mode mark-active
4808 (not buffer-read-only)))
4809 (mark-coordinate (table--transcoord-table-to-cache (table--get-coordinate (mark t)))))
4810 (table-with-cache-buffer
4811 (and delete-selection-p
4812 (>= (car mark-coordinate) 0)
4813 (<= (car mark-coordinate) table-cell-info-width)
4814 (>= (cdr mark-coordinate) 0)
4815 (<= (cdr mark-coordinate) table-cell-info-height)
4816 (save-excursion
4817 (delete-region (point) (table--goto-coordinate mark-coordinate))))
4818 (if overwrite
4819 (let ((coordinate (table--get-coordinate)))
4820 (setq table-inhibit-auto-fill-paragraph t)
4821 (if (>= (car coordinate) table-cell-info-width)
4822 (if (>= (cdr coordinate) (1- table-cell-info-height))
4823 (insert "\n" char)
4824 (forward-line 1)
4825 (insert char)
4826 (unless (eolp)
4827 (delete-char 1)))
4828 (insert char)
4829 (unless (eolp)
4830 (delete-char 1))))
ec85195e 4831 (if (not (eq char ?\s))
238240c9
RS
4832 (if char (insert char))
4833 (if (not (looking-at "\\s *$"))
4834 (if (and table-fixed-width-mode
4835 (> (point) 2)
4836 (save-excursion
4837 (forward-char -2)
4838 (looking-at (concat "\\("
4839 (regexp-quote (char-to-string table-word-continuation-char))
4840 "\\)\n"))))
4841 (save-excursion
4842 (replace-match " " nil nil nil 1))
4843 (insert char))
4844 (let ((coordinate (table--get-coordinate)))
4845 (if (< (car coordinate) table-cell-info-width)
4846 (move-to-column (1+ (car coordinate)) t)
4847 (insert (make-string (forward-line 1) ?\n))
4848 (unless (bolp) (insert ?\n))))
4849 (setq table-inhibit-auto-fill-paragraph t))
4850 (save-excursion
4851 (let ((o-point (point)))
4852 (if (and (bolp)
4853 (or (progn
4854 (forward-paragraph)
4855 (forward-paragraph -1)
4856 (= o-point (point)))
4857 (progn
4858 (goto-char o-point)
4859 (forward-line)
4860 (setq o-point (point))
4861 (forward-paragraph)
4862 (forward-paragraph -1)
4863 (= o-point (point)))))
4864 (insert ?\n)))))))))
4865
4866(defun table--finish-delayed-tasks ()
4867 "Finish all outstanding delayed tasks."
4868 (if table-update-timer
4869 (table--update-cell 'now))
4870 (if table-widen-timer
4871 (table--update-cell-widened 'now))
4872 (if table-heighten-timer
4873 (table--update-cell-heightened 'now)))
4874
4875(defmacro table--log (&rest body)
4876 "Debug logging macro."
1042fc7f 4877 `(with-current-buffer (get-buffer-create "log")
238240c9
RS
4878 (goto-char (point-min))
4879 (let ((standard-output (current-buffer)))
4880 ,@body)))
4881
4882(defun table--measure-max-width (&optional unlimited)
4883 "Return maximum width of current buffer.
4884Normally the current buffer is expected to be already the cache
4885buffer. The width excludes following spaces at the end of each line.
4886Unless UNLIMITED is non-nil minimum return value is 1."
4887 (save-excursion
4888 (let ((width 0))
4889 (goto-char (point-min))
4890 (while
4891 (progn
4892 ;; do not count the following white spaces
4893 (re-search-forward "\\s *$")
4894 (goto-char (match-beginning 0))
4895 (if (> (current-column) width)
4896 (setq width (current-column)))
4897 (forward-line)
4898 (not (eobp))))
4899 (if unlimited width
4900 (max 1 width)))))
4901
4902(defun table--cell-to-coord (cell)
4903 "Create a cell coordinate pair from cell location pair."
4904 (if cell
4905 (cons (table--get-coordinate (car cell))
4906 (table--get-coordinate (cdr cell)))
4907 nil))
4908
4909(defun table--cell-list-to-coord-list (cell-list)
4910 "Create and return a coordinate list that corresponds to CELL-LIST.
4911CELL-LIST is a list of location pairs (lu . rb), where each pair
4912represents a cell in the list. lu is the left upper location and rb
4913is the right bottom location of a cell. The return value is a list of
4914coordinate pairs (lu-coord . rb-coord), where lu-coord is the left
4915upper coordinate and rb-coord is the right bottom coordinate of a
4916cell."
4917 (let ((coord-list))
4918 (while cell-list
4919 (let ((cell (prog1 (car cell-list) (setq cell-list (cdr cell-list)))))
4920 (setq coord-list
4921 (cons (table--cell-to-coord cell) coord-list))))
4922 (nreverse coord-list)))
4923
4924(defun table--test-cell-list (&optional horizontal reverse first-only pivot)
4925 "For testing `table--vertical-cell-list' and `table--horizontal-cell-list'."
4926 (let* ((current-coordinate (table--get-coordinate))
4927 (cell-list (if horizontal
4928 (table--horizontal-cell-list reverse first-only pivot)
4929 (table--vertical-cell-list reverse first-only pivot)))
4930 (count 0))
4931 (while cell-list
4932 (let* ((cell (if first-only (prog1 cell-list (setq cell-list nil))
4933 (prog1 (car cell-list) (setq cell-list (cdr cell-list)))))
4934 (dig1-str (format "%1d" (prog1 (% count 10) (setq count (1+ count))))))
4935 (goto-char (car cell))
4936 (table-with-cache-buffer
1042fc7f
SM
4937 (while (re-search-forward "." nil t)
4938 (replace-match dig1-str nil nil))
238240c9
RS
4939 (setq table-inhibit-auto-fill-paragraph t))
4940 (table--finish-delayed-tasks)))
4941 (table--goto-coordinate current-coordinate)))
4942
4943(defun table--vertical-cell-list (&optional top-to-bottom first-only pivot internal-dir internal-list internal-px)
4944 "Return a vertical cell list from the table.
4945The return value represents a list of cells including the current cell
4946that align vertically. Each element of the list is a cons cell (lu
4947. rb) where lu is the cell's left upper location and rb is the cell's
4948right bottom location. The cell order in the list is from bottom to
4949top of the table. If optional argument TOP-TO-BOTTOM is non-nil the
4950order is reversed as from top to bottom of the table. If optional
4951argument FIRST-ONLY is non-nil the return value is not a list of cells
4952but a single cons cell that is the first cell of the list, if the list
4953had been created. If optional argument PIVOT is a symbol `left' the
4954vertical cell search is aligned with the left edge of the current
4955cell, otherwise aligned with the right edge of the current cell. The
4956arguments INTERNAL-DIR, INTERNAL-LIST and INTERNAL-PX are internal use
4957only and must not be specified."
4958 (save-excursion
4959 (let* ((cell (table--probe-cell))
4960 (lu-coordinate (table--get-coordinate (car cell)))
4961 (rb-coordinate (table--get-coordinate (cdr cell)))
4962 (px (or internal-px (car (if (eq pivot 'left) lu-coordinate rb-coordinate))))
4963 (ty (- (cdr lu-coordinate) 2))
4964 (by (+ (cdr rb-coordinate) 2)))
b4dc7d98 4965 ;; in case of finding the first cell, get the last adding item on the list
238240c9
RS
4966 (if (and (null internal-dir) first-only) (setq top-to-bottom (null top-to-bottom)))
4967 ;; travel up and process as recursion traces back (reverse order)
4968 (and cell
4969 (or (eq internal-dir 'up) (null internal-dir))
4970 (table--goto-coordinate (cons px (if top-to-bottom by ty)) 'no-extension 'no-tab-expansion)
4971 (setq internal-list (table--vertical-cell-list top-to-bottom first-only nil 'up nil px)))
4972 ;; return the last cell or add this cell to the list
4973 (if first-only (or internal-list cell)
4974 (setq internal-list (if cell (cons cell internal-list) internal-list))
4975 ;; travel down and process as entering each recursion (forward order)
4976 (and cell
4977 (or (eq internal-dir 'down) (null internal-dir))
4978 (table--goto-coordinate (cons px (if top-to-bottom ty by)) 'no-extension 'no-tab-expansion)
4979 (setq internal-list (table--vertical-cell-list top-to-bottom nil nil 'down internal-list px)))
4980 ;; return the result
4981 internal-list))))
4982
4983(defun table--horizontal-cell-list (&optional left-to-right first-only pivot internal-dir internal-list internal-py)
4984 "Return a horizontal cell list from the table.
4985The return value represents a list of cells including the current cell
4986that align horizontally. Each element of the list is a cons cells (lu
4987. rb) where lu is the cell's left upper location and rb is the cell's
4988right bottom location. The cell order in the list is from right to
4989left of the table. If optional argument LEFT-TO-RIGHT is non-nil the
4990order is reversed as from left to right of the table. If optional
4991argument FIRST-ONLY is non-nil the return value is not a list of cells
4992but a single cons cell that is the first cell of the list, if the
4993list had been created. If optional argument PIVOT is a symbol `top'
4994the horizontal cell search is aligned with the top edge of the current
4995cell, otherwise aligned with the bottom edge of the current cell. The
4996arguments INTERNAL-DIR, INTERNAL-LIST and INTERNAL-PY are internal use
4997only and must not be specified."
4998 (save-excursion
4999 (let* ((cell (table--probe-cell))
5000 (lu-coordinate (table--get-coordinate (car cell)))
5001 (rb-coordinate (table--get-coordinate (cdr cell)))
5002 (py (or internal-py (if (eq pivot 'top) (cdr lu-coordinate) (1+ (cdr rb-coordinate)))))
5003 (lx (1- (car lu-coordinate)))
5004 (rx (1+ (car rb-coordinate))))
b4dc7d98 5005 ;; in case of finding the first cell, get the last adding item on the list
238240c9
RS
5006 (if (and (null internal-dir) first-only) (setq left-to-right (null left-to-right)))
5007 ;; travel left and process as recursion traces back (reverse order)
5008 (and cell
5009 (or (eq internal-dir 'left) (null internal-dir))
5010 (table--goto-coordinate (cons (if left-to-right rx lx) py) 'no-extension 'no-tab-expansion)
5011 (setq internal-list (table--horizontal-cell-list left-to-right first-only nil 'left nil py)))
5012 ;; return the last cell or add this cell to the list
5013 (if first-only (or internal-list cell)
5014 (setq internal-list (if cell (cons cell internal-list) internal-list))
5015 ;; travel right and process as entering each recursion (forward order)
5016 (and cell
5017 (or (eq internal-dir 'right) (null internal-dir))
5018 (table--goto-coordinate (cons (if left-to-right lx rx) py) 'no-extension 'no-tab-expansion)
5019 (setq internal-list (table--horizontal-cell-list left-to-right nil nil 'right internal-list py)))
5020 ;; return the result
5021 internal-list))))
5022
5023(defun table--point-in-cell-p (&optional location)
5024 "Return t when point is in a valid table cell in the current buffer.
5025When optional LOCATION is provided the test is performed at that location."
5026 (and (table--at-cell-p (or location (point)))
5027 (if location
5028 (save-excursion
5029 (goto-char location)
5030 (table--probe-cell))
5031 (table--probe-cell))))
5032
5033(defun table--region-in-cell-p (beg end)
5034 "Return t when location BEG and END are in a valid table cell in the current buffer."
5035 (and (table--at-cell-p (min beg end))
5036 (save-excursion
5037 (let ((cell-beg (progn (goto-char beg) (table--probe-cell))))
5038 (and cell-beg
5039 (equal cell-beg (progn (goto-char end) (table--probe-cell))))))))
5040
5041(defun table--at-cell-p (position &optional object at-column)
5042 "Returns non-nil if POSITION has table-cell property in OBJECT.
5043OBJECT is optional and defaults to the current buffer.
5044If POSITION is at the end of OBJECT, the value is nil."
5045 (if (and at-column (stringp object))
5046 (setq position (table--str-index-at-column object position)))
5047 (get-text-property position 'table-cell object))
5048
5049(defun table--probe-cell-left-up ()
5050 "Probe left up corner pattern of a cell.
5051If it finds a valid corner returns a position otherwise returns nil.
5052The position is the location before the first cell character.
5053Focus only on the corner pattern. Further cell validity check is required."
5054 (save-excursion
5055 (let ((vertical-str (regexp-quote (char-to-string table-cell-vertical-char)))
5056 (intersection-str (regexp-quote (char-to-string table-cell-intersection-char)))
5057 (v-border (format "[%c%c]" table-cell-vertical-char table-cell-intersection-char))
e99add21 5058 (h-border (format "[%s%c]" table-cell-horizontal-chars table-cell-intersection-char))
5ed619e0 5059 (limit (line-beginning-position)))
238240c9
RS
5060 (catch 'end
5061 (while t
5062 (catch 'retry-horizontal
5063 (if (not (search-backward-regexp v-border limit t))
5064 (throw 'end nil))
5065 (save-excursion
5066 (let ((column (current-column)))
5067 (while t
5068 (catch 'retry-vertical
5069 (if (zerop (forward-line -1)) nil (throw 'end nil))
5070 (move-to-column column)
5071 (while (and (looking-at vertical-str)
5072 (= column (current-column)))
5073 (if (zerop (forward-line -1)) nil (throw 'end nil))
5074 (move-to-column column))
5075 (cond
5076 ((/= column (current-column))
5077 (throw 'end nil))
5078 ((looking-at (concat intersection-str h-border))
5079 (forward-line 1)
5080 (move-to-column column)
5081 (forward-char 1)
5082 (throw 'end (point)))
5083 ((looking-at intersection-str)
5084 (throw 'retry-vertical nil))
5085 (t (throw 'retry-horizontal nil)))))))))))))
5086
5087(defun table--probe-cell-right-bottom ()
5088 "Probe right bottom corner pattern of a cell.
5089If it finds a valid corner returns a position otherwise returns nil.
5090The position is the location after the last cell character.
5091Focus only on the corner pattern. Further cell validity check is required."
5092 (save-excursion
5093 (let ((vertical-str (regexp-quote (char-to-string table-cell-vertical-char)))
5094 (intersection-str (regexp-quote (char-to-string table-cell-intersection-char)))
5095 (v-border (format "[%c%c]" table-cell-vertical-char table-cell-intersection-char))
e99add21 5096 (h-border (format "[%s%c]" table-cell-horizontal-chars table-cell-intersection-char))
5ed619e0 5097 (limit (line-end-position)))
238240c9
RS
5098 (catch 'end
5099 (while t
5100 (catch 'retry-horizontal
5101 (if (not (search-forward-regexp v-border limit t))
5102 (throw 'end nil))
5103 (save-excursion
5104 (forward-char -1)
5105 (let ((column (current-column)))
5106 (while t
5107 (catch 'retry-vertical
5108 (while (and (looking-at vertical-str)
5109 (= column (current-column)))
5110 (if (and (zerop (forward-line 1)) (zerop (current-column))) nil (throw 'end nil))
5111 (move-to-column column))
5112 (cond
5113 ((/= column (current-column))
5114 (throw 'end nil))
5115 ((save-excursion (forward-char -1) (looking-at (concat h-border intersection-str)))
5116 (save-excursion
5117 (and (zerop (forward-line -1))
5118 (move-to-column column)
5119 (looking-at v-border)
5120 (throw 'end (point))))
5121 (forward-char 1)
5122 (throw 'retry-horizontal nil))
5123 ((looking-at intersection-str)
5124 (if (and (zerop (forward-line 1)) (zerop (current-column))) nil (throw 'end nil))
5125 (move-to-column column)
5126 (throw 'retry-vertical nil))
5127 (t (throw 'retry-horizontal nil)))))))))))))
5128
5129(defun table--editable-cell-p (&optional abort-on-error)
5130 (and (not buffer-read-only)
951f97e6 5131 (get-text-property (point) 'table-cell)))
238240c9
RS
5132
5133(defun table--probe-cell (&optional abort-on-error)
5134 "Probes a table cell around the point.
5135Searches for the left upper corner and the right bottom corner of a table
5136cell which contains the current point location.
5137
5138The result is a cons cell (left-upper . right-bottom) where
5139the left-upper is the position before the cell's left upper corner character,
5140the right-bottom is the position after the cell's right bottom corner character.
5141
5142When it fails to find either one of the cell corners it returns nil or
5143signals error if the optional ABORT-ON-ERROR is non-nil."
5144 (let (lu rb
e99add21
JB
5145 (border (format "^[%s%c%c]+$"
5146 table-cell-horizontal-chars
238240c9
RS
5147 table-cell-vertical-char
5148 table-cell-intersection-char)))
5149 (if (and (condition-case nil
5150 (progn
5151 (and (setq lu (table--probe-cell-left-up))
5152 (setq rb (table--probe-cell-right-bottom))))
5153 (error nil))
5154 (< lu rb)
5155 (let ((lu-coordinate (table--get-coordinate lu))
5156 (rb-coordinate (table--get-coordinate rb)))
5157 ;; test for valid upper and lower borders
5158 (and (string-match
5159 border
5160 (buffer-substring
5161 (save-excursion
5162 (table--goto-coordinate
5163 (cons (1- (car lu-coordinate))
5164 (1- (cdr lu-coordinate)))))
5165 (save-excursion
5166 (table--goto-coordinate
5167 (cons (1+ (car rb-coordinate))
5168 (1- (cdr lu-coordinate)))))))
5169 (string-match
5170 border
5171 (buffer-substring
5172 (save-excursion
5173 (table--goto-coordinate
5174 (cons (1- (car lu-coordinate))
5175 (1+ (cdr rb-coordinate)))))
5176 (save-excursion
5177 (table--goto-coordinate
5178 (cons (1+ (car rb-coordinate))
5179 (1+ (cdr rb-coordinate))))))))))
5180 (cons lu rb)
5181 (if abort-on-error
5182 (error "Table cell not found")
5183 nil))))
5184
5185(defun table--insert-rectangle (rectangle)
5186 "Insert text of RECTANGLE with upper left corner at point.
5187Same as insert-rectangle except that mark operation is eliminated."
5188 (let ((lines rectangle)
5189 (insertcolumn (current-column))
5190 (first t))
5191 (while lines
5192 (or first
5193 (progn
5194 (forward-line 1)
5195 (or (bolp) (insert ?\n))
5196 (move-to-column insertcolumn t)))
5197 (setq first nil)
5198 (insert (car lines))
5199 (setq lines (cdr lines)))))
5200
5201(defun table--put-cell-property (cell)
5202 "Put standard text properties to the CELL.
5203The CELL is a cons cell (left-upper . right-bottom) where the
5204left-upper is the position before the cell's left upper corner
5205character, the right-bottom is the position after the cell's right
5206bottom corner character."
5207 (let ((lu (table--get-coordinate (car cell)))
5208 (rb (table--get-coordinate (cdr cell))))
5209 (save-excursion
5210 (while (<= (cdr lu) (cdr rb))
5211 (let ((beg (table--goto-coordinate lu 'no-extension))
5212 (end (table--goto-coordinate (cons (car rb) (cdr lu)))))
5213 (table--put-cell-line-property beg end))
5214 (setcdr lu (1+ (cdr lu))))
5215 (table--put-cell-justify-property cell table-cell-info-justify)
5216 (table--put-cell-valign-property cell table-cell-info-valign))))
5217
5218(defun table--put-cell-line-property (beg end &optional object)
5219 "Put standard text properties to a line of a cell.
5220BEG is the beginning of the line that is the location between left
5221cell border character and the first content character. END is the end
5222of the line that is the location between the last content character
5223and the right cell border character."
5224 (table--put-cell-content-property beg end object)
5225 (table--put-cell-keymap-property end (1+ end) object)
5226 (table--put-cell-indicator-property end (1+ end) object)
5227 (table--put-cell-rear-nonsticky end (1+ end) object))
5228
5229(defun table--put-cell-content-property (beg end &optional object)
5230 "Put cell content text properties."
5231 (table--put-cell-keymap-property beg end object)
5232 (table--put-cell-indicator-property beg end object)
5233 (table--put-cell-face-property beg end object)
5234 (table--put-cell-point-entered/left-property beg end object))
5235
5236(defun table--put-cell-indicator-property (beg end &optional object)
5237 "Put cell property which indicates that the location is within a table cell."
d6db9101
EZ
5238 (put-text-property beg end 'table-cell t object)
5239 (put-text-property beg end 'yank-handler table-yank-handler object))
238240c9
RS
5240
5241(defun table--put-cell-face-property (beg end &optional object)
5242 "Put cell face property."
b4c925d8 5243 (put-text-property beg end 'face 'table-cell object))
238240c9
RS
5244
5245(defun table--put-cell-keymap-property (beg end &optional object)
5246 "Put cell keymap property."
5247 (put-text-property beg end 'keymap 'table-cell-map object))
5248
5249(defun table--put-cell-rear-nonsticky (beg end &optional object)
5250 "Put rear-nonsticky property."
5251 (put-text-property beg end 'rear-nonsticky t object))
db95369b 5252
238240c9
RS
5253(defun table--put-cell-point-entered/left-property (beg end &optional object)
5254 "Put point-entered/left property."
5255 (put-text-property beg end 'point-entered 'table--point-entered-cell-function object)
5256 (put-text-property beg end 'point-left 'table--point-left-cell-function object))
5257
5258(defun table--remove-cell-properties (beg end &optional object)
5259 "Remove all cell properties.
5260If OBJECT is non-nil cell properties are removed from the OBJECT
5261instead of the current buffer and returns the OBJECT."
5262 (while (< beg end)
5263 (let ((next (next-single-property-change beg 'table-cell object end)))
5264 (if (get-text-property beg 'table-cell object)
5265 (remove-text-properties beg next
5266 (list
5267 'table-cell nil
5268 'table-justify nil
5269 'table-valign nil
5270 'face nil
5271 'rear-nonsticky nil
5272 'point-entered nil
5273 'point-left nil
5274 'keymap nil)
5275 object))
5276 (setq beg next)))
5277 object)
5278
5279(defun table--update-cell-face ()
5280 "Update cell face according to the current mode."
5281 (if (featurep 'xemacs)
b4c925d8
MB
5282 (set-face-property 'table-cell 'underline table-fixed-width-mode)
5283 (set-face-inverse-video-p 'table-cell table-fixed-width-mode)))
238240c9
RS
5284
5285(table--update-cell-face)
5286
5287(defun table--get-property (cell property)
5288 "Get CELL's PROPERTY."
5289 (or (get-text-property (car cell) property)
5290 (get-text-property (1- (cdr cell)) property)))
5291
5292(defun table--get-cell-justify-property (cell)
5293 "Get cell's justify property."
5294 (table--get-property cell 'table-justify))
5295
5296(defun table--get-cell-valign-property (cell)
5297 "Get cell's vertical alignment property."
5298 (table--get-property cell 'table-valign))
5299
5300(defun table--put-property (cell property value)
5301 "Put CELL's PROPERTY the VALUE."
5302 (let ((beg (car cell))
5303 (end (cdr cell)))
5304 (put-text-property beg (1+ beg) property value)
5305 (put-text-property (1- end) end property value)))
5306
5307(defun table--put-cell-justify-property (cell justify)
5308 "Put cell's justify property."
5309 (table--put-property cell 'table-justify justify))
5310
5311(defun table--put-cell-valign-property (cell valign)
5312 "Put cell's vertical alignment property."
5313 (table--put-property cell 'table-valign valign))
5314
5315(defun table--point-entered-cell-function (&optional old-point new-point)
5316 "Point has entered a cell.
5317Refresh the menu bar."
250495a7
MR
5318 ;; Avoid calling point-motion-hooks recursively.
5319 (let ((inhibit-point-motion-hooks t))
5320 (unless table-cell-entered-state
5321 (setq table-cell-entered-state t)
5322 (setq table-mode-indicator t)
5323 (force-mode-line-update)
5324 (table--warn-incompatibility)
5325 (run-hooks 'table-point-entered-cell-hook))))
238240c9
RS
5326
5327(defun table--point-left-cell-function (&optional old-point new-point)
5328 "Point has left a cell.
5329Refresh the menu bar."
250495a7
MR
5330 ;; Avoid calling point-motion-hooks recursively.
5331 (let ((inhibit-point-motion-hooks t))
5332 (when table-cell-entered-state
5333 (setq table-cell-entered-state nil)
5334 (setq table-mode-indicator nil)
5335 (force-mode-line-update)
5336 (run-hooks 'table-point-left-cell-hook))))
238240c9
RS
5337
5338(defun table--warn-incompatibility ()
5339 "If called from interactive operation warn the know incompatibilities.
5340This feature is disabled when `table-disable-incompatibility-warning'
5341is non-nil. The warning is done only once per session for each item."
5342 (unless (and table-disable-incompatibility-warning
32226619 5343 (not (called-interactively-p 'interactive)))
238240c9
RS
5344 (cond ((and (featurep 'xemacs)
5345 (not (get 'table-disable-incompatibility-warning 'xemacs)))
5346 (put 'table-disable-incompatibility-warning 'xemacs t)
047ecb4e 5347 (display-warning 'table
238240c9
RS
5348 "
5349*** Warning ***
5350
5351Table package mostly works fine under XEmacs, however, due to the
5352peculiar implementation of text property under XEmacs, cell splitting
5353and any undo operation of table exhibit some known strange problems,
5354such that a border characters dissolve into adjacent cells. Please be
5355aware of this.
5356
5357"
047ecb4e 5358 :warning))
238240c9
RS
5359 ((and (boundp 'flyspell-mode)
5360 flyspell-mode
5361 (not (get 'table-disable-incompatibility-warning 'flyspell)))
5362 (put 'table-disable-incompatibility-warning 'flyspell t)
047ecb4e 5363 (display-warning 'table
238240c9
RS
5364 "
5365*** Warning ***
5366
5367Flyspell minor mode is known to be incompatible with this table
855b42a2 5368package. The flyspell version 1.5d at URL `http://kaolin.unice.fr/~serrano'
238240c9
RS
5369works better than the previous versions however not fully compatible.
5370
5371"
047ecb4e 5372 :warning))
238240c9
RS
5373 )))
5374
5375(defun table--cell-blank-str (&optional n)
5376 "Return blank table cell string of length N."
ec85195e 5377 (let ((str (make-string (or n 1) ?\s)))
238240c9
RS
5378 (table--put-cell-content-property 0 (length str) str)
5379 str))
5380
5381(defun table--remove-eol-spaces (beg end &optional bol force)
5382 "Remove spaces at the end of each line in the BEG END region of the current buffer.
5383When optional BOL is non-nil spaces at the beginning of line are
5384removed. When optional FORCE is non-nil removal operation is enforced
5385even when point is within the removal area."
5386 (if (> beg end)
5387 (let ((tmp beg))
5388 (setq beg end)
5389 (setq end tmp)))
5390 (let ((saved-point (point-marker))
5391 (end-marker (copy-marker end)))
5392 (save-excursion
5393 (goto-char beg)
5394 (while (if bol (re-search-forward "^\\( +\\)" end-marker t)
5395 (re-search-forward "\\( +\\)$" end-marker t))
5396 ;; avoid removal that causes the saved point to lose its location.
5397 (if (and (null bol)
5398 (<= (match-beginning 1) saved-point)
5399 (<= saved-point (match-end 1))
5400 (not force))
5401 (delete-region saved-point (match-end 1))
5402 (delete-region (match-beginning 1) (match-end 1)))))
5403 (set-marker saved-point nil)
5404 (set-marker end-marker nil)))
5405
5406(defun table--fill-region (beg end &optional col justify)
5407 "Fill paragraphs in table cell cache.
5408Current buffer must already be set to the cache buffer."
5409 (let ((fill-column (or col table-cell-info-width))
5410 (fill-prefix nil)
5411 (enable-kinsoku nil)
5412 (adaptive-fill-mode nil)
5413 (marker-beg (copy-marker beg))
5414 (marker-end (copy-marker end))
5415 (marker-point (point-marker)))
5416 (setq justify (or justify table-cell-info-justify))
5417 (and justify
5418 (not (eq justify 'left))
5419 (not (featurep 'xemacs))
5420 (set-marker-insertion-type marker-point t))
5421 (table--remove-eol-spaces (point-min) (point-max))
5422 (if table-fixed-width-mode
5423 (table--fill-region-strictly marker-beg marker-end)
5424 (let ((paragraph-start table-paragraph-start))
5425 (fill-region marker-beg marker-end justify nil t)))
5426 (goto-char marker-point)
5427 (set-marker marker-beg nil)
5428 (set-marker marker-end nil)
5429 (set-marker marker-point nil)))
5430
5431(defun table--fill-region-strictly (beg end)
5432 "Fill region strictly so that no line exceeds fill-column.
5433When a word exceeds fill-column the word is chopped into pieces. The
5434chopped location is indicated with table-word-continuation-char."
5435 (or (and (markerp beg) (markerp end))
5436 (error "markerp"))
5437 (if (< fill-column 2)
5438 (setq fill-column 2))
5439 ;; first remove all continuation characters.
5440 (goto-char beg)
5441 (while (re-search-forward (concat
5442 (format "[^%c ]\\(" table-word-continuation-char)
5443 (regexp-quote (char-to-string table-word-continuation-char))
5444 "\\s +\\)")
5445 end t)
5446 (delete-region (match-beginning 1) (match-end 1)))
5447 ;; then fill as normal
5448 (let ((paragraph-start table-paragraph-start))
5449 (fill-region beg end nil nil t))
5450 ;; now fix up
5451 (goto-char beg)
5452 (while (let ((col (move-to-column fill-column t)))
5453 (cond
5454 ((and (<= col fill-column)
5455 (looking-at " *$"))
5456 (delete-region (match-beginning 0) (match-end 0))
5457 (and (zerop (forward-line 1))
5458 (< (point) end)))
5459 (t (forward-char -1)
ec85195e 5460 (insert-before-markers (if (equal (char-before) ?\s) ?\s table-word-continuation-char)
238240c9
RS
5461 "\n")
5462 t)))))
5463
5464(defun table--goto-coordinate (coordinate &optional no-extension no-tab-expansion)
5465 "Move point to the given COORDINATE and return the location.
5466When optional NO-EXTENSION is non-nil and the specified coordinate is
5467not reachable returns nil otherwise the blanks are added if necessary
5468to achieve the goal coordinate and returns the goal point. It
5469intentionally does not preserve the original point in case it fails
5470achieving the goal. When optional NO-TAB-EXPANSION is non-nil and the
5471goad happens to be in a tab character the tab is not expanded but the
5472goal ends at the beginning of tab."
5473 (if (or (null coordinate)
5474 (< (car coordinate) 0)
5475 (< (cdr coordinate) 0)) nil
5476 (goto-char (point-min))
5477 (let ((x (car coordinate))
5478 (more-lines (forward-line (cdr coordinate))))
5479 (catch 'exit
5480 (if (zerop (current-column)) nil
5481 (if no-extension
5482 (progn
5483 (move-to-column x)
5484 (throw 'exit nil))
5485 (setq more-lines (1+ more-lines))))
5486 (if (zerop more-lines) nil
5487 (newline more-lines))
5488 (if no-extension
5489 (if (/= (move-to-column x) x)
5490 (if (> (move-to-column x) x)
5491 (if no-tab-expansion
5492 (progn
5493 (while (> (move-to-column x) x)
5494 (setq x (1- x)))
5495 (point))
5496 (throw 'exit (move-to-column x t)))
5497 (throw 'exit nil)))
5498 (move-to-column x t))
5499 (point)))))
5500
5501(defun table--copy-coordinate (coord)
5502 "Copy coordinate in a new cons cell."
5503 (cons (car coord) (cdr coord)))
5504
5505(defun table--get-coordinate (&optional where)
5506 "Return the coordinate of point in current buffer.
5507When optional WHERE is given it returns the coordinate of that
5508location instead of point in the current buffer. It does not move the
5509point"
5510 (save-excursion
5511 (if where (goto-char where))
5512 (cons (current-column)
5513 (table--current-line))))
5514
5515(defun table--current-line (&optional location)
5516 "Return zero based line count of current line or if non-nil LOCATION line."
5517 (save-excursion
5518 (if location (goto-char location))
5519 (beginning-of-line)
5520 (count-lines (point-min) (point))))
5521
5522(defun table--transcoord-table-to-cache (&optional coordinate)
5523 "Transpose COORDINATE from table coordinate system to cache coordinate system.
5524When COORDINATE is omitted or nil the point in current buffer is assumed in place."
5525 (table--offset-coordinate
5526 (or coordinate (table--get-coordinate))
5527 table-cell-info-lu-coordinate
5528 'negative))
5529
5530(defun table--transcoord-cache-to-table (&optional coordinate)
5531 "Transpose COORDINATE from cache coordinate system to table coordinate system.
5532When COORDINATE is omitted or nil the point in current buffer is assumed in place."
5533 (table--offset-coordinate
5534 (or coordinate (table--get-coordinate))
5535 table-cell-info-lu-coordinate))
5536
5537(defun table--offset-coordinate (coordinate offset &optional negative)
e1dbe924 5538 "Return the offset COORDINATE by OFFSET.
238240c9
RS
5539When optional NEGATIVE is non-nil offsetting direction is negative."
5540 (cons (if negative (- (car coordinate) (car offset))
5541 (+ (car coordinate) (car offset)))
5542 (if negative (- (cdr coordinate) (cdr offset))
5543 (+ (cdr coordinate) (cdr offset)))))
5544
5545(defun table--char-in-str-at-column (str column)
5546 "Return the character in STR at COLUMN location.
5547When COLUMN is out of range it returns null character."
5548 (let ((idx (table--str-index-at-column str column)))
5549 (if idx (aref str idx)
5550 ?\0)))
5551
5552(defun table--str-index-at-column (str column)
5553 "Return the character index in STR that corresponds to COLUMN location.
5554It returns COLUMN unless STR contains some wide characters."
5555 (let ((col 0)
5556 (idx 0)
5557 (len (length str)))
5558 (while (and (< col column) (< idx len))
5559 (setq col (+ col (char-width (aref str idx))))
5560 (setq idx (1+ idx)))
5561 (if (< idx len)
5562 idx
5563 nil)))
5564
5565(defun table--set-timer (seconds func args)
5566 "Generic wrapper for setting up a timer."
5567 (if (featurep 'xemacs)
5568 ;; the picky xemacs refuses to accept zero
5569 (add-timeout (if (zerop seconds) 0.01 seconds) func args nil)
5570 ;;(run-at-time seconds nil func args)))
5571 ;; somehow run-at-time causes strange problem under Emacs 20.7
5572 ;; this problem does not show up under Emacs 21.0.90
5573 (run-with-idle-timer seconds nil func args)))
5574
5575(defun table--cancel-timer (timer)
5576 "Generic wrapper for canceling a timer."
5577 (if (featurep 'xemacs)
5578 (disable-timeout timer)
5579 (cancel-timer timer)))
5580
5581(defun table--get-last-command ()
5582 "Generic wrapper for getting the real last command."
5583 (if (boundp 'real-last-command)
5584 real-last-command
5585 last-command))
5586
5587(run-hooks 'table-load-hook)
5588
5589(provide 'table)
5590
238240c9 5591;;; table.el ends here