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