table.el 230 KB
Newer Older
Richard M. Stallman's avatar
Richard M. Stallman committed
1 2
;;; table.el --- create and edit WYSIWYG text based embedded tables

3 4
;; Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005
;;           Free Software Foundation, Inc.
Richard M. Stallman's avatar
Richard M. Stallman committed
5 6 7 8

;; Keywords: wp, convenience
;; Author: Takaaki Ota <Takaaki.Ota@am.sony.com>
;; Created: Sat Jul 08 2000 13:28:45 (PST)
9
;; Revised: Fri Mar 18 2005 13:50:13 (PST)
Richard M. Stallman's avatar
Richard M. Stallman committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648

;; This file is part of GNU Emacs.

;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.

;;; Commentary:

;; -------------
;; Introduction:
;; -------------
;;
;; This package provides text based table creation and editing
;; feature.  With this package Emacs is capable of editing tables that
;; are embedded inside a text document, the feature similar to the
;; ones seen in modern WYSIWYG word processors.  A table is a
;; rectangular text area consisting from a surrounding frame and
;; content inside the frame.  The content is usually subdivided into
;; multiple rectangular cells, see the actual tables used below in
;; this document.  Once a table is recognized, editing operation
;; inside a table cell is confined into that specific cell's
;; rectangular area.  This means that typing and deleting characters
;; inside a cell do not affect any outside text but introduces
;; appropriate formatting only to the cell contents.  If necessary for
;; accommodating added text in the cell, the cell automatically grows
;; vertically and/or horizontally.  The package uses no major mode nor
;; minor mode for its implementation because the subject text is
;; localized within a buffer.  Therefore the special behaviors inside
;; a table cells are implemented by using keymap text property
;; instead of buffer wide mode-map.
;;
;;
;; -----------
;; Background:
;; -----------
;;
;; Paul Georgief is one of my best friends.  He became an Emacs
;; convert after I recommended him trying it several years ago.  Now
;; we both are devoted disciples of Emacsism and elisp cult.  One day
;; in his Emacs exploration he asked me "Tak, what is a command to
;; edit tables in Emacs?".  This question started my journey of this
;; table package development.  May the code be with me!  In the
;; software world Emacs is probably one of the longest lifetime record
;; holders.  Amazingly there have been no direct support for WYSIWYG
;; table editing tasks in Emacs.  Many people must have experienced
;; manipulating existing overwrite-mode and picture-mode for this task
;; and only dreamed of having such a lisp package which supports this
;; specific task directly.  Certainly, I have been one of them.  The
;; most difficult part of dealing with table editing in Emacs probably
;; is how to realize localized rectangular editing effect.  Emacs has
;; no rectangular narrowing mechanism.  Existing rect package provides
;; basically kill, delete and yank operations of a rectangle, which
;; internally is a mere list of strings.  A simple approach for
;; realizing the localized virtual rectangular operation is combining
;; rect package capability with a temporary buffer.  Insertion and
;; deletion of a character to a table cell can be trapped by a
;; function that copies the cell rectangle to a temporary buffer then
;; apply the insertion/deletion to the temporary contents.  Then it
;; formats the contents by filling the paragraphs in order to fit it
;; into the original rectangular area and finally copy it back to the
;; original buffer.  This simplistic approach has to bear with
;; significant performance hit.  As cell grows larger the copying
;; rectangle back and forth between the original buffer and the
;; temporary buffer becomes expensive and unbearably slow.  It was
;; completely impractical and an obvious failure.  An idea has been
;; borrowed from the original Emacs design to overcome this
;; shortcoming.  When the terminal screen update was slow and
;; expensive Emacs employed a clever algorithm to reduce actual screen
;; update by removing redundant redrawing operations.  Also the actual
;; redrawing was done only when there was enough idling time.  This
;; technique significantly improved the previously mentioned
;; undesirable situation.  Now the original buffer's rectangle is
;; copied into a cache buffer only once.  Any cell editing operation
;; is done only to the cache contents.  When there is enough idling
;; time the original buffer's rectangle is updated with the current
;; cache contents.  This delayed operation is implemented by using
;; Emacs's timer function.  To reduce the visual awkwardness
;; introduced by the delayed effect the cursor location is updated in
;; real-time as a user types while the cell contents remains the same
;; until the next idling time.  A key to the success of this approach
;; is how to maintain cache coherency.  As a user moves point in and
;; out of a cell the table buffer contents and the cache buffer
;; contents must be synchronized without a mistake.  By observing user
;; action carefully this is possible however not easy.  Once this
;; mechanism is firmly implemented the rest of table features grew in
;; relatively painless progression.  Those users who are familiar with
;; Emacs internals appreciate this table package more.  Because it
;; demonstrates how extensible Emacs is by showing something that
;; appears like a magic.  It lets you re-discover the potential of
;; Emacs.
;;
;;
;; -------------
;; Entry Points:
;; -------------
;;
;; If this is the first time for you to try this package, go ahead and
;; load the package by M-x `load-file' RET.  Specify the package file
;; name "table.el".  Then switch to a new test buffer and issue the
;; command M-x `table-insert' RET.  It'll ask you number of columns,
;; number of rows, cell width and cell height.  Give some small
;; numbers for each of them.  Play with the resulted table for a
;; while.  If you have menu system find the item "Table" under "Tools"
;; and "Table" in the menu bar when the point is in a table cell.
;; Some of them are pretty intuitive and you can easily guess what
;; they do.  M-x `describe-function' and get the documentation of
;; `table-insert'.  The document includes a short tutorial.  When you
;; are tired of guessing how it works come back to this document
;; again.
;;
;; To use the package regularly place this file in the site library
;; directory and add the next expression in your .emacs file.  Make
;; sure that directory is included in the `load-path'.
;;
;;   (require 'table)
;;
;; Have the next expression also, if you want always be ready to edit
;; tables inside text files.  This mechanism is analogous to
;; fontification in a sense that tables are recognized at editing time
;; without having table information saved along with the text itself.
;;
;;   (add-hook 'text-mode-hook 'table-recognize)
;;
;; Following is a table of entry points and brief description of each
;; of them.  The tables below are of course generated and edited by
;; using this package.  Not all the commands are bound to keys.  Many
;; of them must be invoked by "M-x" (`execute-extended-command')
;; command.  Refer to the section "Keymap" below for the commands
;; available from keys.
;;
;; +------------------------------------------------------------------+
;; |                    User Visible Entry Points                     |
;; +-------------------------------+----------------------------------+
;; |           Function            |           Description            |
;; +-------------------------------+----------------------------------+
;; |`table-insert'                 |Insert a table consisting of grid |
;; |                               |of cells by specifying the number |
;; |                               |of COLUMNS, number of ROWS, cell  |
;; |                               |WIDTH and cell HEIGHT.            |
;; +-------------------------------+----------------------------------+
;; |`table-insert-row'             |Insert row(s) of cells before the |
;; |                               |current row that matches the      |
;; |                               |current row structure.            |
;; +-------------------------------+----------------------------------+
;; |`table-insert-column'          |Insert column(s) of cells before  |
;; |                               |the current column that matches   |
;; |                               |the current column structure.     |
;; +-------------------------------+----------------------------------+
;; |`table-delete-row'             |Delete row(s) of cells.  The row  |
;; |                               |must consist from cells of the    |
;; |                               |same height.                      |
;; +-------------------------------+----------------------------------+
;; |`table-delete-column'          |Delete column(s) of cells.  The   |
;; |                               |column must consist from cells of |
;; |                               |the same width.                   |
;; +-------------------------------+----------------------------------+
;; |`table-recognize'              |Recognize all tables in the       |
;; |`table-unrecognize'            |current buffer and                |
;; |                               |activate/inactivate them.         |
;; +-------------------------------+----------------------------------+
;; |`table-recognize-region'       |Recognize all the cells in a      |
;; |`table-unrecognize-region'     |region and activate/inactivate    |
;; |                               |them.                             |
;; +-------------------------------+----------------------------------+
;; |`table-recognize-table'        |Recognize all the cells in a      |
;; |`table-unrecognize-table'      |single table and                  |
;; |                               |activate/inactivate them.         |
;; +-------------------------------+----------------------------------+
;; |`table-recognize-cell'         |Recognize a cell.  Find a cell    |
;; |`table-unrecognize-cell'       |which contains the current point  |
;; |                               |and activate/inactivate that cell.|
;; +-------------------------------+----------------------------------+
;; |`table-forward-cell'           |Move point to the next Nth cell in|
;; |                               |a table.                          |
;; +-------------------------------+----------------------------------+
;; |`table-backward-cell'          |Move point to the previous Nth    |
;; |                               |cell in a table.                  |
;; +-------------------------------+----------------------------------+
;; |`table-span-cell'              |Span the current cell toward the  |
;; |                               |specified direction and merge it  |
;; |                               |with the adjacent cell.  The      |
;; |                               |direction is right, left, above or|
;; |                               |below.                            |
;; +-------------------------------+----------------------------------+
;; |`table-split-cell-vertically'  |Split the current cell vertically |
;; |                               |and create a cell above and a cell|
;; |                               |below the point location.         |
;; +-------------------------------+----------------------------------+
;; |`table-split-cell-horizontally'|Split the current cell            |
;; |                               |horizontally and create a cell on |
;; |                               |the left and a cell on the right  |
;; |                               |of the point location.            |
;; +-------------------------------+----------------------------------+
;; |`table-split-cell'             |Split the current cell vertically |
;; |                               |or horizontally.  This is a       |
;; |                               |wrapper command to the other two  |
;; |                               |orientation specific commands.    |
;; +-------------------------------+----------------------------------+
;; |`table-heighten-cell'          |Heighten the current cell.        |
;; +-------------------------------+----------------------------------+
;; |`table-shorten-cell'           |Shorten the current cell.         |
;; +-------------------------------+----------------------------------+
;; |`table-widen-cell'             |Widen the current cell.           |
;; +-------------------------------+----------------------------------+
;; |`table-narrow-cell'            |Narrow the current cell.          |
;; +-------------------------------+----------------------------------+
;; |`table-fixed-width-mode'       |Toggle fixed width mode.  In the  |
;; |                               |fixed width mode, typing inside a |
;; |                               |cell never changes the cell width,|
;; |                               |while in the normal mode the cell |
;; |                               |width expands automatically in    |
;; |                               |order to prevent a word being     |
;; |                               |folded into multiple lines.  Fixed|
;; |                               |width mode reverses video or      |
;; |                               |underline the cell contents for   |
;; |                               |its indication.                   |
;; +-------------------------------+----------------------------------+
;; |`table-query-dimension'        |Compute and report the current    |
;; |                               |cell dimension, current table     |
;; |                               |dimension and the number of       |
;; |                               |columns and rows in the table.    |
;; +-------------------------------+----------------------------------+
;; |`table-generate-source'        |Generate the source of the current|
;; |                               |table in the specified language   |
;; |                               |and insert it into a specified    |
;; |                               |buffer.                           |
;; +-------------------------------+----------------------------------+
;; |`table-insert-sequence'        |Travel cells forward while        |
;; |                               |inserting a specified sequence    |
;; |                               |string into each cell.            |
;; +-------------------------------+----------------------------------+
;; |`table-capture'                |Convert plain text into a table by|
;; |                               |capturing the text in the region. |
;; +-------------------------------+----------------------------------+
;; |`table-release'                |Convert a table into plain text by|
;; |                               |removing the frame from a table.  |
;; +-------------------------------+----------------------------------+
;; |`table-justify'                |Justify the contents of cell(s).  |
;; +-------------------------------+----------------------------------+
;;
;;
;; *Note*
;;
;; You may find that some of commonly expected table commands are
;; missing such as copying a row/column and yanking it.  Those
;; functions can be obtained through existing Emacs text editing
;; commands.  Rows are easily manipulated with region commands and
;; columns can be copied and pasted through rectangle commands.  After
;; all a table is still a part of text in the buffer.  Only the
;; special behaviors exist inside each cell through text properties.
;;
;; `table-generate-html' which appeared in earlier releases is
;; deprecated in favor of `table-generate-source'.  Now HTML is
;; treated as one of the languages used for describing the table's
;; logical structure.
;;
;;
;; -------
;; Keymap:
;; -------
;;
;; Although this package does not use a mode it does use its own
;; keymap inside a table cell by way of keymap text property.  Some of
;; the standard basic editing commands bound to certain keys are
;; replaced with the table specific version of corresponding commands.
;; This replacement combination is listed in the constant alist
;; `table-command-remap-alist' declared below.  This alist is
;; not meant to be user configurable but mentioned here for your
;; better understanding of using this package.  In addition, table
;; cells have some table specific bindings for cell navigation and
;; cell reformation.  You can find these additional bindings in the
;; constant `table-cell-bindings'.  Those key bound functions are
;; considered as internal functions instead of normal commands,
;; therefore they have special prefix, *table-- instead of table-, for
;; symbols.  The purpose of this is to make it easier for a user to
;; use command name completion.  There is a "normal hooks" variable
;; `table-cell-map-hook' prepared for users to override the default
;; table cell bindings.  Following is the table of predefined default
;; key bound commands inside a table cell.  Remember these bindings
;; exist only inside a table cell.  When your terminal is a tty, the
;; control modifier may not be available or applicable for those
;; special characters.  In this case use "C-cC-c", which is
;; customizable via `table-command-prefix', as the prefix key
;; sequence.  This should preceding the following special character
;; without the control modifier.  For example, use "C-cC-c|" instead
;; of "C-|".
;;
;; +------------------------------------------------------------------+
;; |                Default Bindings in a Table Cell                  |
;; +-------+----------------------------------------------------------+
;; |  Key  |                      Function                            |
;; +-------+----------------------------------------------------------+
;; |  TAB  |Move point forward to the beginning of the next cell.     |
;; +-------+----------------------------------------------------------+
;; | "C->" |Widen the current cell.                                   |
;; +-------+----------------------------------------------------------+
;; | "C-<" |Narrow the current cell.                                  |
;; +-------+----------------------------------------------------------+
;; | "C-}" |Heighten the current cell.                                |
;; +-------+----------------------------------------------------------+
;; | "C-{" |Shorten the current cell.                                 |
;; +-------+----------------------------------------------------------+
;; | "C--" |Split current cell vertically. (one above and one below)  |
;; +-------+----------------------------------------------------------+
;; | "C-|" |Split current cell horizontally. (one left and one right) |
;; +-------+----------------------------------------------------------+
;; | "C-*" |Span current cell into adjacent one.                      |
;; +-------+----------------------------------------------------------+
;; | "C-+" |Insert row(s)/column(s).                                  |
;; +-------+----------------------------------------------------------+
;; | "C-!" |Toggle between normal mode and fixed width mode.          |
;; +-------+----------------------------------------------------------+
;; | "C-#" |Report cell and table dimension.                          |
;; +-------+----------------------------------------------------------+
;; | "C-^" |Generate the source in a language from the current table. |
;; +-------+----------------------------------------------------------+
;; | "C-:" |Justify the contents of cell(s).                          |
;; +-------+----------------------------------------------------------+
;;
;; *Note*
;;
;; When using `table-cell-map-hook' do not use `local-set-key'.
;;
;;   (add-hook 'table-cell-map-hook
;;     (function (lambda ()
;;       (local-set-key [<key sequence>] '<function>))))
;;
;; Above code is well known ~/.emacs idiom for customizing a mode
;; specific keymap however it does not work for this package.  This is
;; because there is no table mode in effect.  This package does not
;; use a local map therefor you must modify `table-cell-map'
;; explicitly.  The correct way of achieving above task is:
;;
;;   (add-hook 'table-cell-map-hook
;;     (function (lambda ()
;;       (define-key table-cell-map [<key sequence>] '<function>))))
;;
;; -----
;; Menu:
;; -----
;;
;; If a menu system is available a group of table specific menu items,
;; "Table" under "Tools" section of the menu bar, is globally added
;; after this package is loaded.  The commands in this group are
;; limited to the ones that are related to creation and initialization
;; of tables, such as to insert a table, to insert rows and columns,
;; or recognize and unrecognize tables.  Once tables are created and
;; point is placed inside of a table cell a table specific menu item
;; "Table" appears directly on the menu bar.  The commands in this
;; menu give full control on table manipulation that include cell
;; navigation, insertion, splitting, spanning, shrinking, expansion
;; and unrecognizing.  In addition to above two types of menu there is
;; a pop-up menu available within a table cell.  The content of pop-up
;; menu is identical to the full table menu.  [mouse-3] is the default
;; button, defined in `table-cell-bindings', to bring up the pop-up
;; menu.  It can be reconfigured via `table-cell-map-hook'.  The
;; benefit of a pop-up menu is that it combines selection of the
;; location (which cell, where in the cell) and selection of the
;; desired operation into a single clicking action.
;;
;;
;; -------------------------------
;; Definition of tables and cells:
;; -------------------------------
;;
;; There is no artificial-intelligence magic in this package.  The
;; definition of a table and the cells inside the table is reasonably
;; limited in order to achieve acceptable performance in the
;; interactive operation under Emacs lisp implementation.  A valid
;; table is a rectangular text area completely filled with valid
;; cells.  A valid cell is a rectangle text area, which four borders
;; consist of valid border characters.  Cells can not be nested one to
;; another or overlapped to each other except sharing the border
;; lines.  A valid character of a cell's vertical border is either
;; table-cell-vertical-char `|' or table-cell-intersection-char `+'.
;; A valid character of a cell's horizontal border is either
;; table-cell-horizontal-char `-' or table-cell-intersection-char `+'.
;; A valid character of the four corners of a cell must be
;; table-cell-intersection-char `+'.  A cell must contain at least one
;; character space inside.  There is no restriction about the contents
;; of a table cell, however it is advised if possible to avoid using
;; any of the border characters inside a table cell.  Normally a few
;; boarder characters inside a table cell are harmless.  But it is
;; possible that they accidentally align up to emulate a bogus cell
;; corner on which software relies on for cell recognition.  When this
;; happens the software may be fooled by it and fail to determine
;; correct cell dimension.
;;
;; Following are the examples of valid tables.
;;
;; +--+----+---+     +-+     +--+-----+
;; |  |    |   |     | |     |  |     |
;; +--+----+---+     +-+     |  +--+--+
;; |  |    |   |             |  |  |  |
;; +--+----+---+             +--+--+  |
;;                           |     |  |
;;                           +-----+--+
;;
;; The next five tables are the examples of invalid tables.  (From
;; left to right, 1. nested cells 2. overlapped cells and a
;; non-rectangle cell 3. non-rectangle table 4. zero width/height
;; cells 5. zero sized cell)
;;
;; +-----+    +-----+       +--+    +-++--+    ++
;; |     |    |     |       |  |    | ||  |    ++
;; | +-+ |    |     |       |  |    | ||  |
;; | | | |    +--+  |    +--+--+    +-++--+
;; | +-+ |    |  |  |    |  |  |    +-++--+
;; |     |    |  |  |    |  |  |    | ||  |
;; +-----+    +--+--+    +--+--+    +-++--+
;;
;; Although the program may recognizes some of these invalid tables,
;; results from the subsequent editing operations inside those cells
;; are not predictable and will most likely start destroying the table
;; structures.
;;
;; It is strongly recommended to have at least one blank line above
;; and below a table.  For a table to coexist peacefully with
;; surrounding environment table needs to be separated from unrelated
;; text.  This is necessary for the left table to grow or shrink
;; horizontally without breaking the right table in the following
;; example.
;;
;;                          +-----+-----+-----+
;;  +-----+-----+           |     |     |     |
;;  |     |     |           +-----+-----+-----+
;;  +-----+-----+           |     |     |     |
;;                          +-----+-----+-----+
;;
;;
;; -------------------------
;; Cell contents formatting:
;; -------------------------
;;
;; The cell contents are formatted by filling a paragraph immediately
;; after characters are inserted into or deleted from a cell.  Because
;; of this, cell contents always remain fit inside a cell neatly.  One
;; drawback of this is that users do not have full control over
;; spacing between words and line breaking.  Only one space can be
;; entered between words and up to two spaces between sentences.  For
;; a newline to be effective the new line must form a beginning of
;; paragraph, otherwise it'll automatically be merged with the
;; previous line in a same paragraph.  To form a new paragraph the
;; line must start with some space characters or immediately follow a
;; blank line.  Here is a typical example of how to list items within
;; a cell.  Without a space at the beginning of each line the items
;; can not stand on their own.
;;
;; +---------------------------------+
;; |Each one of the following three  |
;; |items starts with a space        |
;; |character thus forms a paragraph |
;; |of its own.  Limitations in cell |
;; |contents formatting are:         |
;; |                                 |
;; | 1. Only one space between words.|
;; | 2. Up to two spaces between     |
;; |sentences.                       |
;; | 3. A paragraph must start with  |
;; |spaces or follow a blank line.   |
;; |                                 |
;; |This paragraph stays away from   |
;; |the item 3 because there is a    |
;; |blank line between them.         |
;; +---------------------------------+
;;
;; In the normal operation table cell width grows automatically when
;; certain word has to be folded into the next line if the width had
;; not been increased.  This normal operation is useful and
;; appropriate for most of the time, however, it is sometimes useful
;; or necessary to fix the width of table and width of table cells.
;; For this purpose the package provides fixed width mode.  You can
;; toggle between fixed width mode and normal mode by "C-!".
;;
;; Here is a simple example of the fixed width mode.  Suppose we have
;; a table like this one.
;;
;; +-----+
;; |     |
;; +-----+
;;
;; In normal mode if you type a word "antidisestablishmentarianism" it
;; grows the cell horizontally like this.
;;
;; +----------------------------+
;; |antidisestablishmentarianism|
;; +----------------------------+
;;
;;  In the fixed width mode the same action produces the following
;;  result.  The folded locations are indicated by a continuation
;;  character (`\' is the default).  The continuation character is
;;  treated specially so it is recommended to choose a character that
;;  does not appear elsewhere in table cells.  This character is
;;  configurable via customization and is kept in the variable
;;  `table-word-continuation-char'.  The continuation character is
;;  treated specially only in the fixed width mode and has no special
;;  meaning in the normal mode however.
;;
;; +-----+
;; |anti\|
;; |dise\|
;; |stab\|
;; |lish\|
;; |ment\|
;; |aria\|
;; |nism |
;; +-----+
;;
;;
;; -------------------
;; Cell Justification:
;; -------------------
;;
;; By default the cell contents are filled with left justification and
;; no vertical justification.  A paragraph can be justified
;; individually but only horizontally.  Paragraph justification is for
;; appearance only and does not change any structural information
;; while cell justification affects table's structural information.
;; For cell justification a user can select horizontal justification
;; and vertical justification independently.  Horizontal justification
;; must be one of the three 'left, 'center or 'right.  Vertical
;; justification can be 'top, 'middle, 'bottom or 'none.  When a cell
;; is justified, that information is recorded as a part of text
;; property therefore the information is persistent as long as the
;; cell remains within the Emacs world.  Even copying tables by region
;; and rectangle manipulation commands preserve this information.
;; However, once the table text is saved as a file and the buffer is
;; killed the justification information vanishes permanently.  To
;; alleviate this shortcoming without forcing users to save and
;; maintain a separate attribute file, the table code detects
;; justification of each cell when recognizing a table.  This
;; detection is done by guessing the justification by looking at the
;; appearance of the cell contents.  Since it is a guessing work it
;; does not guarantee the perfectness but it is designed to be
;; practically good enough.  The guessing algorithm is implemented in
;; the function `table--detect-cell-alignment'.  If you have better
;; algorithm or idea any suggestion is welcome.
;;
;;
;; -----
;; Todo: (in the order of priority, some are just possibility)
;; -----
;;
;; Fix compatibilities with other input method than quail
;; Resolve conflict with flyspell
;; Use mouse for resizing cells
;; A mechanism to link cells internally
;; Consider the use of variable width font under Emacs 21
;; Consider the use of `:box' face attribute under Emacs 21
;; Consider the use of `modification-hooks' text property instead of
;; rebinding the keymap
;; Maybe provide complete XEmacs support in the future however the
;; "extent" is the single largest obstacle lying ahead, read the
;; document in Emacs info.
;; (eval '(progn (require 'info) (Info-find-node "elisp" "Not Intervals")))
;;
;;
;; ---------------
;; Acknowledgment:
;; ---------------
;;
;; Table would not have been possible without the help and
;; encouragement of the following spirited contributors.
;;
;; Paul Georgief <georgief@igpp.ucsd.edu> has been the best tester
;; of the code as well as the constructive criticizer.
;;
;; Gerd Moellmann <gerd@gnu.org> gave me useful suggestions from Emacs
;; 21 point of view.
;;
;; Richard Stallman <rms@gnu.org> showed the initial interest in this
;; attempt of implementing the table feature to Emacs.  This greatly
;; motivated me to follow through to its completion.
;;
;; Kenichi Handa <handa@etl.go.jp> kindly guided me through to
;; overcome many technical issues while I was struggling with quail
;; related internationalization problems.
;;
;; Christoph Conrad <christoph.conrad@gmx.de> suggested making symbol
;; names consistent as well as fixing several bugs.
;;
;; Paul Lew <paullew@cisco.com> suggested implementing fixed width
;; mode as well as multi column width (row height) input interface.
;;
;; Michael Smith <smith@xml-doc.org> a well-informed DocBook user
;; asked for CALS table source generation and helped me following
;; through the work by offering valuable suggestions and testing out
;; the code.  Jorge Godoy <godoy@conectiva.com> has also suggested
;; supporting for DocBook tables.
;;
;; And many other individuals who reported bugs and suggestions.

;;; Code:



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Compatibility:
;;;

;; hush up the byte-compiler
(eval-when-compile
  (defvar quail-translating)
  (defvar quail-converting)
  (defvar flyspell-mode)
  (defvar real-last-command)
  (defvar delete-selection-mode)
  (unless (fboundp 'set-face-property)
    (defun set-face-property (face prop value)))
  (unless (fboundp 'unibyte-char-to-multibyte)
    (defun unibyte-char-to-multibyte (char)))
  (defun table--point-in-cell-p (&optional location)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Customization:
;;;

(defgroup table nil
  "Text based table manipulation utilities.
See `table-insert' for examples about how to use."
  :tag "Table"
  :prefix "table-"
  :group 'editing
  :group 'wp
  :group 'paragraphs
649
  :group 'fill
650
  :version "22.1")
Richard M. Stallman's avatar
Richard M. Stallman committed
651

652 653 654 655
(defgroup table-hooks nil
  "Hooks for table manipulation utilities"
  :group 'table)

Richard M. Stallman's avatar
Richard M. Stallman committed
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
(defcustom table-time-before-update 0.2
  "*Time in seconds before updating the cell contents after typing.
Updating the cell contents on the screen takes place only after this
specified amount of time has passed after the last modification to the
cell contents.  When the contents of a table cell changes repetitively
and frequently the updating the cell contents on the screen is
deferred until at least this specified amount of quiet time passes.  A
smaller number wastes more computation resource by unnecessarily
frequent screen update.  A large number presents noticeable and
annoying delay before the typed result start appearing on the screen."
  :tag "Time Before Cell Update"
  :type 'number
  :group 'table)

(defcustom table-time-before-reformat 0.2
  "*Time in seconds before reformatting the table.
This many seconds must pass in addition to `table-time-before-update'
before the table is updated with newly widened width or heightened
height."
  :tag "Time Before Cell Reformat"
  :type 'number
  :group 'table)

(defcustom table-command-prefix [(control c) (control c)]
  "*Key sequence to be used as prefix for table command key bindings."
681
  :type '(vector (repeat :inline t sexp))
Richard M. Stallman's avatar
Richard M. Stallman committed
682 683 684 685 686 687 688 689 690 691 692
  :tag "Table Command Prefix"
  :group 'table)

(defface table-cell-face
  '((((class color))
     (:foreground "gray90" :background "blue"))
    (t (:bold t)))
  "*Face used for table cell contents."
  :tag "Cell Face"
  :group 'table)

693 694 695 696
(defcustom table-cell-horizontal-chars "-="
  "*Characters that may be used for table cell's horizontal border line."
  :tag "Cell Horizontal Boundary Characters"
  :type 'string
Richard M. Stallman's avatar
Richard M. Stallman committed
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
  :group 'table)

(defcustom table-cell-vertical-char ?\|
  "*Character that forms table cell's vertical border line."
  :tag "Cell Vertical Boundary Character"
  :type 'character
  :group 'table)

(defcustom table-cell-intersection-char ?\+
  "*Character that forms table cell's corner."
  :tag "Cell Intersection Character"
  :type 'character
  :group 'table)

(defcustom table-word-continuation-char ?\\
  "*Character that indicates word continuation into the next line.
This character has a special meaning only in the fixed width mode,
that is when `table-fixed-width-mode' is non-nil .  In the fixed width
mode this character indicates that the location is continuing into the
next line.  Be careful about the choice of this character.  It is
treated substantially different manner than ordinary characters.  Try
select a character that is unlikely to appear in your document."
  :tag "Cell Word Continuation Character"
  :type 'character
  :group 'table)

(defun table-set-table-fixed-width-mode (variable value)
  (if (fboundp variable)
      (funcall variable (if value 1 -1))))

(defun table-initialize-table-fixed-width-mode (variable value)
  (set variable value))

(defcustom table-fixed-width-mode nil
  "*Cell width is fixed when this is non-nil.
Normally it should be nil for allowing automatic cell width expansion
that widens a cell when it is necessary.  When non-nil, typing in a
cell does not automatically expand the cell width.  A word that is too
long to fit in a cell is chopped into multiple lines.  The chopped
location is indicated by `table-word-continuation-char'.  This
variable's value can be toggled by \\[table-fixed-width-mode] at
run-time."
  :tag "Fix Cell Width"
  :type 'boolean
  :initialize 'table-initialize-table-fixed-width-mode
  :set 'table-set-table-fixed-width-mode
  :group 'table)

(defcustom table-detect-cell-alignment t
  "*Detect cell contents alignment automatically.
When non-nil cell alignment is automatically determined by the
appearance of the current cell contents when recognizing tables as a
whole.  This applies to `table-recognize', `table-recognize-region'
and `table-recognize-table' but not to `table-recognize-cell'."
  :tag "Detect Cell Alignment"
  :type 'boolean
  :group 'table)

(defcustom table-dest-buffer-name "table"
  "*Default buffer name (without a suffix) for source generation."
  :tag "Source Buffer Name"
  :type 'string
  :group 'table)

(defcustom table-html-delegate-spacing-to-user-agent nil
  "*Non-nil delegates cell contents spacing entirely to user agent.
Otherwise, when nil, it preserves the original spacing and line breaks."
  :tag "HTML delegate spacing"
  :type 'boolean
  :group 'table)

(defcustom table-html-th-rows 0
  "*Number of top rows to become header cells automatically in HTML generation."
  :tag "HTML Header Rows"
  :type 'integer
  :group 'table)

(defcustom table-html-th-columns 0
  "*Number of left columns to become header cells automatically in HTML generation."
  :tag "HTML Header Columns"
  :type 'integer
  :group 'table)

(defcustom table-html-table-attribute "border=\"1\""
  "*Table attribute that applies to the table in HTML generation."
  :tag "HTML table attribute"
  :type 'string
  :group 'table)

(defcustom table-html-cell-attribute ""
  "*Cell attribute that applies to all cells in HTML generation.
Do not specify \"align\" and \"valign\" because they are determined by
the cell contents dynamically."
  :tag "HTML cell attribute"
  :type 'string
  :group 'table)

(defcustom table-cals-thead-rows 1
  "*Number of top rows to become header rows in CALS table."
  :tag "CALS Header Rows"
  :type 'integer
  :group 'table)

;;;###autoload
(defcustom table-cell-map-hook nil
  "*Normal hooks run when finishing construction of `table-cell-map'.
User can modify `table-cell-map' by adding custom functions here."
  :tag "Cell Keymap Hooks"
  :type 'hook
806
  :group 'table-hooks)
Richard M. Stallman's avatar
Richard M. Stallman committed
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841

(defcustom table-disable-incompatibility-warning nil
  "*Disable compatibility warning notice.
When nil user is reminded of known incompatible issues."
  :tag "Disable Incompatibility Warning"
  :type 'boolean
  :group 'table)

(defcustom table-abort-recognition-when-input-pending t
  "*Abort current recognition process when input pending.
Abort current recognition process when we are not sure that no input
is available.  When non-nil lengthy recognition process is aborted
simply by any key input."
  :tag "Abort Recognition When Input Pending"
  :type 'boolean
  :group 'table)

;;;###autoload
(defcustom table-load-hook nil
  "*List of functions to be called after the table is first loaded."
  :type 'hook
  :group 'table-hooks)

;;;###autoload
(defcustom table-point-entered-cell-hook nil
  "*List of functions to be called after point entered a table cell."
  :type 'hook
  :group 'table-hooks)

;;;###autoload
(defcustom table-point-left-cell-hook nil
  "*List of functions to be called after point left a table cell."
  :type 'hook
  :group 'table-hooks)

842 843 844
(defcustom table-yank-handler '(nil nil t nil)
  "*yank-handler for table.")

Richard M. Stallman's avatar
Richard M. Stallman committed
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
(setplist 'table-disable-incompatibility-warning nil)

(defvar table-disable-menu (null (and (locate-library "easymenu")
				      (require 'easymenu)
				      (fboundp 'easy-menu-add-item)))
  "*When non-nil, use of menu by table package is disabled.
It must be set before loading this package `table.el' for the first
time.")


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Implementation:
;;;

;;; Internal variables and constants
;;; No need of user configuration

(defconst table-paragraph-start "[ \t\n\f]"
  "*Regexp for beginning of a line that starts OR separates paragraphs.")
(defconst table-cache-buffer-name " *table cell cache*"
  "Cell cache buffer name.")
(defvar table-cell-info-lu-coordinate nil
  "Zero based coordinate of the cached cell's left upper corner.")
(defvar table-cell-info-rb-coordinate nil
  "Zero based coordinate of the cached cell's right bottom corner.")
(defvar table-cell-info-width nil
  "Number of characters per cached cell width.")
(defvar table-cell-info-height nil
  "Number of lines per cached cell height.")
(defvar table-cell-info-justify nil
  "Justification information of the cached cell.")
(defvar table-cell-info-valign nil
  "Vertical alignment information of the cached cell.")
(defvar table-cell-self-insert-command-count 0
  "Counter for undo control.")
(defvar table-cell-map nil
  "Keymap for table cell contents.")
(defvar table-cell-global-map-alist nil
  "Alist of copy of global maps that are substituted in `table-cell-map'.")
(defvar table-global-menu-map nil
  "Menu map created via `easy-menu-define'.")
(defvar table-cell-menu-map nil
  "Menu map created via `easy-menu-define'.")
(defvar table-cell-buffer nil
  "Buffer that contains the table cell.")
(defvar table-cell-cache-point-coordinate nil
  "Cache point coordinate based from the cell origin.")
(defvar table-cell-cache-mark-coordinate nil
  "Cache mark coordinate based from the cell origin.")
(defvar table-cell-entered-state nil
  "Records the state whether currently in a cell or nor.")
(defvar table-update-timer nil
  "Timer id for deferred cell update.")
(defvar table-widen-timer nil
  "Timer id for deferred cell update.")
(defvar table-heighten-timer nil
  "Timer id for deferred cell update.")
(defvar table-inhibit-update nil
  "Non-nil inhibits implicit cell and cache updates.
It inhibits `table-with-cache-buffer' to update data in both direction, cell to cache and cache to cell.")
(defvar table-inhibit-auto-fill-paragraph nil
  "Non-nil inhibits auto fill paragraph when `table-with-cache-buffer' exits.
This is always set to nil at the entry to `table-with-cache-buffer' before executing body forms.")
(defvar table-mode-indicator nil
  "For mode line indicator")
(defvar table-fixed-mode-indicator nil
  "For mode line indicator")
(defconst table-source-languages '(html latex cals)
  "Supported source languages.")
(defvar table-source-info-plist nil
  "General storage for temporary information used while generating source.")
;;; These are not real minor-mode but placed in the minor-mode-alist
;;; so that we can show the indicator on the mode line handy.
(mapcar (lambda (indicator)
	  (make-variable-buffer-local (car indicator))
	  (unless (assq (car indicator) minor-mode-alist)
	    (setq minor-mode-alist
		  (cons indicator minor-mode-alist))))
	'((table-mode-indicator " Table")
	  (table-fixed-mode-indicator " Fixed-Table")))
;;; The following history containers not only keep the history of user
;;; entries but also serve as the default value providers.  When an
;;; interactive command is invoked it offers a user the latest entry
;;; of the history as a default selection.  Therefore the values below
;;; are the first default value when a command is invoked for the very
;;; first time when there is no real history existing yet.
(defvar table-cell-span-direction-history '("right"))
(defvar table-cell-split-orientation-history '("horizontally"))
(defvar table-cell-split-contents-to-history '("split"))
(defvar table-insert-row-column-history '("row"))
(defvar table-justify-history '("center"))
(defvar table-columns-history '("3"))
(defvar table-rows-history '("3"))
(defvar table-cell-width-history '("5"))
(defvar table-cell-height-history '("1"))
(defvar table-source-caption-history '("Table"))
(defvar table-sequence-string-history '("0"))
(defvar table-sequence-count-history '("0"))
(defvar table-sequence-increment-history '("1"))
(defvar table-sequence-interval-history '("1"))
(defvar table-sequence-justify-history '("left"))
(defvar table-source-language-history '("html"))
(defvar table-col-delim-regexp-history '(""))
(defvar table-row-delim-regexp-history '(""))
(defvar table-capture-justify-history '("left"))
(defvar table-capture-min-cell-width-history '("5"))
(defvar table-capture-columns-history '(""))
(defvar table-target-history '("cell"))

;;; Some entries in `table-cell-bindings' are duplicated in
;;; `table-command-remap-alist'.  There is a good reason for
;;; this.  Common key like return key may be taken by some other
;;; function than normal `newline' function.  Thus binding return key
;;; directly for `*table--cell-newline' ensures that the correct enter
;;; operation in a table cell.  However
;;; `table-command-remap-alist' has an additional role than
;;; replacing commands.  It is also used to construct a table command
;;; list.  This list is very important because it is used to check if
;;; the previous command was one of them in this list or not.  If the
;;; previous command is found in the list the current command will not
;;; refill the table cache.  If the command were not listed fast
;;; typing can cause unwanted cache refill.
(defconst table-cell-bindings
  '(([(control i)]	. table-forward-cell)
    ([(control I)]	. table-backward-cell)
    ([tab]		. table-forward-cell)
    ([(shift backtab)]	. table-backward-cell) ; for HPUX console keyboard
    ([(shift iso-lefttab)]    . table-backward-cell) ; shift-tab on a microsoft natural keyboard and redhat linux
    ([(shift tab)]	. table-backward-cell)
    ([return]		. *table--cell-newline)
    ([(control m)]	. *table--cell-newline)
    ([(control j)]	. *table--cell-newline-and-indent)
    ([mouse-3]		. *table--present-cell-popup-menu)
    ([(control ?>)]	. table-widen-cell)
    ([(control ?<)]	. table-narrow-cell)
    ([(control ?})]	. table-heighten-cell)
    ([(control ?{)]	. table-shorten-cell)
    ([(control ?-)]	. table-split-cell-vertically)
    ([(control ?|)]	. table-split-cell-horizontally)
    ([(control ?*)]	. table-span-cell)
    ([(control ?+)]	. table-insert-row-column)
    ([(control ?!)]	. table-fixed-width-mode)
    ([(control ?#)]	. table-query-dimension)
    ([(control ?^)]	. table-generate-source)
    ([(control ?:)]	. table-justify)
    )
  "Bindings for table cell commands.")

994
(defvar table-command-remap-alist
Richard M. Stallman's avatar
Richard M. Stallman committed
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
  '((self-insert-command . *table--cell-self-insert-command)
    (completion-separator-self-insert-autofilling . *table--cell-self-insert-command)
    (completion-separator-self-insert-command . *table--cell-self-insert-command)
    (delete-char . *table--cell-delete-char)
    (delete-backward-char . *table--cell-delete-backward-char)
    (backward-delete-char . *table--cell-delete-backward-char)
    (backward-delete-char-untabify . *table--cell-delete-backward-char)
    (newline . *table--cell-newline)
    (newline-and-indent . *table--cell-newline-and-indent)
    (open-line . *table--cell-open-line)
    (quoted-insert . *table--cell-quoted-insert)
    (describe-mode . *table--cell-describe-mode)
    (describe-bindings . *table--cell-describe-bindings)
    (dabbrev-expand . *table--cell-dabbrev-expand)
    (dabbrev-completion . *table--cell-dabbrev-completion))
  "List of cons cells consisting of (ORIGINAL-COMMAND . TABLE-VERSION-OF-THE-COMMAND).")

1012
(defvar table-command-list nil
Richard M. Stallman's avatar
Richard M. Stallman committed
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
  "List of commands that override original commands.")
;; construct the real contents of the `table-command-list'
(let ((remap-alist table-command-remap-alist))
  (setq table-command-list nil)
  (while remap-alist
    (setq table-command-list (cons (cdar remap-alist) table-command-list))
    (setq remap-alist (cdr remap-alist))))

(defconst table-global-menu
  '("Table"
    ("Insert"
     ["a Table..." table-insert
      :active (and (not buffer-read-only) (not (table--probe-cell)))
      :help "Insert a text based table at point"]
     ["Row" table-insert-row
1028
      :active (table--row-column-insertion-point-p)
Richard M. Stallman's avatar
Richard M. Stallman committed
1029 1030
      :help "Insert row(s) of cells in table"]
     ["Column" table-insert-column
1031
      :active (table--row-column-insertion-point-p 'column)
Richard M. Stallman's avatar
Richard M. Stallman committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
      :help "Insert column(s) of cells in table"])
    "----"
    ("Recognize"
     ["in Buffer" table-recognize
      :active t
      :help "Recognize all tables in the current buffer"]
     ["in Region" table-recognize-region
      :active (and mark-active (not (eq (mark t) (point))))
      :help "Recognize all tables in the current region"]
     ["a Table" table-recognize-table
      :active (table--probe-cell)
      :help "Recognize a table at point"]
     ["a Cell" table-recognize-cell
      :active (let ((cell (table--probe-cell)))
		(and cell (null (table--at-cell-p (car cell)))))
      :help "Recognize a cell at point"])
    ("Unrecognize"
     ["in Buffer" table-unrecognize
      :active t
      :help "Unrecognize all tables in the current buffer"]
     ["in Region" table-unrecognize-region
      :active (and mark-active (not (eq (mark t) (point))))
      :help "Unrecognize all tables in the current region"]
     ["a Table" table-unrecognize-table
      :active (table--probe-cell)
      :help "Unrecognize the current table"]
     ["a Cell" table-unrecognize-cell
      :active (let ((cell (table--probe-cell)))
		(and cell (table--at-cell-p (car cell))))
      :help "Unrecognize the current cell"])
    "----"
    ["Capture Region" table-capture
     :active (and (not buffer-read-only) mark-active (not (eq (mark t) (point))) (not (table--probe-cell)))
     :help "Capture text in the current region as a table"]
    ["Release" table-release
     :active (table--editable-cell-p)
     :help "Release the current table as plain text"]))

(defconst table-cell-menu
  '("Table"
    ("Insert"
     ["Row" table-insert-row
1074
      :active (table--row-column-insertion-point-p)
Richard M. Stallman's avatar
Richard M. Stallman committed
1075 1076
      :help "Insert row(s) of cells in table"]
     ["Column" table-insert-column
1077
      :active (table--row-column-insertion-point-p 'column)
Richard M. Stallman's avatar
Richard M. Stallman committed
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
      :help "Insert column(s) of cells in table"])
    ("Delete"
     ["Row" table-delete-row
      :active (table--editable-cell-p)
      :help "Delete row(s) of cells in table"]
     ["Column" table-delete-column
      :active (table--editable-cell-p)
      :help "Delete column(s) of cells in table"])
    "----"
    ("Split a Cell"
     ["Horizontally" table-split-cell-horizontally
      :active (table--cell-can-split-horizontally-p)
      :help "Split the current cell horizontally at point"]
     ["Vertically"  table-split-cell-vertically
      :active (table--cell-can-split-vertically-p)
      :help "Split the current cell vertical at point"])
    ("Span a Cell to"
     ["Right" (table-span-cell 'right)
      :active (table--cell-can-span-p 'right)
      :help "Span the current cell into the right cell"]
     ["Left" (table-span-cell 'left)
      :active (table--cell-can-span-p 'left)
      :help "Span the current cell into the left cell"]
     ["Above" (table-span-cell 'above)
      :active (table--cell-can-span-p 'above)
      :help "Span the current cell into the cell above"]
     ["Below" (table-span-cell 'below)
      :active (table--cell-can-span-p 'below)
      :help "Span the current cell into the cell below"])
    "----"
    ("Shrink Cells"
     ["Horizontally" table-narrow-cell
      :active (table--editable-cell-p)
      :help "Shrink the current cell horizontally"]
     ["Vertically" table-shorten-cell
      :active (table--editable-cell-p)
      :help "Shrink the current cell vertically"])
    ("Expand Cells"
     ["Horizontally" table-widen-cell
      :active (table--editable-cell-p)
      :help "Expand the current cell horizontally"]
     ["Vertically" table-heighten-cell
      :active (table--editable-cell-p)
      :help "Expand the current cell vertically"])
    "----"
    ("Justify"
     ("a Cell"
      ["Left" (table-justify-cell 'left)
       :active (table--editable-cell-p)
       :help "Left justify the contents of the current cell"]
      ["Center" (table-justify-cell 'center)
       :active (table--editable-cell-p)
       :help "Center justify the contents of the current cell"]
      ["Right" (table-justify-cell 'right)
       :active (table--editable-cell-p)
       :help "Right justify the contents of the current cell"]
      "----"
      ["Top" (table-justify-cell 'top)
       :active (table--editable-cell-p)
       :help "Top align the contents of the current cell"]
      ["Middle" (table-justify-cell 'middle)
       :active (table--editable-cell-p)
       :help "Middle align the contents of the current cell"]
      ["Bottom" (table-justify-cell 'bottom)
       :active (table--editable-cell-p)
       :help "Bottom align the contents of the current cell"]
      ["None" (table-justify-cell 'none)
       :active (table--editable-cell-p)
       :help "Remove vertical alignment from the current cell"])
     ("a Row"
      ["Left" (table-justify-row 'left)
       :active (table--editable-cell-p)
       :help "Left justify the contents of all cells in the current row"]
      ["Center" (table-justify-row 'center)
       :active (table--editable-cell-p)
       :help "Center justify the contents of all cells in the current row"]
      ["Right" (table-justify-row 'right)
       :active (table--editable-cell-p)
       :help "Right justify the contents of all cells in the current row"]
      "----"
      ["Top" (table-justify-row 'top)
       :active (table--editable-cell-p)
       :help "Top align the contents of all cells in the current row"]
      ["Middle" (table-justify-row 'middle)
       :active (table--editable-cell-p)
       :help "Middle align the contents of all cells in the current row"]
      ["Bottom" (table-justify-row 'bottom)
       :active (table--editable-cell-p)
       :help "Bottom align the contents of all cells in the current row"]
      ["None" (table-justify-cell 'none)
       :active (table--editable-cell-p)
       :help "Remove vertical alignment from all cells in the current row"])
     ("a Column"
      ["Left" (table-justify-column 'left)
       :active (table--editable-cell-p)
       :help "Left justify the contents of all cells in the current column"]
      ["Center" (table-justify-column 'center)
       :active (table--editable-cell-p)
       :help "Center justify the contents of all cells in the current column"]
      ["Right" (table-justify-column 'right)
       :active (table--editable-cell-p)
       :help "Right justify the contents of all cells in the current column"]
      "----"
      ["Top" (table-justify-column 'top)
       :active (table--editable-cell-p)
       :help "Top align the contents of all cells in the current column"]
      ["Middle" (table-justify-column 'middle)
       :active (table--editable-cell-p)
       :help "Middle align the contents of all cells in the current column"]
      ["Bottom" (table-justify-column 'bottom)
       :active (table--editable-cell-p)
       :help "Bottom align the contents of all cells in the current column"]
      ["None" (table-justify-cell 'none)
       :active (table--editable-cell-p)
       :help "Remove vertical alignment from all cells in the current column"])
     ("a Paragraph"
      ["Left" (table-justify-cell 'left t)
       :active (table--editable-cell-p)
       :help "Left justify the current paragraph"]
      ["Center" (table-justify-cell 'center t)
       :active (table--editable-cell-p)
       :help "Center justify the current paragraph"]
      ["Right" (table-justify-cell 'right t)
       :active (table--editable-cell-p)
       :help "Right justify the current paragraph"]))
    "----"
    ["Query Dimension" table-query-dimension
     :active (table--probe-cell)
     :help "Get the dimension of the current cell and the current table"]
    ["Generate Source" table-generate-source
     :active (table--probe-cell)
     :help "Generate source of the current table in the specified language"]
    ["Insert Sequence" table-insert-sequence
     :active (table--editable-cell-p)
     :help "Travel cells forward while inserting a specified sequence string in each cell"]
    ("Unrecognize"
     ["a Table" table-unrecognize-table
      :active (table--probe-cell)
      :help "Unrecognize the current table"]
     ["a Cell" table-unrecognize-cell
      :active (let ((cell (table--probe-cell)))
		(and cell (table--at-cell-p (car cell))))
      :help "Unrecognize the current cell"])
    ["Release" table-release
     :active (table--editable-cell-p)
     :help "Release the current table as plain text"]
    ("Configure Width to"
     ["Auto Expand Mode" (table-fixed-width-mode -1)
      :active t
      :style radio
      :selected (not table-fixed-width-mode)
      :help "A mode that allows automatic horizontal cell expansion"]
     ["Fixed Width Mode" (table-fixed-width-mode 1)
      :active t
      :style radio
      :selected table-fixed-width-mode
      :help "A mode that does not allow automatic horizontal cell expansion"])
    ("Navigate"
     ["Forward Cell" table-forward-cell
      :active (table--probe-cell)
      :help "Move point forward by cell(s)"]
     ["Backward Cell" table-backward-cell
      :active (table--probe-cell)
      :help "Move point backward by cell(s)"])
    ))

;; XEmacs causes an error when encountering unknown keywords in the
;; menu definition.  Specifically the :help keyword is new in Emacs 21
;; and causes error for the XEmacs function `check-menu-syntax'.  IMHO
;; it is unwise to generate an error for unknown keywords because it
;; kills the nice backward compatible extensibility of keyword use.
;; Unknown keywords should be quietly ignore so that future extension
;; does not cause a problem in the old implementation.  Sigh...
(when (featurep 'xemacs)
  (mapcar
   (defun table--tweak-menu-for-xemacs (menu)
     (cond
      ((listp menu)
       (mapcar 'table--tweak-menu-for-xemacs menu))
      ((vectorp menu)
       (let ((i 0) (len (length menu)))
	 (while (< i len)
	   ;; replace :help with something harmless.
	   (if (eq (aref menu i) :help) (aset menu i :included))
	   (setq i (1+ i)))))))
   (list table-global-menu table-cell-menu))
  (defvar mark-active t))

;; register table menu under global tools menu
(unless table-disable-menu
  (easy-menu-define table-global-menu-map nil "Table global menu" table-global-menu)
  (if (featurep 'xemacs)
      (progn
	(easy-menu-add-item nil '("Tools") table-global-menu-map))
    (easy-menu-add-item (current-global-map) '("menu-bar" "tools") '("--"))
    (easy-menu-add-item (current-global-map) '("menu-bar" "tools") table-global-menu-map)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Macros
;;

(defmacro table-with-cache-buffer (&rest body)
  "Execute the forms in BODY with table cache buffer as the current buffer.
This macro simplifies the rest of the work greatly by condensing the
common idiom used in many of the cell manipulation functions.  It does
not return any meaningful value.

Save the current buffer and set the cache buffer as the current
buffer.  Move the point to the cache buffer coordinate
`table-cell-cache-point-coordinate'.  After BODY forms are executed,
the paragraph is filled as long as `table-inhibit-auto-fill-paragraph'
remains nil.  BODY can set it to t when it does not want to fill the
paragraph.  If necessary the cell width and height are extended as the
consequence of cell content modification by the BODY.  Then the
current buffer is restored to the original one.  The last cache point
coordinate is stored in `table-cell-cache-point-coordinate'.  The
original buffer's point is moved to the location that corresponds to
the last cache point coordinate."
  (let ((height-expansion (make-symbol "height-expansion-var-symbol"))
	(width-expansion (make-symbol "width-expansion-var-symbol")))
    `(let (,height-expansion ,width-expansion)
       ;; make sure cache has valid data unless it is explicitly inhibited.
       (unless table-inhibit-update
	 (table-recognize-cell))
       (with-current-buffer (get-buffer-create table-cache-buffer-name)
	 ;; goto the cell coordinate based on `table-cell-cache-point-coordinate'.
	 (set-mark (table--goto-coordinate table-cell-cache-mark-coordinate))
	 (table--goto-coordinate table-cell-cache-point-coordinate)
	 (table--untabify-line)
	 ;; always reset before executing body forms because auto-fill behavior is the default.
	 (setq table-inhibit-auto-fill-paragraph nil)
	 ;; do the body
	 ,@body
	 ;; fill paragraph unless the body does not want to by setting `table-inhibit-auto-fill-paragraph'.
	 (unless table-inhibit-auto-fill-paragraph
	   (if (and table-cell-info-justify
		    (not (eq table-cell-info-justify 'left)))
	       (table--fill-region (point-min) (point-max))
	     (table--fill-region
	      (save-excursion (forward-paragraph -1) (point))
	      (save-excursion (forward-paragraph 1) (point)))))
	 ;; keep the updated cell coordinate.
	 (setq table-cell-cache-point-coordinate (table--get-coordinate))
	 ;; determine the cell width expansion.
	 (setq ,width-expansion (table--measure-max-width))
	 (if (<= ,width-expansion table-cell-info-width) nil
	   (table--fill-region (point-min) (point-max) ,width-expansion)
	   ;; keep the updated cell coordinate.
	   (setq table-cell-cache-point-coordinate (table--get-coordinate)))
	 (setq ,width-expansion (- ,width-expansion table-cell-info-width))
	 ;; determine the cell height expansion.
	 (if (looking-at "\\s *\\'") nil
	   (goto-char (point-min))
	   (if (re-search-forward "\\(\\s *\\)\\'" nil t)
	       (goto-char (match-beginning 1))))
	 (setq ,height-expansion (- (cdr (table--get-coordinate)) (1- table-cell-info-height))))
       ;; now back to the table buffer.
       ;; expand the cell width in the table buffer if necessary.
       (if (> ,width-expansion 0)
	   (table-widen-cell ,width-expansion 'no-copy 'no-update))
       ;; expand the cell height in the table buffer if necessary.
       (if (> ,height-expansion 0)
	   (table-heighten-cell ,height-expansion 'no-copy 'no-update))
       ;; do valign
       (with-current-buffer (get-buffer-create table-cache-buffer-name)
	 (table--goto-coordinate table-cell-cache-point-coordinate)
	 (setq table-cell-cache-point-coordinate (table--valign)))
       ;; move the point in the table buffer to the location that corresponds to
       ;; the location in the cell cache buffer
       (table--goto-coordinate (table--transcoord-cache-to-table table-cell-cache-point-coordinate))
       ;; set up the update timer unless it is explicitly inhibited.
       (unless table-inhibit-update
	 (table--update-cell)))))

;; for debugging the body form of the macro
(put 'table-with-cache-buffer 'edebug-form-spec '(body))
;; for neat presentation use the same indentation as `progn'
(put 'table-with-cache-buffer 'lisp-indent-function 0)
(if (or (featurep 'xemacs)
	(null (fboundp 'font-lock-add-keywords))) nil
  ;; color it as a keyword
  (font-lock-add-keywords
   'emacs-lisp-mode
   '("\\<table-with-cache-buffer\\>")))

(defmacro table-put-source-info (prop value)
  "Register source generation information."
  `(put 'table-source-info-plist ,prop ,value))

(defmacro table-get-source-info (prop)
  "Retrieve source generation information."
  `(get 'table-source-info-plist ,prop))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Modified commands for cell operation
;;

;; Point Motion Only Group
(mapcar
 (lambda (command)
   (let ((func-symbol (intern (format "*table--cell-%s" command)))
	 (doc-string (format "Table remapped function for `%s'." command)))
     (fset func-symbol
	   `(lambda
	      (&rest args)
	      ,doc-string
	      (interactive)
	      (let ((table-inhibit-update t)
		    (deactivate-mark nil))
		(table--finish-delayed-tasks)
		(table-recognize-cell 'force)
		(table-with-cache-buffer
		  (call-interactively ',command)
		  (setq table-inhibit-auto-fill-paragraph t)))))
     (setq table-command-remap-alist
	   (cons (cons command func-symbol)
		 table-command-remap-alist))))
 '(beginning-of-line
   end-of-line
   beginning-of-buffer
   end-of-buffer
   forward-word
   backward-word
1403 1404
   forward-sentence
   backward-sentence
Richard M. Stallman's avatar
Richard M. Stallman committed
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
   forward-paragraph
   backward-paragraph))

;; Extraction Group
(mapcar
 (lambda (command)
   (let ((func-symbol (intern (format "*table--cell-%s" command)))
	 (doc-string (format "Table remapped function for `%s'." command)))
     (fset func-symbol
	   `(lambda
	      (&rest args)
	      ,doc-string
	      (interactive)
	      (table--finish-delayed-tasks)
	      (table-recognize-cell 'force)
	      (table-with-cache-buffer
		(table--remove-cell-properties (point-min) (point-max))
		(table--remove-eol-spaces (point-min) (point-max))
		(call-interactively ',command))
	      (table--finish-delayed-tasks)))
     (setq table-command-remap-alist
	   (cons (cons command func-symbol)
		 table-command-remap-alist))))
 '(kill-region
1429
   kill-ring-save
Richard M. Stallman's avatar
Richard M. Stallman committed
1430 1431
   delete-region
   copy-region-as-kill
1432 1433 1434 1435 1436 1437 1438 1439 1440
   kill-line
   kill-word
   backward-kill-word
   kill-sentence
   backward-kill-sentence
   kill-paragraph
   backward-kill-paragraph
   kill-sexp
   backward-kill-sexp))
Richard M. Stallman's avatar
Richard M. Stallman committed
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549

;; Pasting Group
(mapcar
 (lambda (command)
   (let ((func-symbol (intern (format "*table--cell-%s" command)))
	 (doc-string (format "Table remapped function for `%s'." command)))
     (fset func-symbol
	   `(lambda
	      (&rest args)
	      ,doc-string
	      (interactive)
	      (table--finish-delayed-tasks)
	      (table-recognize-cell 'force)
	      (table-with-cache-buffer
		(call-interactively ',command)
		(table--untabify (point-min) (point-max))
		(table--fill-region (point-min) (point-max))
		(setq table-inhibit-auto-fill-paragraph t))
	      (table--finish-delayed-tasks)))
     (setq table-command-remap-alist
	   (cons (cons command func-symbol)
		 table-command-remap-alist))))
 '(yank
   clipboard-yank
   yank-clipboard-selection
   insert))

;; Formatting Group
(mapcar
 (lambda (command)
   (let ((func-symbol (intern (format "*table--cell-%s" command)))
	 (doc-string (format "Table remapped function for `%s'." command)))
     (fset func-symbol
	   `(lambda
	      (&rest args)
	      ,doc-string
	      (interactive)
	      (table--finish-delayed-tasks)
	      (table-recognize-cell 'force)
	      (table-with-cache-buffer
		(let ((fill-column table-cell-info-width))
		  (call-interactively ',command))
		(setq table-inhibit-auto-fill-paragraph t))
	      (table--finish-delayed-tasks)))
     (setq table-command-remap-alist
	   (cons (cons command func-symbol)
		 table-command-remap-alist))))
 '(center-line
   conter-region
   center-paragraph
   fill-paragraph))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Commands
;;

;;;###autoload
(defun table-insert (columns rows &optional cell-width cell-height)
  "Insert an editable text table.
Insert a table of specified number of COLUMNS and ROWS.  Optional
parameter CELL-WIDTH and CELL-HEIGHT can specify the size of each
cell.  The cell size is uniform across the table if the specified size
is a number.  They can be a list of numbers to specify different size
for each cell.  When called interactively, the list of number is
entered by simply listing all the numbers with space characters
delimiting them.

Examples:

\\[table-insert] inserts a table at the current point location.

Suppose we have the following situation where `-!-' indicates the
location of point.

    -!-

Type \\[table-insert] and hit ENTER key.  As it asks table
specification, provide 3 for number of columns, 1 for number of rows,
5 for cell width and 1 for cell height.  Now you shall see the next
table and the point is automatically moved to the beginning of the
first cell.

    +-----+-----+-----+
    |-!-  |     |     |
    +-----+-----+-----+

Inside a table cell, there are special key bindings. \\<table-cell-map>

M-9 \\[table-widen-cell] (or \\[universal-argument] 9 \\[table-widen-cell]) widens the first cell by 9 character
width, which results as

    +--------------+-----+-----+
    |-!-           |     |     |
    +--------------+-----+-----+

Type TAB \\[table-widen-cell] then type TAB M-2 M-7 \\[table-widen-cell] (or \\[universal-argument] 2 7 \\[table-widen-cell]).  Typing
TAB moves the point forward by a cell. The result now looks like this:

    +--------------+------+--------------------------------+
    |              |      |-!-                             |
    +--------------+------+--------------------------------+

If you knew each width of the columns prior to the table creation,
what you could have done better was to have had given the complete
width information to `table-insert'.

Cell width(s): 14 6 32

1550
instead of
Richard M. Stallman's avatar
Richard M. Stallman committed
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664

Cell width(s): 5

This would have eliminated the previously mentioned width adjustment
work all together.

If the point is in the last cell type S-TAB S-TAB to move it to the
first cell.  Now type \\[table-heighten-cell] which heighten the row by a line.

    +--------------+------+--------------------------------+
    |-!-           |      |                                |
    |              |      |                                |
    +--------------+------+--------------------------------+

Type \\[table-insert-row-column] and tell it to insert a row.

    +--------------+------+--------------------------------+
    |-!-           |      |                                |
    |              |      |                                |
    +--------------+------+--------------------------------+
    |              |      |                                |
    |              |      |                                |
    +--------------+------+--------------------------------+

Move the point under the table as shown below.

    +--------------+------+--------------------------------+
    |              |      |                                |
    |              |      |                                |
    +--------------+------+--------------------------------+
    |              |      |                                |
    |              |      |                                |
    +--------------+------+--------------------------------+
    -!-

Type M-x table-insert-row instead of \\[table-insert-row-column].  \\[table-insert-row-column] does not work
when the point is outside of the table.  This insertion at
outside of the table effectively appends a row at the end.

    +--------------+------+--------------------------------+
    |              |      |                                |
    |              |      |                                |
    +--------------+------+--------------------------------+
    |              |      |                                |
    |              |      |                                |
    +--------------+------+--------------------------------+
    |-!-           |      |                                |
    |              |      |                                |
    +--------------+------+--------------------------------+

Text editing inside the table cell produces reasonably expected
results.

    +--------------+------+--------------------------------+
    |              |      |                                |
    |              |      |                                |
    +--------------+------+--------------------------------+
    |              |      |Text editing inside the table   |
    |              |      |cell produces reasonably        |
    |              |      |expected results.-!-            |
    +--------------+------+--------------------------------+
    |              |      |                                |
    |              |      |                                |
    +--------------+------+--------------------------------+

Inside a table cell has a special keymap.

\\{table-cell-map}
"
  (interactive
   (progn
     (barf-if-buffer-read-only)
     (if (table--probe-cell)
	 (error "Can't insert a table inside a table"))
     (mapcar (function table--read-from-minibuffer)
	     '(("Number of columns" . table-columns-history)
	       ("Number of rows" . table-rows-history)
	       ("Cell width(s)" . table-cell-width-history)
	       ("Cell height(s)" . table-cell-height-history)))))
  (table--make-cell-map)
  ;; reform the arguments.
  (if (null cell-width) (setq cell-width (car table-cell-width-history)))
  (if (null cell-height) (setq cell-height (car table-cell-height-history)))
  (if (stringp columns) (setq columns (string-to-number columns)))
  (if (stringp rows) (setq rows (string-to-number rows)))
  (if (stringp cell-width) (setq cell-width (table--string-to-number-list cell-width)))
  (if (stringp cell-height) (setq cell-height (table--string-to-number-list cell-height)))
  (if (numberp cell-width) (setq cell-width (cons cell-width nil)))
  (if (numberp cell-height) (setq cell-height (cons cell-height nil)))
  ;; test validity of the arguments.
  (mapcar (lambda (arg)
	    (let* ((value (symbol-value arg))
		   (error-handler
		    (function (lambda ()
				(error "%s must be a positive integer%s" arg
				       (if (listp value) " or a list of positive integers" ""))))))
	      (if (null value) (funcall error-handler))
	      (mapcar (function (lambda (arg1)
				  (if (or (not (integerp arg1))
					  (< arg1 1))
				      (funcall error-handler))))
		      (if (listp value) value
			(cons value nil)))))
	  '(columns rows cell-width cell-height))
  (let ((orig-coord (table--get-coordinate))
	(coord (table--get-coordinate))
	r i cw ch cell-str border-str)
    ;; prefabricate the building blocks border-str and cell-str.
    (with-temp-buffer
      ;; construct border-str
      (insert table-cell-intersection-char)
      (setq cw cell-width)
      (setq i 0)
      (while (< i columns)
1665
	(insert (make-string (car cw) (string-to-char table-cell-horizontal-chars)) table-cell-intersection-char)
Richard M. Stallman's avatar
Richard M. Stallman committed
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
	(if (cdr cw) (setq cw (cdr cw)))
	(setq i (1+ i)))
      (setq border-str (buffer-substring (point-min) (point-max)))
      ;; construct cell-str
      (erase-buffer)
      (insert table-cell-vertical-char)
      (setq cw cell-width)
      (setq i 0)
      (while (< i columns)
	(let ((beg (point)))
	  (insert (make-string (car cw) ?\ ))
	  (insert table-cell-vertical-char)
	  (table--put-cell-line-property beg (1- (point))))
	(if (cdr cw) (setq cw (cdr cw)))
	(setq i (1+ i)))
      (setq cell-str (buffer-substring (point-min) (point-max))))
    ;; if the construction site has an empty border push that border down.
    (save-excursion
      (beginning-of-line)
      (if (looking-at "\\s *$")
	  (progn
	    (setq border-str (concat border-str "\n"))
	    (setq cell-str (concat cell-str "\n")))))
    ;; now build the table using the prefabricated building blocks
    (setq r 0)
    (setq ch cell-height)
    (while (< r rows)
      (if (> r 0) nil
	(table--goto-coordinate coord) (setcdr coord (1+ (cdr coord)))
	(table--untabify-line (point))
	(insert border-str))
      (setq i 0)
      (while (< i (car ch))
	(table--goto-coordinate coord) (setcdr coord (1+ (cdr coord)))
	(table--untabify-line (point))
	(insert cell-str)
	(setq i (1+ i)))
      (table--goto-coordinate coord) (setcdr coord (1+ (cdr coord)))
      (table--untabify-line (point))
      (insert border-str)
      (if (cdr ch) (setq ch (cdr ch)))
      (setq r (1+ r)))
    ;; stand by at the first cell
    (table--goto-coordinate (table--offset-coordinate orig-coord '(1 . 1)))
    (table-recognize-cell 'force)))

;;;###autoload
(defun table-insert-row (n)
  "Insert N table row(s).
When point is in a table the newly inserted row(s) are placed above
the current row.  When point is outside of the table it must be below
the table within the table width range, then the newly created row(s)
are appended at the bottom of the table."
  (interactive "*p")
  (if (< n 0) (setq n 1))
  (let* ((current-coordinate (table--get-coordinate))
	 (coord-list (table--cell-list-to-coord-list (table--horizontal-cell-list t nil 'top)))
	 (append-row (if coord-list nil (setq coord-list (table--find-row-column))))
	 (cell-height (cdr (table--min-coord-list coord-list)))
	 (left-list nil)
	 (this-list coord-list)
	 (right-list (cdr coord-list))
	 (bottom-border-y (1+ (cdr (table--get-coordinate (cdr (table--vertical-cell-list nil t))))))
	 (vertical-str (string table-cell-vertical-char))
	 (vertical-str-with-properties (let ((str (string table-cell-vertical-char)))
					 (table--put-cell-keymap-property 0 (length str) str)
					 (table--put-cell-rear-nonsticky 0 (length str) str) str))
	 (first-time t))
    ;; create the space below for the table to grow
    (table--create-growing-space-below (* n (+ 1 cell-height)) coord-list bottom-border-y)
    ;; vertically expand each cell from left to right
    (while this-list
      (let* ((left (prog1 (car left-list) (setq left-list (if left-list (cdr left-list) coord-list))))
	     (this (prog1 (car this-list) (setq this-list (cdr this-list))))
	     (right (prog1 (car right-list) (setq right-list (cdr right-list))))
	     (exclude-left (and left (< (cdar left) (cdar this))))
	     (exclude-right (and right (<= (cdar right) (cdar this))))
	     (beg (table--goto-coordinate
		   (cons (if exclude-left (caar this) (1- (caar this)))
			 (cdar this))))
	     (end (table--goto-coordinate
		   (cons (if exclude-right (cadr this) (1+ (cadr this)))
			 bottom-border-y)))
	     (rect (if append-row nil (extract-rectangle beg end))))
	;; prepend blank cell lines to the extracted rectangle
	(let ((i n))
	  (while (> i 0)
	    (setq rect (cons
			(concat (if exclude-left "" (char-to-string table-cell-intersection-char))
1755
				(make-string (- (cadr this) (caar this)) (string-to-char table-cell-horizontal-chars))
Richard M. Stallman's avatar
Richard M. Stallman committed
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
				(if exclude-right "" (char-to-string table-cell-intersection-char)))
			rect))
	    (let ((j cell-height))
	      (while (> j 0)
		(setq rect (cons
			    (concat (if exclude-left ""
				      (if first-time vertical-str vertical-str-with-properties))
				    (table--cell-blank-str (- (cadr this) (caar this)))
				    (if exclude-right "" vertical-str-with-properties))
			    rect))
		(setq j (1- j))))
	    (setq i (1- i))))
	(setq first-time nil)
	(if append-row
	    (table--goto-coordinate (cons (if exclude-left (caar this) (1- (caar this)))
					  (1+ bottom-border-y)))
	  (delete-rectangle beg end)
	  (goto-char beg))
	(table--insert-rectangle rect)))
    ;; fix up the intersections
    (setq this-list (if append-row nil coord-list))
    (while this-list
      (let ((this (prog1 (car this-list) (setq this-list (cdr this-list))))
	    (i 0))
	(while (< i n)
	  (let ((y (1- (* i (+ 1 cell-height)))))
	    (table--goto-coordinate (table--offset-coordinate (car this) (cons -1  y)))
	    (delete-char 1) (insert table-cell-intersection-char)
	    (table--goto-coordinate (table--offset-coordinate (cons (cadr this) (cdar this)) (cons 0  y)))
	    (delete-char 1) (insert table-cell-intersection-char)
	    (setq i (1+ i))))))
    ;; move the point to the beginning of the first newly inserted cell.
    (if (table--goto-coordinate
	 (if append-row (cons (car (caar coord-list)) (1+ bottom-border-y))
	   (caar coord-list))) nil
      (table--goto-coordinate current-coordinate))
    ;; re-recognize the current cell's new dimension
    (table-recognize-cell 'force)))

;;;###autoload
(defun table-insert-column (n)
  "Insert N table column(s).
When point is in a table the newly inserted column(s) are placed left
of the current column.  When point is outside of the table it must be
right side of the table within the table height range, then the newly
created column(s) are appended at the right of the table."
  (interactive "*p")
  (if (< n 0) (setq n 1))
  (let* ((current-coordinate (table--get-coordinate))
	 (coord-list (table--cell-list-to-coord-list (table--vertical-cell-list t nil 'left)))
	 (append-column (if coord-list nil (setq coord-list (table--find-row-column 'column))))
	 (cell-width (car (table--min-coord-list coord-list)))
1808
	 (border-str (table--multiply-string (concat (make-string cell-width (string-to-char table-cell-horizontal-chars))
Richard M. Stallman's avatar
Richard M. Stallman committed
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
						     (char-to-string table-cell-intersection-char)) n))
	 (cell-str (table--multiply-string (concat (table--cell-blank-str cell-width)
						   (let ((str (string table-cell-vertical-char)))
						     (table--put-cell-keymap-property 0 (length str) str)
						     (table--put-cell-rear-nonsticky 0 (length str) str) str)) n))
	 (columns-to-extend (* n (+ 1 cell-width)))
	 (above-list nil)
	 (this-list coord-list)
	 (below-list (cdr coord-list))
	 (right-border-x (car (table--get-coordinate (cdr (table--horizontal-cell-list nil t))))))
    ;; push back the affected area above and below this table
    (table--horizontally-shift-above-and-below columns-to-extend coord-list)
    ;; process each cell vertically from top to bottom
    (while this-list
      (let* ((above (prog1 (car above-list) (setq above-list (if above-list (cdr above-list) coord-list))))
	     (this (prog1 (car this-list) (setq this-list (cdr this-list))))
	     (below (prog1 (car below-list) (setq below-list (cdr below-list))))
	     (exclude-above (and above (<= (caar above) (caar this))))
	     (exclude-below (and below (< (caar below) (caar this))))
	     (beg-coord (cons (if append-column (1+ right-border-x) (caar this))
			      (if exclude-above (cdar this) (1- (cdar this)))))
	     (end-coord (cons (1+ right-border-x)
			      (if exclude-below (cddr this) (1+ (cddr this)))))
	     rect)
	;; untabify the area right of the bar that is about to be inserted
	(let ((coord (table--copy-coordinate beg-coord))
	      (i 0)
	      (len (length rect)))
	  (while (< i len)
	    (if (table--goto-coordinate coord 'no-extension)
		(table--untabify-line (point)))
	    (setcdr coord (1+ (cdr coord)))
	    (setq i (1+ i))))
	;; extract and delete the rectangle area including the current
	;; cell and to the right border of the table.
	(setq rect (extract-rectangle (table--goto-coordinate beg-coord)
				      (table--goto-coordinate end-coord)))
	(delete-rectangle (table--goto-coordinate beg-coord)
			  (table--goto-coordinate end-coord))
	;; prepend the empty column string at the beginning of each
	;; rectangle string extracted before.
	(let ((rect-str rect)
	      (first t))
	  (while rect-str
	    (if (and first (null exclude-above))
		(setcar rect-str (concat border-str (car rect-str)))
	      (if (and (null (cdr rect-str)) (null exclude-below))
		  (setcar rect-str (concat border-str (car rect-str)))
		(setcar rect-str (concat cell-str (car rect-str)))))
	    (setq first nil)
	    (setq rect-str (cdr rect-str))))
	;; insert the extended rectangle
	(table--goto-coordinate beg-coord)
	(table--insert-rectangle rect)))
    ;; fix up the intersections
    (setq this-list (if append-column nil coord-list))
    (while this-list
      (let ((this (prog1 (car this-list) (setq this-list (cdr this-list))))
	    (i 0))
	(while (< i n)
	  (let ((x (1- (* (1+ i) (+ 1 cell-width)))))
	    (table--goto-coordinate (table--offset-coordinate (car this) (cons x  -1)))
	    (delete-char 1) (insert table-cell-intersection-char)
	    (table--goto-coordinate (table--offset-coordinate (cons (caar this) (cddr this)) (cons x  1)))
	    (delete-char 1) (insert table-cell-intersection-char)
	    (setq i (1+ i))))))
    ;; move the point to the beginning of the first newly inserted cell.
    (if (table--goto-coordinate
	 (if append-column
	     (cons (1+ right-border-x)
		   (cdar (car coord-list)))
	   (caar coord-list))) nil
      (table--goto-coordinate current-coordinate))
    ;; re-recognize the current cell's new dimension
    (table-recognize-cell 'force)))

;;;###autoload
(defun table-insert-row-column (row-column n)
  "Insert row(s) or column(s).
See `table-insert-row' and `table-insert-column'."
  (interactive
   (let ((n (prefix-numeric-value current-prefix-arg)))
     (if (< n 0) (setq n 1))
     (list (intern (let ((completion-ignore-case t)
			 (default (car table-insert-row-column-history)))
		     (downcase (completing-read
				(format "Insert %s row%s/column%s (default %s): "
					(if (> n 1) (format "%d" n) "a")
					(if (> n 1) "s" "")
					(if (> n 1) "s" "")
					default)
				'(("row") ("column"))
				nil t nil 'table-insert-row-column-history default))))
	   n)))
  (cond ((eq row-column 'row)
	 (table-insert-row n))
	((eq row-column 'column)
	 (table-insert-column n))))

;;;###autoload
(defun table-recognize (&optional arg)
  "Recognize all tables within the current buffer and activate them.
Scans the entire buffer and recognizes valid table cells.  If the
optional numeric prefix argument ARG is negative the tables in the
buffer become inactive, meaning the tables become plain text and loses
all the table specific features."
  (interactive "P")
  (setq arg (prefix-numeric-value arg))
  (let* ((inhibit-read-only t))
    (table-recognize-region (point-min) (point-max) -1)
    (if (>= arg 0)
	(save-excursion
	  (goto-char (point-min))
1922 1923
	  (let* ((border (format "[%s%c%c]"
				 table-cell-horizontal-chars
Richard M. Stallman's avatar
Richard M. Stallman committed
1924 1925 1926
				 table-cell-vertical-char
				 table-cell-intersection-char))
		 (border3 (concat border border border))
1927 1928
		 (non-border (format "^[^%s%c%c]*$"
				     table-cell-horizontal-chars
Richard M. Stallman's avatar
Richard M. Stallman committed
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
				     table-cell-vertical-char
				     table-cell-intersection-char)))
	    ;; `table-recognize-region' is an expensive function so minimize
	    ;; the search area.  A minimum table at least consists of three consecutive
	    ;; table border characters to begin with such as
	    ;; +-+
	    ;; |A|
	    ;; +-+
	    ;; and any tables end with a line containing no table border characters
	    ;; or the end of buffer.
	    (while (and (re-search-forward border3 (point-max) t)
			(not (and (input-pending-p)
				  table-abort-recognition-when-input-pending)))
	      (message "Recognizing tables...(%d%%)" (/ (* 100 (match-beginning 0)) (- (point-max) (point-min))))
	      (let ((beg (match-beginning 0))
		    end)
		(if (re-search-forward non-border (point-max) t)
		    (setq end (match-beginning 0))
		  (setq end (goto-char (point-max))))
		(table-recognize-region beg end arg)))
	    (message "Recognizing tables...done"))))))

;;;###autoload
(defun table-unrecognize ()
  (interactive)
  (table-recognize -1))

;;;###autoload
(defun table-recognize-region (beg end &optional arg)
  "Recognize all tables within region.
BEG and END specify the region to work on.  If the optional numeric
prefix argument ARG is negative the tables in the region become
inactive, meaning the tables become plain text and lose all the table
specific features."
  (interactive "r\nP")
  (setq arg (prefix-numeric-value arg))
  (let ((inhibit-read-only t)
	(modified-flag (buffer-modified-p)))
    (if (< arg 0)
	(table--remove-cell-properties beg end)
      (save-excursion
	(goto-char beg)
1971 1972
	(let* ((border (format "[%s%c%c]"
			       table-cell-horizontal-chars
Richard M. Stallman's avatar
Richard M. Stallman committed
1973 1974
			       table-cell-vertical-char
			       table-cell-intersection-char))
1975 1976
	       (non-border (format "[^%s%c%c]"
				   table-cell-horizontal-chars
Richard M. Stallman's avatar
Richard M. Stallman committed
1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251