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