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