]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
Extend the notermination flag to math as well.
[lyx.git] / src / insets / InsetTabular.cpp
1 /**
2  * \file InsetTabular.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Matthias Ettrich
8  * \author José Matos
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Jürgen Vigna
14  * \author Uwe Stöhr
15  * \author Edwin Leuven
16  *
17  * Full author contact details are available in file CREDITS.
18  */
19
20 #include <config.h>
21
22 #include "InsetTabular.h"
23
24 #include "buffer_funcs.h"
25 #include "Buffer.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "CoordCache.h"
29 #include "Counters.h"
30 #include "Cursor.h"
31 #include "CutAndPaste.h"
32 #include "DispatchResult.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "Lexer.h"
38 #include "LyX.h"
39 #include "LyXRC.h"
40 #include "MetricsInfo.h"
41 #include "OutputParams.h"
42 #include "output_xhtml.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "ParIterator.h"
46 #include "TextClass.h"
47 #include "TextMetrics.h"
48
49 #include "frontends/Application.h"
50 #include "frontends/alert.h"
51 #include "frontends/Clipboard.h"
52 #include "frontends/Painter.h"
53 #include "frontends/Selection.h"
54
55 #include "support/convert.h"
56 #include "support/debug.h"
57 #include "support/docstream.h"
58 #include "support/FileName.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/lstrings.h"
62
63 #include <boost/scoped_ptr.hpp>
64
65 #include <sstream>
66 #include <iostream>
67 #include <limits>
68 #include <cstring>
69
70 using namespace std;
71 using namespace lyx::support;
72
73
74
75 namespace lyx {
76
77 using cap::dirtyTabularStack;
78 using cap::tabularStackDirty;
79
80 using graphics::PreviewLoader;
81
82 using frontend::Painter;
83 using frontend::Clipboard;
84
85 namespace Alert = frontend::Alert;
86
87
88 namespace {
89
90 int const ADD_TO_HEIGHT = 2; // in cell
91 int const ADD_TO_TABULAR_WIDTH = 6; // horizontal space before and after the table
92 int const default_line_space = 10; // ?
93 int const WIDTH_OF_LINE = 5; // space between double lines
94
95
96 ///
97 boost::scoped_ptr<Tabular> paste_tabular;
98
99
100 struct TabularFeature {
101         Tabular::Feature action;
102         string feature;
103         bool need_value;
104 };
105
106
107 TabularFeature tabularFeature[] =
108 {
109         // the SET/UNSET actions are used by the table dialog,
110         // the TOGGLE actions by the table toolbar buttons
111         { Tabular::APPEND_ROW, "append-row", false },
112         { Tabular::APPEND_COLUMN, "append-column", false },
113         { Tabular::DELETE_ROW, "delete-row", false },
114         { Tabular::DELETE_COLUMN, "delete-column", false },
115         { Tabular::COPY_ROW, "copy-row", false },
116         { Tabular::COPY_COLUMN, "copy-column", false },
117         { Tabular::SET_LINE_TOP, "set-line-top", true },
118         { Tabular::SET_LINE_BOTTOM, "set-line-bottom", true },
119         { Tabular::SET_LINE_LEFT, "set-line-left", true },
120         { Tabular::SET_LINE_RIGHT, "set-line-right", true },
121         { Tabular::TOGGLE_LINE_TOP, "toggle-line-top", false },
122         { Tabular::TOGGLE_LINE_BOTTOM, "toggle-line-bottom", false },
123         { Tabular::TOGGLE_LINE_LEFT, "toggle-line-left", false },
124         { Tabular::TOGGLE_LINE_RIGHT, "toggle-line-right", false },
125         { Tabular::ALIGN_LEFT, "align-left", false },
126         { Tabular::ALIGN_RIGHT, "align-right", false },
127         { Tabular::ALIGN_CENTER, "align-center", false },
128         { Tabular::ALIGN_BLOCK, "align-block", false },
129         { Tabular::ALIGN_DECIMAL, "align-decimal", false },
130         { Tabular::VALIGN_TOP, "valign-top", false },
131         { Tabular::VALIGN_BOTTOM, "valign-bottom", false },
132         { Tabular::VALIGN_MIDDLE, "valign-middle", false },
133         { Tabular::M_ALIGN_LEFT, "m-align-left", false },
134         { Tabular::M_ALIGN_RIGHT, "m-align-right", false },
135         { Tabular::M_ALIGN_CENTER, "m-align-center", false },
136         { Tabular::M_VALIGN_TOP, "m-valign-top", false },
137         { Tabular::M_VALIGN_BOTTOM, "m-valign-bottom", false },
138         { Tabular::M_VALIGN_MIDDLE, "m-valign-middle", false },
139         { Tabular::MULTICOLUMN, "multicolumn", false },
140         { Tabular::SET_MULTICOLUMN, "set-multicolumn", false },
141         { Tabular::UNSET_MULTICOLUMN, "unset-multicolumn", false },
142         { Tabular::MULTIROW, "multirow", false },
143         { Tabular::SET_MULTIROW, "set-multirow", false },
144         { Tabular::UNSET_MULTIROW, "unset-multirow", false },
145         { Tabular::SET_MROFFSET, "set-mroffset", true },
146         { Tabular::SET_ALL_LINES, "set-all-lines", false },
147         { Tabular::UNSET_ALL_LINES, "unset-all-lines", false },
148         { Tabular::SET_LONGTABULAR, "set-longtabular", false },
149         { Tabular::UNSET_LONGTABULAR, "unset-longtabular", false },
150         { Tabular::SET_PWIDTH, "set-pwidth", true },
151         { Tabular::SET_MPWIDTH, "set-mpwidth", true },
152         { Tabular::SET_ROTATE_TABULAR, "set-rotate-tabular", true },
153         { Tabular::UNSET_ROTATE_TABULAR, "unset-rotate-tabular", true },
154         { Tabular::TOGGLE_ROTATE_TABULAR, "toggle-rotate-tabular", true },
155         { Tabular::SET_ROTATE_CELL, "set-rotate-cell", true },
156         { Tabular::UNSET_ROTATE_CELL, "unset-rotate-cell", true },
157         { Tabular::TOGGLE_ROTATE_CELL, "toggle-rotate-cell", true },
158         { Tabular::SET_USEBOX, "set-usebox", true },
159         { Tabular::SET_LTHEAD, "set-lthead", true },
160         { Tabular::UNSET_LTHEAD, "unset-lthead", true },
161         { Tabular::SET_LTFIRSTHEAD, "set-ltfirsthead", true },
162         { Tabular::UNSET_LTFIRSTHEAD, "unset-ltfirsthead", true },
163         { Tabular::SET_LTFOOT, "set-ltfoot", true },
164         { Tabular::UNSET_LTFOOT, "unset-ltfoot", true },
165         { Tabular::SET_LTLASTFOOT, "set-ltlastfoot", true },
166         { Tabular::UNSET_LTLASTFOOT, "unset-ltlastfoot", true },
167         { Tabular::SET_LTNEWPAGE, "set-ltnewpage", false },
168         { Tabular::TOGGLE_LTCAPTION, "toggle-ltcaption", false },
169         { Tabular::SET_LTCAPTION, "set-ltcaption", false },
170         { Tabular::UNSET_LTCAPTION, "unset-ltcaption", false },
171         { Tabular::SET_SPECIAL_COLUMN, "set-special-column", true },
172         { Tabular::SET_SPECIAL_MULTICOLUMN, "set-special-multicolumn", true },
173         { Tabular::SET_BOOKTABS, "set-booktabs", false },
174         { Tabular::UNSET_BOOKTABS, "unset-booktabs", false },
175         { Tabular::SET_TOP_SPACE, "set-top-space", true },
176         { Tabular::SET_BOTTOM_SPACE, "set-bottom-space", true },
177         { Tabular::SET_INTERLINE_SPACE, "set-interline-space", true },
178         { Tabular::SET_BORDER_LINES, "set-border-lines", false },
179         { Tabular::TABULAR_VALIGN_TOP, "tabular-valign-top", false},
180         { Tabular::TABULAR_VALIGN_MIDDLE, "tabular-valign-middle", false},
181         { Tabular::TABULAR_VALIGN_BOTTOM, "tabular-valign-bottom", false},
182         { Tabular::LONGTABULAR_ALIGN_LEFT, "longtabular-align-left", false },
183         { Tabular::LONGTABULAR_ALIGN_CENTER, "longtabular-align-center", false },
184         { Tabular::LONGTABULAR_ALIGN_RIGHT, "longtabular-align-right", false },
185         { Tabular::SET_DECIMAL_POINT, "set-decimal-point", true },
186         { Tabular::SET_TABULAR_WIDTH, "set-tabular-width", true },
187         { Tabular::LAST_ACTION, "", false }
188 };
189
190
191 string const tostr(LyXAlignment const & num)
192 {
193         switch (num) {
194         case LYX_ALIGN_NONE:
195                 return "none";
196         case LYX_ALIGN_BLOCK:
197                 return "block";
198         case LYX_ALIGN_LEFT:
199                 return "left";
200         case LYX_ALIGN_CENTER:
201                 return "center";
202         case LYX_ALIGN_RIGHT:
203                 return "right";
204         case LYX_ALIGN_LAYOUT:
205                 return "layout";
206         case LYX_ALIGN_SPECIAL:
207                 return "special";
208         case LYX_ALIGN_DECIMAL:
209                 return "decimal";
210         }
211         return string();
212 }
213
214
215 string const tostr(Tabular::HAlignment const & num)
216 {
217         switch (num) {
218         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
219                 return "left";
220         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
221                 return "center";
222         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
223                 return "right";
224         }
225         return string();
226 }
227
228
229 string const tostr(Tabular::VAlignment const & num)
230 {
231         switch (num) {
232         case Tabular::LYX_VALIGN_TOP:
233                 return "top";
234         case Tabular::LYX_VALIGN_MIDDLE:
235                 return "middle";
236         case Tabular::LYX_VALIGN_BOTTOM:
237                 return "bottom";
238         }
239         return string();
240 }
241
242
243 string const tostr(Tabular::BoxType const & num)
244 {
245         switch (num) {
246         case Tabular::BOX_NONE:
247                 return "none";
248         case Tabular::BOX_PARBOX:
249                 return "parbox";
250         case Tabular::BOX_MINIPAGE:
251                 return "minipage";
252         }
253         return string();
254 }
255
256
257 // I would have liked a fromstr template a lot better. (Lgb)
258 bool string2type(string const str, LyXAlignment & num)
259 {
260         if (str == "none")
261                 num = LYX_ALIGN_NONE;
262         else if (str == "block")
263                 num = LYX_ALIGN_BLOCK;
264         else if (str == "left")
265                 num = LYX_ALIGN_LEFT;
266         else if (str == "center")
267                 num = LYX_ALIGN_CENTER;
268         else if (str == "right")
269                 num = LYX_ALIGN_RIGHT;
270         else if (str == "decimal")
271                 num = LYX_ALIGN_DECIMAL;
272         else
273                 return false;
274         return true;
275 }
276
277
278 bool string2type(string const str, Tabular::HAlignment & num)
279 {
280         if (str == "left")
281                 num = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
282         else if (str == "center" )
283                 num = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
284         else if (str == "right")
285                 num = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
286         else
287                 return false;
288         return true;
289 }
290
291
292 bool string2type(string const str, Tabular::VAlignment & num)
293 {
294         if (str == "top")
295                 num = Tabular::LYX_VALIGN_TOP;
296         else if (str == "middle" )
297                 num = Tabular::LYX_VALIGN_MIDDLE;
298         else if (str == "bottom")
299                 num = Tabular::LYX_VALIGN_BOTTOM;
300         else
301                 return false;
302         return true;
303 }
304
305
306 bool string2type(string const str, Tabular::BoxType & num)
307 {
308         if (str == "none")
309                 num = Tabular::BOX_NONE;
310         else if (str == "parbox")
311                 num = Tabular::BOX_PARBOX;
312         else if (str == "minipage")
313                 num = Tabular::BOX_MINIPAGE;
314         else
315                 return false;
316         return true;
317 }
318
319
320 bool string2type(string const str, bool & num)
321 {
322         if (str == "true")
323                 num = true;
324         else if (str == "false")
325                 num = false;
326         else
327                 return false;
328         return true;
329 }
330
331
332 bool getTokenValue(string const & str, char const * token, string & ret)
333 {
334         ret.erase();
335         size_t token_length = strlen(token);
336         size_t pos = str.find(token);
337
338         if (pos == string::npos || pos + token_length + 1 >= str.length()
339                 || str[pos + token_length] != '=')
340                 return false;
341         pos += token_length + 1;
342         char ch = str[pos];
343         if (ch != '"' && ch != '\'') { // only read till next space
344                 ret += ch;
345                 ch = ' ';
346         }
347         while (pos < str.length() - 1 && str[++pos] != ch)
348                 ret += str[pos];
349
350         return true;
351 }
352
353
354 bool getTokenValue(string const & str, char const * token, docstring & ret)
355 {
356         string tmp;
357         bool const success = getTokenValue(str, token, tmp);
358         ret = from_utf8(tmp);
359         return success;
360 }
361
362
363 bool getTokenValue(string const & str, char const * token, int & num)
364 {
365         string tmp;
366         num = 0;
367         if (!getTokenValue(str, token, tmp))
368                 return false;
369         num = convert<int>(tmp);
370         return true;
371 }
372
373
374 bool getTokenValue(string const & str, char const * token, LyXAlignment & num)
375 {
376         string tmp;
377         return getTokenValue(str, token, tmp) && string2type(tmp, num);
378 }
379
380
381 bool getTokenValue(string const & str, char const * token,
382                                    Tabular::HAlignment & num)
383 {
384         string tmp;
385         return getTokenValue(str, token, tmp) && string2type(tmp, num);
386 }
387
388
389 bool getTokenValue(string const & str, char const * token,
390                                    Tabular::VAlignment & num)
391 {
392         string tmp;
393         return getTokenValue(str, token, tmp) && string2type(tmp, num);
394 }
395
396
397 bool getTokenValue(string const & str, char const * token,
398                                    Tabular::BoxType & num)
399 {
400         string tmp;
401         return getTokenValue(str, token, tmp) && string2type(tmp, num);
402 }
403
404
405 bool getTokenValue(string const & str, char const * token, bool & flag)
406 {
407         // set the flag always to false as this should be the default for bools
408         // not in the file-format.
409         flag = false;
410         string tmp;
411         return getTokenValue(str, token, tmp) && string2type(tmp, flag);
412 }
413
414
415 bool getTokenValue(string const & str, char const * token, Length & len)
416 {
417         // set the length to be zero() as default as this it should be if not
418         // in the file format.
419         len = Length();
420         string tmp;
421         return getTokenValue(str, token, tmp) && isValidLength(tmp, &len);
422 }
423
424
425 bool getTokenValue(string const & str, char const * token, Length & len, bool & flag)
426 {
427         len = Length();
428         flag = false;
429         string tmp;
430         if (!getTokenValue(str, token, tmp))
431                 return false;
432         if (tmp == "default") {
433                 flag = true;
434                 return  true;
435         }
436         return isValidLength(tmp, &len);
437 }
438
439
440 void l_getline(istream & is, string & str)
441 {
442         str.erase();
443         while (str.empty()) {
444                 getline(is, str);
445                 if (!str.empty() && str[str.length() - 1] == '\r')
446                         str.erase(str.length() - 1);
447         }
448 }
449
450 template <class T>
451 string const write_attribute(string const & name, T const & t)
452 {
453         string const s = tostr(t);
454         return s.empty() ? s : " " + name + "=\"" + s + "\"";
455 }
456
457 template <>
458 string const write_attribute(string const & name, string const & t)
459 {
460         return t.empty() ? t : " " + name + "=\"" + t + "\"";
461 }
462
463
464 template <>
465 string const write_attribute(string const & name, docstring const & t)
466 {
467         return t.empty() ? string() : " " + name + "=\"" + to_utf8(t) + "\"";
468 }
469
470
471 template <>
472 string const write_attribute(string const & name, bool const & b)
473 {
474         // we write only true attribute values so we remove a bit of the
475         // file format bloat for tabulars.
476         return b ? write_attribute(name, convert<string>(b)) : string();
477 }
478
479
480 template <>
481 string const write_attribute(string const & name, int const & i)
482 {
483         // we write only true attribute values so we remove a bit of the
484         // file format bloat for tabulars.
485         return i ? write_attribute(name, convert<string>(i)) : string();
486 }
487
488
489 template <>
490 string const write_attribute(string const & name, Tabular::idx_type const & i)
491 {
492         // we write only true attribute values so we remove a bit of the
493         // file format bloat for tabulars.
494         return i ? write_attribute(name, convert<string>(i)) : string();
495 }
496
497
498 template <>
499 string const write_attribute(string const & name, Length const & value)
500 {
501         // we write only the value if we really have one same reson as above.
502         return value.zero() ? string() : write_attribute(name, value.asString());
503 }
504
505 } // namespace
506
507
508 string const featureAsString(Tabular::Feature action)
509 {
510         for (size_t i = 0; i != Tabular::LAST_ACTION; ++i) {
511                 if (tabularFeature[i].action == action)
512                         return tabularFeature[i].feature;
513         }
514         return string();
515 }
516
517
518 DocIterator separatorPos(InsetTableCell * cell, docstring const & align_d)
519 {
520         DocIterator dit = doc_iterator_begin(&(cell->buffer()), cell);
521         for (; dit; dit.forwardChar())
522                 if (dit.inTexted() && dit.depth() == 1
523                         && dit.paragraph().find(align_d, false, false, dit.pos()))
524                         break;
525
526         return dit;
527 }
528
529
530 InsetTableCell splitCell(InsetTableCell & head, docstring const align_d, bool & hassep)
531 {
532         InsetTableCell tail = InsetTableCell(head);
533         DocIterator const dit = separatorPos(&head, align_d);
534         hassep = dit;
535         if (hassep) {
536                 pit_type const psize = head.paragraphs().front().size();
537                 head.paragraphs().front().eraseChars(dit.pos(), psize, false);
538                 tail.paragraphs().front().eraseChars(0, 
539                         dit.pos() < psize ? dit.pos() + 1 : psize, false);
540         }
541
542         return tail;
543 }
544
545
546 /////////////////////////////////////////////////////////////////////
547 //
548 // Tabular
549 //
550 /////////////////////////////////////////////////////////////////////
551
552
553 Tabular::CellData::CellData(Buffer * buf)
554         : cellno(0),
555           width(0),
556           multicolumn(Tabular::CELL_NORMAL),
557           multirow(Tabular::CELL_NORMAL),
558           alignment(LYX_ALIGN_CENTER),
559           valignment(LYX_VALIGN_TOP),
560           decimal_hoffset(0),
561           decimal_width(0),
562           voffset(0),
563           top_line(false),
564           bottom_line(false),
565           left_line(false),
566           right_line(false),
567           usebox(BOX_NONE),
568           rotate(0),
569           inset(new InsetTableCell(buf))
570 {
571         inset->setBuffer(*buf);
572 }
573
574
575 Tabular::CellData::CellData(CellData const & cs)
576         : cellno(cs.cellno),
577           width(cs.width),
578           multicolumn(cs.multicolumn),
579           multirow(cs.multirow),
580           mroffset(cs.mroffset),
581           alignment(cs.alignment),
582           valignment(cs.valignment),
583           decimal_hoffset(cs.decimal_hoffset),
584           decimal_width(cs.decimal_width),
585           voffset(cs.voffset),
586           top_line(cs.top_line),
587           bottom_line(cs.bottom_line),
588           left_line(cs.left_line),
589           right_line(cs.right_line),
590           usebox(cs.usebox),
591           rotate(cs.rotate),
592           align_special(cs.align_special),
593           p_width(cs.p_width),
594           inset(static_cast<InsetTableCell *>(cs.inset->clone()))
595 {
596 }
597
598 Tabular::CellData & Tabular::CellData::operator=(CellData cs)
599 {
600         swap(cs);
601         return *this;
602 }
603
604 void Tabular::CellData::swap(CellData & rhs)
605 {
606         std::swap(cellno, rhs.cellno);
607         std::swap(width, rhs.width);
608         std::swap(multicolumn, rhs.multicolumn);
609         std::swap(multirow, rhs.multirow);
610         std::swap(mroffset, rhs.mroffset);
611         std::swap(alignment, rhs.alignment);
612         std::swap(valignment, rhs.valignment);
613         std::swap(decimal_hoffset, rhs.decimal_hoffset);
614         std::swap(decimal_width, rhs.decimal_width);
615         std::swap(voffset, rhs.voffset);
616         std::swap(top_line, rhs.top_line);
617         std::swap(bottom_line, rhs.bottom_line);
618         std::swap(left_line, rhs.left_line);
619         std::swap(right_line, rhs.right_line);
620         std::swap(usebox, rhs.usebox);
621         std::swap(rotate, rhs.rotate);
622         std::swap(align_special, rhs.align_special);
623         p_width.swap(rhs.p_width);
624         inset.swap(rhs.inset);
625 }
626
627
628 Tabular::RowData::RowData()
629         : ascent(0),
630           descent(0),
631           top_space_default(false),
632           bottom_space_default(false),
633           interline_space_default(false),
634           endhead(false),
635           endfirsthead(false),
636           endfoot(false),
637           endlastfoot(false),
638           newpage(false),
639           caption(false)
640 {}
641
642
643 Tabular::ColumnData::ColumnData()
644         : alignment(LYX_ALIGN_CENTER),
645           valignment(LYX_VALIGN_TOP),
646           width(0)
647 {
648 }
649
650
651 Tabular::ltType::ltType()
652         : topDL(false),
653           bottomDL(false),
654           empty(false)
655 {}
656
657
658 Tabular::Tabular(Buffer * buffer, row_type rows_arg, col_type columns_arg)
659 {
660         init(buffer, rows_arg, columns_arg);
661 }
662
663
664 void Tabular::setBuffer(Buffer & buffer)
665 {
666         buffer_ = &buffer;
667         for (row_type i = 0; i < nrows(); ++i)
668                 for (col_type j = 0; j < ncols(); ++j)
669                         cell_info[i][j].inset->setBuffer(*buffer_);
670 }
671
672
673 // activates all lines and sets all widths to 0
674 void Tabular::init(Buffer * buf, row_type rows_arg,
675                       col_type columns_arg)
676 {
677         buffer_ = buf;
678         row_info = row_vector(rows_arg);
679         column_info = column_vector(columns_arg);
680         cell_info = cell_vvector(rows_arg, cell_vector(columns_arg, CellData(buf)));
681         row_info.reserve(10);
682         column_info.reserve(10);
683         cell_info.reserve(100);
684         updateIndexes();
685         is_long_tabular = false;
686         tabular_valignment = LYX_VALIGN_MIDDLE;
687         tabular_width = Length();
688         longtabular_alignment = LYX_LONGTABULAR_ALIGN_CENTER;
689         rotate = 0;
690         use_booktabs = false;
691         // set silly default lines
692         for (row_type r = 0; r < nrows(); ++r)
693                 for (col_type c = 0; c < ncols(); ++c) {
694                         cell_info[r][c].inset->setBuffer(*buffer_);
695                         cell_info[r][c].top_line = true;
696                         cell_info[r][c].left_line = true;
697                         cell_info[r][c].bottom_line = r == 0 || r == nrows() - 1;
698                         cell_info[r][c].right_line = c == ncols() - 1;
699                 }
700 }
701
702
703 void Tabular::deleteRow(row_type const row)
704 {
705         // Not allowed to delete last row
706         if (nrows() == 1)
707                 return;
708
709         for (col_type c = 0; c < ncols(); ++c) {
710                 // Care about multirow cells
711                 if (row + 1 < nrows() &&
712                     cell_info[row][c].multirow == CELL_BEGIN_OF_MULTIROW &&
713                     cell_info[row + 1][c].multirow == CELL_PART_OF_MULTIROW) {
714                                 cell_info[row + 1][c].multirow = CELL_BEGIN_OF_MULTIROW;
715                 }
716         }
717         row_info.erase(row_info.begin() + row);
718         cell_info.erase(cell_info.begin() + row);
719         updateIndexes();
720 }
721
722
723 void Tabular::copyRow(row_type const row)
724 {
725         insertRow(row, true);
726 }
727
728
729 void Tabular::appendRow(row_type row)
730 {
731         insertRow(row, false);
732 }
733
734
735 void Tabular::insertRow(row_type const row, bool copy)
736 {
737         row_info.insert(row_info.begin() + row + 1, RowData(row_info[row]));
738         cell_info.insert(cell_info.begin() + row + 1, 
739                 cell_vector(0, CellData(buffer_)));
740         
741         for (col_type c = 0; c < ncols(); ++c) {
742                 cell_info[row + 1].insert(cell_info[row + 1].begin() + c,
743                         copy ? CellData(cell_info[row][c]) : CellData(buffer_));
744                 if (buffer().params().trackChanges)
745                         cell_info[row + 1][c].inset->setChange(Change(Change::INSERTED));
746                 if (cell_info[row][c].multirow == CELL_BEGIN_OF_MULTIROW)
747                         cell_info[row + 1][c].multirow = CELL_PART_OF_MULTIROW;
748         }
749         
750         updateIndexes();
751         for (col_type c = 0; c < ncols(); ++c) {
752                 if (isPartOfMultiRow(row, c))
753                         continue;
754                 // inherit line settings
755                 idx_type const i = cellIndex(row + 1, c);
756                 idx_type const j = cellIndex(row, c);
757                 setLeftLine(i, leftLine(j));
758                 setRightLine(i, rightLine(j));
759                 setTopLine(i, topLine(j));
760                 if (topLine(j) && bottomLine(j)) {
761                         setBottomLine(i, true);
762                         setBottomLine(j, false);
763                 }
764                 // mark track changes
765                 if (buffer().params().trackChanges)
766                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
767         }
768 }
769
770
771 void Tabular::deleteColumn(col_type const col)
772 {
773         // Not allowed to delete last column
774         if (ncols() == 1)
775                 return;
776
777         for (row_type r = 0; r < nrows(); ++r) {
778                 // Care about multicolumn cells
779                 if (col + 1 < ncols() &&
780                     cell_info[r][col].multicolumn == CELL_BEGIN_OF_MULTICOLUMN &&
781                     cell_info[r][col + 1].multicolumn == CELL_PART_OF_MULTICOLUMN) {
782                                 cell_info[r][col + 1].multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
783                 }
784                 cell_info[r].erase(cell_info[r].begin() + col);
785         }
786         column_info.erase(column_info.begin() + col);
787         updateIndexes();
788 }
789
790
791 void Tabular::copyColumn(col_type const col)
792 {
793         insertColumn(col, true);
794 }
795
796
797 void Tabular::appendColumn(col_type col)
798 {       
799         insertColumn(col, false);
800 }
801
802
803 void Tabular::insertColumn(col_type const col, bool copy)
804 {
805         BufferParams const & bp = buffer().params();
806         column_info.insert(column_info.begin() + col + 1, ColumnData(column_info[col]));
807
808         for (row_type r = 0; r < nrows(); ++r) {
809                 cell_info[r].insert(cell_info[r].begin() + col + 1,
810                         copy ? CellData(cell_info[r][col]) : CellData(buffer_));
811                 if (bp.trackChanges)
812                         cell_info[r][col + 1].inset->setChange(Change(Change::INSERTED));
813                 if (cell_info[r][col].multicolumn == CELL_BEGIN_OF_MULTICOLUMN)
814                         cell_info[r][col + 1].multicolumn = CELL_PART_OF_MULTICOLUMN;
815         }
816         updateIndexes();
817         for (row_type r = 0; r < nrows(); ++r) {
818                 // inherit line settings
819                 idx_type const i = cellIndex(r, col + 1);
820                 idx_type const j = cellIndex(r, col);
821                 setBottomLine(i, bottomLine(j));
822                 setTopLine(i, topLine(j));
823                 setLeftLine(i, leftLine(j));
824                 if (rightLine(j) && rightLine(j)) {
825                         setRightLine(i, true);
826                         setRightLine(j, false);
827                 }
828                 if (buffer().params().trackChanges)
829                         cellInfo(i).inset->setChange(Change(Change::INSERTED));
830         }
831 }
832
833
834 void Tabular::updateIndexes()
835 {
836         setBuffer(buffer());
837         numberofcells = 0;
838         // reset cell number
839         for (row_type row = 0; row < nrows(); ++row)
840                 for (col_type column = 0; column < ncols(); ++column) {
841                         if (!isPartOfMultiColumn(row, column)
842                                 && !isPartOfMultiRow(row, column))
843                                 ++numberofcells;
844                         if (isPartOfMultiRow(row, column))
845                                 cell_info[row][column].cellno = cell_info[row - 1][column].cellno;
846                         else
847                                 cell_info[row][column].cellno = numberofcells - 1;
848                 }
849
850         rowofcell.resize(numberofcells);
851         columnofcell.resize(numberofcells);
852         idx_type i = 0;
853         // reset column and row of cells and update their width and alignment
854         for (row_type row = 0; row < nrows(); ++row)
855                 for (col_type column = 0; column < ncols(); ++column) {
856                         if (isPartOfMultiColumn(row, column))
857                                 continue;
858                         // columnofcell needs to be called before setting width and aligment
859                         // multirow cells inherit the width from the column width
860                         if (!isPartOfMultiRow(row, column)) {
861                                 columnofcell[i] = column;
862                                 rowofcell[i] = row;
863                         }
864                         setFixedWidth(row, column);
865                         if (isPartOfMultiRow(row, column))
866                                 continue;
867                         cell_info[row][column].inset->setContentAlignment(
868                                 getAlignment(cellIndex(row, column)));
869                         ++i;
870                 }
871 }
872
873
874 Tabular::idx_type Tabular::numberOfCellsInRow(row_type const row) const
875 {
876         idx_type result = 0;
877         for (col_type c = 0; c < ncols(); ++c)
878                 if (cell_info[row][c].multicolumn != Tabular::CELL_PART_OF_MULTICOLUMN)
879                         ++result;
880         return result;
881 }
882
883
884 bool Tabular::topLine(idx_type const cell) const
885 {
886         return cellInfo(cell).top_line;
887 }
888
889
890 bool Tabular::bottomLine(idx_type const cell) const
891 {
892         return cellInfo(cell).bottom_line;
893 }
894
895
896 bool Tabular::leftLine(idx_type cell) const
897 {
898         if (use_booktabs)
899                 return false;
900         return cellInfo(cell).left_line;
901 }
902
903
904 bool Tabular::rightLine(idx_type cell) const
905 {
906         if (use_booktabs)
907                 return false;
908         return cellInfo(cell).right_line;
909 }
910
911
912 int Tabular::interRowSpace(row_type row) const
913 {
914         if (!row || row >= nrows())
915                 return 0;
916
917         int const interline_space = row_info[row - 1].interline_space_default ?
918                 default_line_space :
919                 row_info[row - 1].interline_space.inPixels(width());
920         if (rowTopLine(row) && rowBottomLine(row - 1))
921                 return interline_space + WIDTH_OF_LINE;
922         return interline_space;
923 }
924
925
926 int Tabular::interColumnSpace(idx_type cell) const
927 {
928         col_type const nextcol = cellColumn(cell) + columnSpan(cell);
929         if (rightLine(cell) && nextcol < ncols()
930                 && leftLine(cellIndex(cellRow(cell), nextcol)))
931                 return WIDTH_OF_LINE;
932         return 0;
933 }
934
935
936 int Tabular::cellWidth(idx_type cell) const
937 {
938         int w = 0;
939         col_type const span = columnSpan(cell);
940         col_type const col = cellColumn(cell);
941         for(col_type c = col; c < col + span ; ++c)
942                 w += column_info[c].width;
943         return w;
944 }
945
946
947 int Tabular::cellHeight(idx_type cell) const
948 {
949         row_type const span = rowSpan(cell);
950         row_type const row = cellRow(cell);
951         int h = 0;
952         for(row_type r = row; r < row + span ; ++r) {
953                 h += rowAscent(r) + rowDescent(r);
954                 if (r != row + span - 1)
955                         h += interRowSpace(r + 1);
956         }
957
958         return h;
959 }
960
961
962 bool Tabular::updateColumnWidths()
963 {
964         vector<int> max_dwidth(ncols(), 0);
965         for(col_type c = 0; c < ncols(); ++c)
966                 for(row_type r = 0; r < nrows(); ++r) {
967                         idx_type const i = cellIndex(r, c);
968                         if (getAlignment(i) == LYX_ALIGN_DECIMAL)
969                                 max_dwidth[c] = max(max_dwidth[c], cell_info[r][c].decimal_width);
970                 }
971
972         bool update = false;
973         // for each col get max of single col cells
974         for(col_type c = 0; c < ncols(); ++c) {
975                 int new_width = 0;
976                 for(row_type r = 0; r < nrows(); ++r) {
977                         idx_type const i = cellIndex(r, c);
978                         if (columnSpan(i) == 1) {
979                                 if (getAlignment(i) == LYX_ALIGN_DECIMAL
980                                         && cell_info[r][c].decimal_width!=0)
981                                         new_width = max(new_width, cellInfo(i).width 
982                                                 + max_dwidth[c] - cellInfo(i).decimal_width);
983                                 else
984                                         new_width = max(new_width, cellInfo(i).width);
985                         }
986                 }
987
988                 if (column_info[c].width != new_width) {
989                         column_info[c].width = new_width;
990                         update = true;
991                 }
992         }
993         // update col widths to fit merged cells
994         for(col_type c = 0; c < ncols(); ++c)
995                 for(row_type r = 0; r < nrows(); ++r) {
996                         idx_type const i = cellIndex(r, c);
997                         int const span = columnSpan(i);
998                         if (span == 1 || c > cellColumn(i))
999                                 continue;
1000
1001                         int old_width = 0;
1002                         for(col_type j = c; j < c + span ; ++j)
1003                                 old_width += column_info[j].width;
1004
1005                         if (cellInfo(i).width > old_width) {
1006                                 column_info[c + span - 1].width += cellInfo(i).width - old_width;
1007                                 update = true;
1008                         }
1009                 }
1010
1011         return update;
1012 }
1013
1014
1015 int Tabular::width() const
1016 {
1017         int width = 0;
1018         for (col_type c = 0; c < ncols(); ++c)
1019                 width += column_info[c].width;
1020         return width;
1021 }
1022
1023
1024 void Tabular::setAlignment(idx_type cell, LyXAlignment align,
1025                               bool has_width)
1026 {
1027         col_type const col = cellColumn(cell);
1028         // set alignment for the whole row if we are not in a multicolumn cell,
1029         // exclude possible multicolumn cells in the row
1030         if (!isMultiColumn(cell)) {
1031                 for (row_type r = 0; r < nrows(); ++r) {
1032                         // only if the column has no width the multirow inherits the
1033                         // alignment of the column, otherwise it is left aligned
1034                         if (!(isMultiRow(cellIndex(r, col)) && has_width)
1035                                 && !isMultiColumn(cellIndex(r, col))) {
1036                                 cell_info[r][col].alignment = align;
1037                                 cell_info[r][col].inset->setContentAlignment(align);
1038                         }
1039                         if ((isMultiRow(cellIndex(r, col)) && has_width)
1040                                 && !isMultiColumn(cellIndex(r, col))) {
1041                                 cell_info[r][col].alignment = LYX_ALIGN_LEFT;
1042                                 cell_info[r][col].inset->setContentAlignment(LYX_ALIGN_LEFT);
1043                         }
1044                 }
1045                 column_info[col].alignment = align;
1046                 docstring & dpoint = column_info[col].decimal_point;
1047                 if (align == LYX_ALIGN_DECIMAL && dpoint.empty())
1048                         dpoint = from_utf8(lyxrc.default_decimal_point);
1049         } else {
1050                 cellInfo(cell).alignment = align; 
1051                 cellInset(cell).get()->setContentAlignment(align); 
1052         }
1053 }
1054
1055
1056 void Tabular::setVAlignment(idx_type cell, VAlignment align,
1057                                bool onlycolumn)
1058 {
1059         if (!isMultiColumn(cell) || onlycolumn)
1060                 column_info[cellColumn(cell)].valignment = align;
1061         if (!onlycolumn)
1062                 cellInfo(cell).valignment = align;
1063 }
1064
1065
1066 namespace {
1067
1068 /**
1069  * Allow line and paragraph breaks for fixed width cells or disallow them,
1070  * merge cell paragraphs and reset layout to standard for variable width
1071  * cells.
1072  */
1073 void toggleFixedWidth(Cursor & cur, InsetTableCell * inset, bool fixedWidth)
1074 {
1075         inset->setAutoBreakRows(fixedWidth);
1076         inset->toggleFixedWidth(fixedWidth);
1077         if (fixedWidth)
1078                 return;
1079
1080         // merge all paragraphs to one
1081         BufferParams const & bp = cur.bv().buffer().params();
1082         while (inset->paragraphs().size() > 1)
1083                 mergeParagraph(bp, inset->paragraphs(), 0);
1084
1085         // reset layout
1086         cur.push(*inset);
1087         // undo information has already been recorded
1088         inset->getText(0)->setLayout(0, cur.lastpit() + 1,
1089                         bp.documentClass().plainLayoutName());
1090         cur.pop();
1091 }
1092
1093 }
1094
1095
1096 void Tabular::setColumnPWidth(Cursor & cur, idx_type cell,
1097                 Length const & width)
1098 {
1099         col_type const c = cellColumn(cell);
1100
1101         column_info[c].p_width = width;
1102         // reset the vertical alignment to top if the fixed with
1103         // is removed or zero because only fixed width columns can
1104         // have a vertical alignment
1105         if (column_info[c].p_width.zero())
1106                 column_info[c].valignment = LYX_VALIGN_TOP;
1107         for (row_type r = 0; r < nrows(); ++r) {
1108                 idx_type const cell = cellIndex(r, c);
1109                 // because of multicolumns
1110                 toggleFixedWidth(cur, cellInset(cell).get(),
1111                                  !getPWidth(cell).zero());
1112         }
1113         // cur paragraph can become invalid after paragraphs were merged
1114         if (cur.pit() > cur.lastpit())
1115                 cur.pit() = cur.lastpit();
1116         // cur position can become invalid after newlines were removed
1117         if (cur.pos() > cur.lastpos())
1118                 cur.pos() = cur.lastpos();
1119 }
1120
1121
1122 bool Tabular::setFixedWidth(row_type r, col_type c)
1123 {
1124         bool const multicol = cell_info[r][c].multicolumn != CELL_NORMAL;
1125         bool const fixed_width = (!column_info[c].p_width.zero() && !multicol)
1126               || (multicol && !cell_info[r][c].p_width.zero());
1127         cell_info[r][c].inset->toggleFixedWidth(fixed_width);
1128         return fixed_width;
1129 }
1130
1131
1132 bool Tabular::setMColumnPWidth(Cursor & cur, idx_type cell,
1133                 Length const & width)
1134 {
1135         if (!isMultiColumn(cell))
1136                 return false;
1137
1138         cellInfo(cell).p_width = width;
1139         toggleFixedWidth(cur, cellInset(cell).get(), !width.zero());
1140         // cur paragraph can become invalid after paragraphs were merged
1141         if (cur.pit() > cur.lastpit())
1142                 cur.pit() = cur.lastpit();
1143         // cur position can become invalid after newlines were removed
1144         if (cur.pos() > cur.lastpos())
1145                 cur.pos() = cur.lastpos();
1146         return true;
1147 }
1148
1149
1150 bool Tabular::setMROffset(Cursor &, idx_type cell, Length const & mroffset)
1151 {
1152         cellInfo(cell).mroffset = mroffset;
1153         return true;
1154 }
1155
1156
1157 void Tabular::setAlignSpecial(idx_type cell, docstring const & special,
1158                                  Tabular::Feature what)
1159 {
1160         if (what == SET_SPECIAL_MULTICOLUMN)
1161                 cellInfo(cell).align_special = special;
1162         else
1163                 column_info[cellColumn(cell)].align_special = special;
1164 }
1165
1166
1167 void Tabular::setTopLine(idx_type i, bool line)
1168 {
1169         cellInfo(i).top_line = line;
1170 }
1171
1172
1173 void Tabular::setBottomLine(idx_type i, bool line)
1174 {
1175         cellInfo(i).bottom_line = line;
1176 }
1177
1178
1179 void Tabular::setLeftLine(idx_type cell, bool line)
1180 {
1181         cellInfo(cell).left_line = line;
1182 }
1183
1184
1185 void Tabular::setRightLine(idx_type cell, bool line)
1186 {
1187         cellInfo(cell).right_line = line;
1188 }
1189
1190 bool Tabular::rowTopLine(row_type r) const
1191 {
1192         bool all_rows_set = true;
1193         for (col_type c = 0; all_rows_set && c < ncols(); ++c)
1194                 all_rows_set = cellInfo(cellIndex(r, c)).top_line;
1195         return all_rows_set;
1196 }
1197
1198
1199 bool Tabular::rowBottomLine(row_type r) const
1200 {
1201         bool all_rows_set = true;
1202         for (col_type c = 0; all_rows_set && c < ncols(); ++c)
1203                 all_rows_set = cellInfo(cellIndex(r, c)).bottom_line;
1204         return all_rows_set;
1205 }
1206
1207
1208 bool Tabular::columnLeftLine(col_type c) const
1209 {
1210         if (use_booktabs)
1211                 return false;
1212
1213         int nrows_left = 0;
1214         int total = 0;
1215         for (row_type r = 0; r < nrows(); ++r) {
1216                 idx_type const i = cellIndex(r, c);
1217                 if (c == cellColumn(i)) {
1218                         ++total;
1219                         bool right = c > 0 && cellInfo(cellIndex(r, c - 1)).right_line;
1220                         if (cellInfo(i).left_line || right)
1221                                 ++nrows_left;
1222                 }
1223         }
1224         return 2 * nrows_left >= total;
1225 }
1226
1227
1228 bool Tabular::columnRightLine(col_type c) const
1229 {
1230         if (use_booktabs)
1231                 return false;
1232
1233         int nrows_right = 0;
1234         int total = 0;
1235         for (row_type r = 0; r < nrows(); ++r) {
1236                 idx_type i = cellIndex(r, c);
1237                 if (c == cellColumn(i) + columnSpan(i) - 1) {
1238                         ++total;
1239                         bool left = (c + 1 < ncols() 
1240                                 && cellInfo(cellIndex(r, c + 1)).left_line)
1241                                 || c + 1 == ncols();
1242                         if (cellInfo(i).right_line && left)
1243                                 ++nrows_right;
1244                 }
1245         }
1246         return 2 * nrows_right >= total;
1247 }
1248
1249
1250 LyXAlignment Tabular::getAlignment(idx_type cell, bool onlycolumn) const
1251 {
1252         if (!onlycolumn && (isMultiColumn(cell) || isMultiRow(cell)))
1253                 return cellInfo(cell).alignment;
1254         
1255         return column_info[cellColumn(cell)].alignment;
1256 }
1257
1258
1259 Tabular::VAlignment
1260 Tabular::getVAlignment(idx_type cell, bool onlycolumn) const
1261 {
1262         if (!onlycolumn && (isMultiColumn(cell) || isMultiRow(cell)))
1263                 return cellInfo(cell).valignment;
1264         return column_info[cellColumn(cell)].valignment;
1265 }
1266
1267
1268 Length const Tabular::getPWidth(idx_type cell) const
1269 {
1270         if (isMultiColumn(cell))
1271                 return cellInfo(cell).p_width;
1272         return column_info[cellColumn(cell)].p_width;
1273 }
1274
1275
1276 Length const Tabular::getMROffset(idx_type cell) const
1277 {
1278         return cellInfo(cell).mroffset;
1279 }
1280
1281
1282 int Tabular::textHOffset(idx_type cell) const
1283 {
1284         // the LaTeX Way :-(
1285         int x = WIDTH_OF_LINE;
1286
1287         int const w = cellWidth(cell) - cellInfo(cell).width;
1288
1289         switch (getAlignment(cell)) {
1290         case LYX_ALIGN_CENTER:
1291                 x += w / 2;
1292                 break;
1293         case LYX_ALIGN_RIGHT:
1294                 x += w;
1295                 break;
1296         case LYX_ALIGN_DECIMAL: {
1297                 // we center when no decimal point
1298                 if (cellInfo(cell).decimal_width == 0) {
1299                         x += w / 2;
1300                         break;
1301                 }
1302                 col_type const c = cellColumn(cell);
1303                 int max_dhoffset = 0;
1304                 for(row_type r = 0; r < row_info.size() ; ++r) {
1305                         idx_type const i = cellIndex(r, c);
1306                         if (getAlignment(i) == LYX_ALIGN_DECIMAL
1307                                 && cellInfo(i).decimal_width != 0)
1308                                 max_dhoffset = max(max_dhoffset, cellInfo(i).decimal_hoffset);
1309                 }
1310                 x += max_dhoffset - cellInfo(cell).decimal_hoffset;
1311         }
1312         default:
1313                 // LYX_ALIGN_LEFT: nothing :-)
1314                 break;
1315         }
1316
1317         return x;
1318 }
1319
1320
1321 int Tabular::textVOffset(idx_type cell) const
1322 {
1323         int voffset = cellInfo(cell).voffset;
1324         if (isMultiRow(cell)) {
1325                 row_type const row = cellRow(cell);
1326                 voffset += (cellHeight(cell) - rowAscent(row) - rowDescent(row))/2; 
1327         }
1328         return voffset;
1329 }
1330
1331
1332 Tabular::idx_type Tabular::getFirstCellInRow(row_type row) const
1333 {
1334         col_type c = 0;
1335         idx_type const numcells = numberOfCellsInRow(row);
1336         // we check against numcells to make sure we do not crash if all the
1337         // cells are multirow (bug #7535), but in that case our return value
1338         // is really invalid, i.e., it is NOT the first cell in the row. but
1339         // i do not know what to do here. (rgh)
1340         while (c < numcells - 1
1341                && cell_info[row][c].multirow == CELL_PART_OF_MULTIROW)
1342                 ++c;
1343         return cell_info[row][c].cellno;
1344 }
1345
1346
1347 Tabular::idx_type Tabular::getLastCellInRow(row_type row) const
1348 {
1349         col_type c = ncols() - 1;
1350         // of course we check against 0 so we don't crash. but we have the same
1351         // problem as in the previous routine: if all the cells are part of a
1352         // multirow or part of a multi column, then our return value is invalid.
1353         while (c > 0
1354                && (cell_info[row][c].multirow == CELL_PART_OF_MULTIROW
1355                    || cell_info[row][c].multicolumn == CELL_PART_OF_MULTICOLUMN))
1356                 --c;
1357         return cell_info[row][c].cellno;
1358 }
1359
1360
1361 Tabular::row_type Tabular::cellRow(idx_type cell) const
1362 {
1363         if (cell >= numberofcells)
1364                 return nrows() - 1;
1365         if (cell == npos)
1366                 return 0;
1367         return rowofcell[cell];
1368 }
1369
1370
1371 Tabular::col_type Tabular::cellColumn(idx_type cell) const
1372 {
1373         if (cell >= numberofcells)
1374                 return ncols() - 1;
1375         if (cell == npos)
1376                 return 0;
1377         return columnofcell[cell];
1378 }
1379
1380
1381 void Tabular::write(ostream & os) const
1382 {
1383         // header line
1384         os << "<lyxtabular"
1385            << write_attribute("version", 3)
1386            << write_attribute("rows", nrows())
1387            << write_attribute("columns", ncols())
1388            << ">\n";
1389         // global longtable options
1390         os << "<features"
1391            << write_attribute("rotate", convert<string>(rotate))
1392            << write_attribute("booktabs", use_booktabs)
1393            << write_attribute("islongtable", is_long_tabular)
1394            << write_attribute("firstHeadTopDL", endfirsthead.topDL)
1395            << write_attribute("firstHeadBottomDL", endfirsthead.bottomDL)
1396            << write_attribute("firstHeadEmpty", endfirsthead.empty)
1397            << write_attribute("headTopDL", endhead.topDL)
1398            << write_attribute("headBottomDL", endhead.bottomDL)
1399            << write_attribute("footTopDL", endfoot.topDL)
1400            << write_attribute("footBottomDL", endfoot.bottomDL)
1401            << write_attribute("lastFootTopDL", endlastfoot.topDL)
1402            << write_attribute("lastFootBottomDL", endlastfoot.bottomDL)
1403            << write_attribute("lastFootEmpty", endlastfoot.empty);
1404         // longtables cannot be aligned vertically
1405         if (!is_long_tabular) {
1406            os << write_attribute("tabularvalignment", tabular_valignment);
1407            os << write_attribute("tabularwidth", tabular_width);
1408         }
1409         if (is_long_tabular)
1410            os << write_attribute("longtabularalignment",
1411                                  longtabular_alignment);
1412         os << ">\n";
1413         for (col_type c = 0; c < ncols(); ++c) {
1414                 os << "<column"
1415                    << write_attribute("alignment", column_info[c].alignment);
1416                 if (column_info[c].alignment == LYX_ALIGN_DECIMAL)
1417                    os << write_attribute("decimal_point", column_info[c].decimal_point);
1418                 os << write_attribute("valignment", column_info[c].valignment)
1419                    << write_attribute("width", column_info[c].p_width.asString())
1420                    << write_attribute("special", column_info[c].align_special)
1421                    << ">\n";
1422         }
1423         for (row_type r = 0; r < nrows(); ++r) {
1424                 static const string def("default");
1425                 os << "<row";
1426                 if (row_info[r].top_space_default)
1427                         os << write_attribute("topspace", def);
1428                 else
1429                         os << write_attribute("topspace", row_info[r].top_space);
1430                 if (row_info[r].bottom_space_default)
1431                         os << write_attribute("bottomspace", def);
1432                 else
1433                         os << write_attribute("bottomspace", row_info[r].bottom_space);
1434                 if (row_info[r].interline_space_default)
1435                         os << write_attribute("interlinespace", def);
1436                 else
1437                         os << write_attribute("interlinespace", row_info[r].interline_space);
1438                 os << write_attribute("endhead", row_info[r].endhead)
1439                    << write_attribute("endfirsthead", row_info[r].endfirsthead)
1440                    << write_attribute("endfoot", row_info[r].endfoot)
1441                    << write_attribute("endlastfoot", row_info[r].endlastfoot)
1442                    << write_attribute("newpage", row_info[r].newpage)
1443                    << write_attribute("caption", row_info[r].caption)
1444                    << ">\n";
1445                 for (col_type c = 0; c < ncols(); ++c) {
1446                         os << "<cell"
1447                            << write_attribute("multicolumn", cell_info[r][c].multicolumn)
1448                            << write_attribute("multirow", cell_info[r][c].multirow)
1449                            << write_attribute("mroffset", cell_info[r][c].mroffset)
1450                            << write_attribute("alignment", cell_info[r][c].alignment)
1451                            << write_attribute("valignment", cell_info[r][c].valignment)
1452                            << write_attribute("topline", cell_info[r][c].top_line)
1453                            << write_attribute("bottomline", cell_info[r][c].bottom_line)
1454                            << write_attribute("leftline", cell_info[r][c].left_line)
1455                            << write_attribute("rightline", cell_info[r][c].right_line)
1456                            << write_attribute("rotate", cell_info[r][c].rotate)
1457                            << write_attribute("usebox", cell_info[r][c].usebox)
1458                            << write_attribute("width", cell_info[r][c].p_width)
1459                            << write_attribute("special", cell_info[r][c].align_special)
1460                            << ">\n";
1461                         os << "\\begin_inset ";
1462                         cell_info[r][c].inset->write(os);
1463                         os << "\n\\end_inset\n"
1464                            << "</cell>\n";
1465                 }
1466                 os << "</row>\n";
1467         }
1468         os << "</lyxtabular>\n";
1469 }
1470
1471
1472 void Tabular::read(Lexer & lex)
1473 {
1474         string line;
1475         istream & is = lex.getStream();
1476
1477         l_getline(is, line);
1478         if (!prefixIs(line, "<lyxtabular ") && !prefixIs(line, "<Tabular ")) {
1479                 LASSERT(false, /**/);
1480                 return;
1481         }
1482
1483         int version;
1484         if (!getTokenValue(line, "version", version))
1485                 return;
1486         LASSERT(version >= 2, /**/);
1487
1488         int rows_arg;
1489         if (!getTokenValue(line, "rows", rows_arg))
1490                 return;
1491         int columns_arg;
1492         if (!getTokenValue(line, "columns", columns_arg))
1493                 return;
1494         init(buffer_, rows_arg, columns_arg);
1495         l_getline(is, line);
1496         if (!prefixIs(line, "<features")) {
1497                 lyxerr << "Wrong tabular format (expected <features ...> got"
1498                        << line << ')' << endl;
1499                 return;
1500         }
1501         getTokenValue(line, "rotate", rotate);
1502         getTokenValue(line, "booktabs", use_booktabs);
1503         getTokenValue(line, "islongtable", is_long_tabular);
1504         getTokenValue(line, "tabularvalignment", tabular_valignment);
1505         getTokenValue(line, "tabularwidth", tabular_width);
1506         getTokenValue(line, "longtabularalignment", longtabular_alignment);
1507         getTokenValue(line, "firstHeadTopDL", endfirsthead.topDL);
1508         getTokenValue(line, "firstHeadBottomDL", endfirsthead.bottomDL);
1509         getTokenValue(line, "firstHeadEmpty", endfirsthead.empty);
1510         getTokenValue(line, "headTopDL", endhead.topDL);
1511         getTokenValue(line, "headBottomDL", endhead.bottomDL);
1512         getTokenValue(line, "footTopDL", endfoot.topDL);
1513         getTokenValue(line, "footBottomDL", endfoot.bottomDL);
1514         getTokenValue(line, "lastFootTopDL", endlastfoot.topDL);
1515         getTokenValue(line, "lastFootBottomDL", endlastfoot.bottomDL);
1516         getTokenValue(line, "lastFootEmpty", endlastfoot.empty);
1517
1518         for (col_type c = 0; c < ncols(); ++c) {
1519                 l_getline(is,line);
1520                 if (!prefixIs(line,"<column")) {
1521                         lyxerr << "Wrong tabular format (expected <column ...> got"
1522                                << line << ')' << endl;
1523                         return;
1524                 }
1525                 getTokenValue(line, "alignment", column_info[c].alignment);
1526                 getTokenValue(line, "decimal_point", column_info[c].decimal_point);
1527                 getTokenValue(line, "valignment", column_info[c].valignment);
1528                 getTokenValue(line, "width", column_info[c].p_width);
1529                 getTokenValue(line, "special", column_info[c].align_special);
1530         }
1531
1532         for (row_type i = 0; i < nrows(); ++i) {
1533                 l_getline(is, line);
1534                 if (!prefixIs(line, "<row")) {
1535                         lyxerr << "Wrong tabular format (expected <row ...> got"
1536                                << line << ')' << endl;
1537                         return;
1538                 }
1539                 getTokenValue(line, "topspace", row_info[i].top_space,
1540                               row_info[i].top_space_default);
1541                 getTokenValue(line, "bottomspace", row_info[i].bottom_space,
1542                               row_info[i].bottom_space_default);
1543                 getTokenValue(line, "interlinespace", row_info[i].interline_space,
1544                               row_info[i].interline_space_default);
1545                 getTokenValue(line, "endfirsthead", row_info[i].endfirsthead);
1546                 getTokenValue(line, "endhead", row_info[i].endhead);
1547                 getTokenValue(line, "endfoot", row_info[i].endfoot);
1548                 getTokenValue(line, "endlastfoot", row_info[i].endlastfoot);
1549                 getTokenValue(line, "newpage", row_info[i].newpage);
1550                 getTokenValue(line, "caption", row_info[i].caption);
1551                 for (col_type j = 0; j < ncols(); ++j) {
1552                         l_getline(is, line);
1553                         if (!prefixIs(line, "<cell")) {
1554                                 lyxerr << "Wrong tabular format (expected <cell ...> got"
1555                                        << line << ')' << endl;
1556                                 return;
1557                         }
1558                         getTokenValue(line, "multicolumn", cell_info[i][j].multicolumn);
1559                         getTokenValue(line, "multirow", cell_info[i][j].multirow);
1560                         getTokenValue(line, "mroffset", cell_info[i][j].mroffset);
1561                         getTokenValue(line, "alignment", cell_info[i][j].alignment);
1562                         getTokenValue(line, "valignment", cell_info[i][j].valignment);
1563                         getTokenValue(line, "topline", cell_info[i][j].top_line);
1564                         getTokenValue(line, "bottomline", cell_info[i][j].bottom_line);
1565                         getTokenValue(line, "leftline", cell_info[i][j].left_line);
1566                         getTokenValue(line, "rightline", cell_info[i][j].right_line);
1567                         getTokenValue(line, "rotate", cell_info[i][j].rotate);
1568                         getTokenValue(line, "usebox", cell_info[i][j].usebox);
1569                         getTokenValue(line, "width", cell_info[i][j].p_width);
1570                         setFixedWidth(i,j);
1571                         getTokenValue(line, "special", cell_info[i][j].align_special);
1572                         l_getline(is, line);
1573                         if (prefixIs(line, "\\begin_inset")) {
1574                                 cell_info[i][j].inset->setBuffer(*buffer_);
1575                                 cell_info[i][j].inset->read(lex);
1576                                 l_getline(is, line);
1577                         }
1578                         if (!prefixIs(line, "</cell>")) {
1579                                 lyxerr << "Wrong tabular format (expected </cell> got"
1580                                        << line << ')' << endl;
1581                                 return;
1582                         }
1583                 }
1584                 l_getline(is, line);
1585                 if (!prefixIs(line, "</row>")) {
1586                         lyxerr << "Wrong tabular format (expected </row> got"
1587                                << line << ')' << endl;
1588                         return;
1589                 }
1590         }
1591         while (!prefixIs(line, "</lyxtabular>")) {
1592                 l_getline(is, line);
1593         }
1594         updateIndexes();
1595 }
1596
1597
1598 bool Tabular::isMultiColumn(idx_type cell) const
1599 {
1600         return (cellInfo(cell).multicolumn == CELL_BEGIN_OF_MULTICOLUMN 
1601                 || cellInfo(cell).multicolumn == CELL_PART_OF_MULTICOLUMN);
1602 }
1603
1604
1605 Tabular::CellData & Tabular::cellInfo(idx_type cell) const
1606 {
1607         return cell_info[cellRow(cell)][cellColumn(cell)];
1608 }
1609
1610
1611 Tabular::idx_type Tabular::setMultiColumn(idx_type cell, idx_type number,
1612                                           bool const right_border)
1613 {
1614         idx_type const col = cellColumn(cell);
1615         idx_type const row = cellRow(cell);
1616         for (idx_type i = 0; i < number; ++i)
1617                 unsetMultiRow(cellIndex(row, col + i));
1618
1619         // unsetting of multirow may have invalidated cell index
1620         cell = cellIndex(row, col);
1621         CellData & cs = cellInfo(cell);
1622         cs.multicolumn = CELL_BEGIN_OF_MULTICOLUMN;
1623         if (column_info[col].alignment != LYX_ALIGN_DECIMAL)
1624                 cs.alignment = column_info[col].alignment;
1625         if (col > 0)
1626                 setRightLine(cell, right_border);
1627
1628         for (idx_type i = 1; i < number; ++i) {
1629                 CellData & cs1 = cellInfo(cell + i);
1630                 cs1.multicolumn = CELL_PART_OF_MULTICOLUMN;
1631                 cs.inset->appendParagraphs(cs1.inset->paragraphs());
1632                 cs1.inset->clear();
1633         }
1634         updateIndexes();
1635         return cell;
1636 }
1637
1638
1639 bool Tabular::isMultiRow(idx_type cell) const
1640 {
1641         return (cellInfo(cell).multirow == CELL_BEGIN_OF_MULTIROW
1642                 || cellInfo(cell).multirow == CELL_PART_OF_MULTIROW);
1643 }
1644
1645
1646 Tabular::idx_type Tabular::setMultiRow(idx_type cell, idx_type number,
1647                                        bool const bottom_border)
1648 {
1649         idx_type const col = cellColumn(cell);
1650         idx_type const row = cellRow(cell);
1651         for (idx_type i = 0; i < number; ++i)
1652                 unsetMultiColumn(cellIndex(row + i, col));
1653
1654         // unsetting of multirow may have invalidated cell index
1655         cell = cellIndex(row, col);
1656         CellData & cs = cellInfo(cell);
1657         cs.multirow = CELL_BEGIN_OF_MULTIROW;
1658         cs.valignment = LYX_VALIGN_MIDDLE;
1659         // the horizontal alignment of multirow cells can only
1660         // be changed for the whole table row,
1661         // support changing this only for the multirow cell can be done via
1662         // \multirowsetup
1663         // this feature would be a fileformat change
1664         // until LyX supports this, use the deault alignment of multirow
1665         // cells: left
1666         cs.alignment = LYX_ALIGN_LEFT;
1667
1668         // set the bottom line of the last selected cell
1669         setBottomLine(cell, bottom_border);
1670
1671         for (idx_type i = 1; i < number; ++i) {
1672                 CellData & cs1 = cell_info[row + i][col];
1673                 cs1.multirow = CELL_PART_OF_MULTIROW;
1674                 cs.inset->appendParagraphs(cs1.inset->paragraphs());
1675                 cs1.inset->clear();
1676         }
1677         updateIndexes();
1678         return cell;
1679 }
1680
1681
1682 Tabular::idx_type Tabular::columnSpan(idx_type cell) const
1683 {
1684         row_type const row = cellRow(cell);
1685         col_type const col = cellColumn(cell);
1686         int span = 1;
1687         while (col + span < ncols() && isPartOfMultiColumn(row, col + span))
1688                 ++span;
1689
1690         return span;
1691 }
1692
1693
1694 Tabular::idx_type Tabular::rowSpan(idx_type cell) const
1695 {
1696         col_type const column = cellColumn(cell);
1697         col_type row = cellRow(cell) + 1;
1698         while (row < nrows() && isPartOfMultiRow(row, column))
1699                 ++row;
1700         
1701         return row - cellRow(cell);
1702 }
1703
1704
1705 void Tabular::unsetMultiColumn(idx_type cell)
1706 {
1707         if (!isMultiColumn(cell))
1708                 return;
1709
1710         row_type const row = cellRow(cell);
1711         col_type const col = cellColumn(cell);
1712         row_type const span = columnSpan(cell);
1713         for (col_type c = 0; c < span; ++c) {
1714                 // in the table dialog the lines are set in every case
1715                 // when unsetting a multicolumn this leads to an additional right
1716                 // line for every cell that was part of the former multicolumn cell,
1717                 // except if the cell is in the last column
1718                 // therefore remove this line
1719                 if (cell_info[row][col + c].multicolumn == CELL_BEGIN_OF_MULTICOLUMN
1720                         && (col + c) < (col + span - 1))
1721                         cell_info[row][col + c].right_line = false;
1722                 cell_info[row][col + c].multicolumn = CELL_NORMAL;
1723         }
1724         updateIndexes();
1725 }
1726
1727
1728 void Tabular::unsetMultiRow(idx_type cell)
1729 {
1730         if (!isMultiRow(cell))
1731                 return;
1732
1733         cellInfo(cell).valignment = LYX_VALIGN_TOP;
1734         cellInfo(cell).alignment = LYX_ALIGN_CENTER;
1735         row_type const row = cellRow(cell);
1736         col_type const col = cellColumn(cell);
1737         row_type const span = rowSpan(cell);
1738         for (row_type r = 0; r < span; ++r)
1739                 cell_info[row + r][col].multirow = CELL_NORMAL;
1740         updateIndexes();
1741 }
1742
1743
1744 void Tabular::setRotateCell(idx_type cell, int value)
1745 {
1746         cellInfo(cell).rotate = value;
1747 }
1748
1749
1750 int Tabular::getRotateCell(idx_type cell) const
1751 {
1752         return cellInfo(cell).rotate;
1753 }
1754
1755
1756 bool Tabular::needRotating() const
1757 {
1758         if (rotate)
1759                 return true;
1760         for (row_type r = 0; r < nrows(); ++r)
1761                 for (col_type c = 0; c < ncols(); ++c)
1762                         if (cell_info[r][c].rotate != 0)
1763                                 return true;
1764         return false;
1765 }
1766
1767
1768 bool Tabular::isLastCell(idx_type cell) const
1769 {
1770         if (cell + 1 < numberofcells)
1771                 return false;
1772         return true;
1773 }
1774
1775
1776 Tabular::idx_type Tabular::cellAbove(idx_type cell) const
1777 {
1778         if (cellRow(cell) == 0)
1779                 return cell;
1780         
1781         col_type const col = cellColumn(cell);
1782         row_type r = cellRow(cell) - 1;
1783         while (r > 0 && cell_info[r][col].multirow == CELL_PART_OF_MULTIROW)
1784                 --r;
1785
1786         return cell_info[r][col].cellno;
1787 }
1788
1789
1790 Tabular::idx_type Tabular::cellBelow(idx_type cell) const
1791 {
1792         row_type const nextrow = cellRow(cell) + rowSpan(cell);
1793         if (nextrow < nrows())
1794                 return cell_info[nextrow][cellColumn(cell)].cellno;
1795         return cell;
1796 }
1797
1798
1799 Tabular::idx_type Tabular::cellIndex(row_type row, col_type column) const
1800 {
1801         LASSERT(column != npos && column < ncols()
1802                 && row != npos && row < nrows(), /**/);
1803         return cell_info[row][column].cellno;
1804 }
1805
1806
1807 void Tabular::setUsebox(idx_type cell, BoxType type)
1808 {
1809         cellInfo(cell).usebox = type;
1810 }
1811
1812
1813 // FIXME: Remove this routine because we cannot insert \parboxes when the user
1814 // adds line breaks, see bug 4886.
1815 Tabular::BoxType Tabular::getUsebox(idx_type cell) const
1816 {
1817         if ((!column_info[cellColumn(cell)].p_width.zero() && !isMultiColumn(cell)) ||
1818                 (isMultiColumn(cell) && !cellInfo(cell).p_width.zero()))
1819                 return BOX_NONE;
1820         if (cellInfo(cell).usebox > 1)
1821                 return cellInfo(cell).usebox;
1822         return useParbox(cell);
1823 }
1824
1825
1826 ///
1827 //  This are functions used for the longtable support
1828 ///
1829 void Tabular::setLTHead(row_type row, bool flag, ltType const & hd,
1830                            bool first)
1831 {
1832         if (first) {
1833                 endfirsthead = hd;
1834                 if (hd.set)
1835                         row_info[row].endfirsthead = flag;
1836         } else {
1837                 endhead = hd;
1838                 if (hd.set)
1839                         row_info[row].endhead = flag;
1840         }
1841 }
1842
1843
1844 bool Tabular::getRowOfLTHead(row_type row, ltType & hd) const
1845 {
1846         hd = endhead;
1847         hd.set = haveLTHead();
1848         return row_info[row].endhead;
1849 }
1850
1851
1852 bool Tabular::getRowOfLTFirstHead(row_type row, ltType & hd) const
1853 {
1854         hd = endfirsthead;
1855         hd.set = haveLTFirstHead();
1856         return row_info[row].endfirsthead;
1857 }
1858
1859
1860 void Tabular::setLTFoot(row_type row, bool flag, ltType const & fd,
1861                            bool last)
1862 {
1863         if (last) {
1864                 endlastfoot = fd;
1865                 if (fd.set)
1866                         row_info[row].endlastfoot = flag;
1867         } else {
1868                 endfoot = fd;
1869                 if (fd.set)
1870                         row_info[row].endfoot = flag;
1871         }
1872 }
1873
1874
1875 bool Tabular::getRowOfLTFoot(row_type row, ltType & fd) const
1876 {
1877         fd = endfoot;
1878         fd.set = haveLTFoot();
1879         return row_info[row].endfoot;
1880 }
1881
1882
1883 bool Tabular::getRowOfLTLastFoot(row_type row, ltType & fd) const
1884 {
1885         fd = endlastfoot;
1886         fd.set = haveLTLastFoot();
1887         return row_info[row].endlastfoot;
1888 }
1889
1890
1891 void Tabular::setLTNewPage(row_type row, bool what)
1892 {
1893         row_info[row].newpage = what;
1894 }
1895
1896
1897 bool Tabular::getLTNewPage(row_type row) const
1898 {
1899         return row_info[row].newpage;
1900 }
1901
1902
1903 bool Tabular::haveLTHead(bool withcaptions) const
1904 {
1905         if (!is_long_tabular)
1906                 return false;
1907         for (row_type i = 0; i < nrows(); ++i)
1908                 if (row_info[i].endhead &&
1909                     (withcaptions || !row_info[i].caption))
1910                         return true;
1911         return false;
1912 }
1913
1914
1915 bool Tabular::haveLTFirstHead(bool withcaptions) const
1916 {
1917         if (!is_long_tabular || endfirsthead.empty)
1918                 return false;
1919         for (row_type r = 0; r < nrows(); ++r)
1920                 if (row_info[r].endfirsthead &&
1921                     (withcaptions || !row_info[r].caption))
1922                         return true;
1923         return false;
1924 }
1925
1926
1927 bool Tabular::haveLTFoot(bool withcaptions) const
1928 {
1929         if (!is_long_tabular)
1930                 return false;
1931         for (row_type r = 0; r < nrows(); ++r)
1932                 if (row_info[r].endfoot &&
1933                     (withcaptions || !row_info[r].caption))
1934                         return true;
1935         return false;
1936 }
1937
1938
1939 bool Tabular::haveLTLastFoot(bool withcaptions) const
1940 {
1941         if (!is_long_tabular || endlastfoot.empty)
1942                 return false;
1943         for (row_type r = 0; r < nrows(); ++r)
1944                 if (row_info[r].endlastfoot &&
1945                     (withcaptions || !row_info[r].caption))
1946                         return true;
1947         return false;
1948 }
1949
1950
1951 Tabular::idx_type Tabular::setLTCaption(row_type row, bool what)
1952 {
1953         idx_type i = getFirstCellInRow(row);
1954         if (what) {
1955                 setMultiColumn(i, numberOfCellsInRow(row), false);
1956                 setTopLine(i, false);
1957                 setBottomLine(i, false);
1958                 setLeftLine(i, false);
1959                 setRightLine(i, false);
1960                 if (!row_info[row].endfirsthead && !row_info[row].endhead &&
1961                     !row_info[row].endfoot && !row_info[row].endlastfoot) {
1962                         setLTHead(row, true, endfirsthead, true);
1963                         row_info[row].endfirsthead = true;
1964                 }
1965         } else {
1966                 unsetMultiColumn(i);
1967                 // When unsetting a caption row, also all existing
1968                 // captions in this row must be dissolved.
1969         }
1970         row_info[row].caption = what;
1971         return i;
1972 }
1973
1974
1975 bool Tabular::ltCaption(row_type row) const
1976 {
1977         return row_info[row].caption;
1978 }
1979
1980
1981 bool Tabular::haveLTCaption(CaptionType captiontype) const
1982 {
1983         if (!is_long_tabular)
1984                 return false;
1985         for (row_type r = 0; r < nrows(); ++r) {
1986                 if (row_info[r].caption) {
1987                         switch (captiontype) {
1988                         case CAPTION_FIRSTHEAD:
1989                                 if (row_info[r].endfirsthead)
1990                                         return true;
1991                                 break;
1992                         case CAPTION_HEAD:
1993                                 if (row_info[r].endhead)
1994                                         return true;
1995                                 break;
1996                         case CAPTION_FOOT:
1997                                 if (row_info[r].endfoot)
1998                                         return true;
1999                                 break;
2000                         case CAPTION_LASTFOOT:
2001                                 if (row_info[r].endlastfoot)
2002                                         return true;
2003                                 break;
2004                         case CAPTION_ANY:
2005                                 return true;
2006                         }
2007                 }
2008         }
2009         return false;
2010 }
2011
2012
2013 // end longtable support functions
2014
2015 void Tabular::setRowAscent(row_type row, int height)
2016 {
2017         if (row >= nrows() || row_info[row].ascent == height)
2018                 return;
2019         row_info[row].ascent = height;
2020 }
2021
2022
2023 void Tabular::setRowDescent(row_type row, int height)
2024 {
2025         if (row >= nrows() || row_info[row].descent == height)
2026                 return;
2027         row_info[row].descent = height;
2028 }
2029
2030
2031 int Tabular::rowAscent(row_type row) const
2032 {
2033         LASSERT(row < nrows(), /**/);
2034         return row_info[row].ascent;
2035 }
2036
2037
2038 int Tabular::rowDescent(row_type row) const
2039 {
2040         LASSERT(row < nrows(), /**/);
2041         return row_info[row].descent;
2042 }
2043
2044
2045 int Tabular::height() const
2046 {
2047         int height = 0;
2048         for (row_type row = 0; row < nrows(); ++row)
2049                 height += rowAscent(row) + rowDescent(row) +
2050                         interRowSpace(row);
2051         return height;
2052 }
2053
2054
2055 bool Tabular::isPartOfMultiColumn(row_type row, col_type column) const
2056 {
2057         LASSERT(row < nrows(), /**/);
2058         LASSERT(column < ncols(), /**/);
2059         return cell_info[row][column].multicolumn == CELL_PART_OF_MULTICOLUMN;
2060 }
2061
2062
2063 bool Tabular::isPartOfMultiRow(row_type row, col_type column) const
2064 {
2065         LASSERT(row < nrows(), /**/);
2066         LASSERT(column < ncols(), /**/);
2067         return cell_info[row][column].multirow == CELL_PART_OF_MULTIROW;
2068 }
2069
2070
2071 void Tabular::TeXTopHLine(otexstream & os, row_type row, string const lang) const
2072 {
2073         // we only output complete row lines and the 1st row here, the rest
2074         // is done in Tabular::TeXBottomHLine(...)
2075
2076         // get for each column the topline (if any)
2077         vector<bool> topline;
2078         col_type nset = 0;
2079         for (col_type c = 0; c < ncols(); ++c) {
2080                 topline.push_back(topLine(cellIndex(row, c)));
2081                 // If cell is part of a multirow and not the first cell of the
2082                 // multirow, no line must be drawn.
2083                 if (row != 0)
2084                         if (isMultiRow(cellIndex(row, c))
2085                             && cell_info[row][c].multirow != CELL_BEGIN_OF_MULTIROW)
2086                                 topline[c] = false;
2087                 if (topline[c])
2088                         ++nset;
2089         }
2090
2091         // do nothing if empty first row, or incomplete row line after
2092         if ((row == 0 && nset == 0) || (row > 0 && nset != ncols()))
2093                 return;
2094
2095         // only output complete row lines and the 1st row's clines
2096         if (nset == ncols()) {
2097                 if (use_booktabs) {
2098                         os << (row == 0 ? "\\toprule " : "\\midrule ");
2099                 } else {
2100                         os << "\\hline ";
2101                 }
2102         } else if (row == 0) {
2103                 for (col_type c = 0; c < ncols(); ++c) {
2104                         if (topline[c]) {
2105                                 col_type offset = 0;
2106                                 for (col_type j = 0 ; j < c; ++j)
2107                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2108                                                 ++offset;
2109                                 
2110                                 //babel makes the "-" character an active one, so we have to suppress this here
2111                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
2112                                 if (lang == "slovak" || lang == "czech")
2113                                         os << "\\expandafter" << (use_booktabs ? "\\cmidrule" : "\\cline") 
2114                                         << "\\expandafter{\\expandafter" << c + 1 + offset << "\\string-";
2115                                 else
2116                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 + offset << '-';
2117                                 
2118                                 col_type cstart = c;
2119                                 for ( ; c < ncols() && topline[c]; ++c) {}
2120                                 
2121                                 for (col_type j = cstart ; j < c ; ++j)
2122                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2123                                                 ++offset;
2124                                 
2125                                 os << c + offset << "} ";
2126                         }
2127                 }
2128         }
2129         os << "\n";
2130 }
2131
2132
2133 void Tabular::TeXBottomHLine(otexstream & os, row_type row, string const lang) const
2134 {
2135         // we output bottomlines of row r and the toplines of row r+1
2136         // if the latter do not span the whole tabular
2137
2138         // get the bottomlines of row r, and toplines in next row
2139         bool lastrow = row == nrows() - 1;
2140         vector<bool> bottomline, topline;
2141         bool nextrowset = true;
2142         for (col_type c = 0; c < ncols(); ++c) {
2143                 bottomline.push_back(bottomLine(cellIndex(row, c)));
2144                 topline.push_back(!lastrow && topLine(cellIndex(row + 1, c)));
2145                 // If cell is part of a multirow and not the last cell of the
2146                 // multirow, no line must be drawn.
2147                 if (!lastrow)
2148                         if (isMultiRow(cellIndex(row, c))
2149                             && isMultiRow(cellIndex(row + 1, c))
2150                             && cell_info[row + 1][c].multirow != CELL_BEGIN_OF_MULTIROW) {
2151                                 bottomline[c] = false;
2152                                 topline[c] = false;
2153                                 }
2154                 nextrowset &= topline[c];
2155         }
2156
2157         // combine this row's bottom lines and next row's toplines if necessary
2158         col_type nset = 0;
2159         for (col_type c = 0; c < ncols(); ++c) {
2160                 if (!nextrowset)
2161                         bottomline[c] = bottomline[c] || topline[c];
2162                 if (bottomline[c])
2163                         ++nset;
2164         }
2165
2166         // do nothing if empty, OR incomplete row line with a topline in next row
2167         if (nset == 0 || (nextrowset && nset != ncols()))
2168                 return;
2169
2170         if (nset == ncols()) {
2171                 if (use_booktabs)
2172                         os << (lastrow ? "\\bottomrule" : "\\midrule");
2173                 else
2174                         os << "\\hline ";
2175         } else {
2176                 for (col_type c = 0; c < ncols(); ++c) {
2177                         if (bottomline[c]) {
2178                                 col_type offset = 0;
2179                                 for (col_type j = 0 ; j < c; ++j)
2180                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2181                                                 ++offset;
2182                                 
2183                                 //babel makes the "-" character an active one, so we have to suppress this here
2184                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
2185                                 if (lang == "slovak" || lang == "czech")
2186                                         os << "\\expandafter" << (use_booktabs ? "\\cmidrule" : "\\cline")
2187                                         << "\\expandafter{\\expandafter" << c + 1 + offset << "\\string-";
2188                                 else
2189                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 + offset << '-';
2190                                 
2191                                 col_type cstart = c;
2192                                 for ( ; c < ncols() && bottomline[c]; ++c) {}
2193                                 
2194                                 for (col_type j = cstart ; j < c ; ++j)
2195                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2196                                                 ++offset;
2197                                 
2198                                 os << c + offset << "} ";
2199                         }
2200                 }
2201         }
2202         os << "\n";
2203 }
2204
2205
2206 void Tabular::TeXCellPreamble(otexstream & os, idx_type cell,
2207                               bool & ismulticol, bool & ismultirow) const
2208 {
2209         row_type const r = cellRow(cell);
2210         if (is_long_tabular && row_info[r].caption)
2211                 return;
2212
2213         Tabular::VAlignment valign =  getVAlignment(cell, !isMultiColumn(cell));
2214         LyXAlignment align = getAlignment(cell, !isMultiColumn(cell));
2215         // figure out how to set the lines
2216         // we always set double lines to the right of the cell
2217         col_type const c = cellColumn(cell);
2218         col_type const nextcol = c + columnSpan(cell);
2219         bool colright = columnRightLine(c);
2220         bool colleft = columnLeftLine(c);
2221         bool nextcolleft = nextcol < ncols() && columnLeftLine(nextcol);
2222         bool nextcellleft = nextcol < ncols() 
2223                 && leftLine(cellIndex(r, nextcol));
2224         bool coldouble = colright && nextcolleft;
2225         bool celldouble = rightLine(cell) && nextcellleft;
2226
2227         ismulticol = isMultiColumn(cell)
2228                 || (c == 0 && colleft != leftLine(cell))
2229                 || ((colright || nextcolleft) && !rightLine(cell) && !nextcellleft)
2230                 || (!colright && !nextcolleft && (rightLine(cell) || nextcellleft))
2231                 || (coldouble != celldouble);
2232
2233         // we center in multicol when no decimal point
2234         if (column_info[c].alignment == LYX_ALIGN_DECIMAL) {
2235                 docstring const align_d = column_info[c].decimal_point;
2236                 DocIterator const dit = separatorPos(cellInset(cell).get(), align_d);
2237                 ismulticol |= !dit;
2238         }
2239
2240         // up counter by 1 for each decimally aligned col since they use 2 latex cols
2241         int latexcolspan = columnSpan(cell);
2242         for(col_type col = c; col < c + columnSpan(cell); ++col)
2243                 if (column_info[col].alignment == LYX_ALIGN_DECIMAL)
2244                         ++latexcolspan;
2245
2246         if (ismulticol) {
2247                 os << "\\multicolumn{" << latexcolspan << "}{";
2248                 if (c ==0 && leftLine(cell))
2249                         os << '|';
2250                 if (!cellInfo(cell).align_special.empty()) {
2251                         os << cellInfo(cell).align_special;
2252                 } else {
2253                         if (!getPWidth(cell).zero()) {
2254                                 switch (align) {
2255                                 case LYX_ALIGN_LEFT:
2256                                         os << ">{\\raggedright}";
2257                                         break;
2258                                 case LYX_ALIGN_RIGHT:
2259                                         os << ">{\\raggedleft}";
2260                                         break;
2261                                 case LYX_ALIGN_CENTER:
2262                                         os << ">{\\centering}";
2263                                         break;
2264                                 default:
2265                                         break;
2266                                 }
2267                                 switch (valign) {
2268                                 case LYX_VALIGN_TOP:
2269                                         os << 'p';
2270                                         break;
2271                                 case LYX_VALIGN_MIDDLE:
2272                                         os << 'm';
2273                                         break;
2274                                 case LYX_VALIGN_BOTTOM:
2275                                         os << 'b';
2276                                         break;
2277                                 }
2278                                 os << '{'
2279                                    << from_ascii(getPWidth(cell).asLatexString())
2280                                    << '}';
2281                         } else {
2282                                 switch (align) {
2283                                 case LYX_ALIGN_LEFT:
2284                                         os << 'l';
2285                                         break;
2286                                 case LYX_ALIGN_RIGHT:
2287                                         os << 'r';
2288                                         break;
2289                                 default:
2290                                         os << 'c';
2291                                         break;
2292                                 }
2293                         } // end if else !getPWidth
2294                 } // end if else !cellinfo_of_cell
2295                 if (rightLine(cell) || nextcellleft)
2296                         os << '|';
2297                 if (celldouble)
2298                         // add extra vertical line if we want a double one
2299                         os << '|';
2300                 os << "}{";
2301         } // end if ismulticol
2302
2303         // we only need code for the first multirow cell
2304         ismultirow = isMultiRow(cell);
2305         if (ismultirow) {
2306                 os << "\\multirow{" << rowSpan(cell) << "}{";
2307                 if (!getPWidth(cell).zero())
2308                         os << from_ascii(getPWidth(cell).asLatexString());
2309                 else
2310                         // we need to set a default value
2311                         os << "*";
2312                 os << "}";
2313                 if (!getMROffset(cell).zero())
2314                         os << "[" << from_ascii(getMROffset(cell).asLatexString()) << "]";
2315                 os << "{";
2316         } // end if ismultirow
2317
2318         if (getRotateCell(cell) != 0)
2319                 os << "\\begin{turn}{" << convert<string>(getRotateCell(cell)) << "}\n";
2320
2321         if (getUsebox(cell) == BOX_PARBOX) {
2322                 os << "\\parbox[";
2323                 switch (valign) {
2324                 case LYX_VALIGN_TOP:
2325                         os << 't';
2326                         break;
2327                 case LYX_VALIGN_MIDDLE:
2328                         os << 'c';
2329                         break;
2330                 case LYX_VALIGN_BOTTOM:
2331                         os << 'b';
2332                         break;
2333                 }
2334                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2335                    << "}{";
2336         } else if (getUsebox(cell) == BOX_MINIPAGE) {
2337                 os << "\\begin{minipage}[";
2338                 switch (valign) {
2339                 case LYX_VALIGN_TOP:
2340                         os << 't';
2341                         break;
2342                 case LYX_VALIGN_MIDDLE:
2343                         os << 'm';
2344                         break;
2345                 case LYX_VALIGN_BOTTOM:
2346                         os << 'b';
2347                         break;
2348                 }
2349                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2350                    << "}\n";
2351         }
2352 }
2353
2354
2355 void Tabular::TeXCellPostamble(otexstream & os, idx_type cell,
2356                                bool ismulticol, bool ismultirow) const
2357 {
2358         row_type const r = cellRow(cell);
2359         if (is_long_tabular && row_info[r].caption)
2360                 return;
2361
2362         // usual cells
2363         if (getUsebox(cell) == BOX_PARBOX)
2364                 os << '}';
2365         else if (getUsebox(cell) == BOX_MINIPAGE)
2366                 os << breakln << "\\end{minipage}";
2367         if (getRotateCell(cell) != 0)
2368                 os << breakln << "\\end{turn}";
2369         if (ismultirow)
2370                 os << '}';
2371         if (ismulticol)
2372                 os << '}';
2373 }
2374
2375
2376 void Tabular::TeXLongtableHeaderFooter(otexstream & os,
2377                                         OutputParams const & runparams) const
2378 {
2379         if (!is_long_tabular)
2380                 return;
2381
2382         // output first header info
2383         if (haveLTFirstHead()) {
2384                 if (endfirsthead.topDL)
2385                         os << "\\hline\n";
2386                 for (row_type r = 0; r < nrows(); ++r) {
2387                         if (row_info[r].endfirsthead)
2388                                 TeXRow(os, r, runparams);
2389                 }
2390                 if (endfirsthead.bottomDL)
2391                         os << "\\hline\n";
2392                 os << "\\endfirsthead\n";
2393         }
2394         // output header info
2395         if (haveLTHead()) {
2396                 if (endfirsthead.empty && !haveLTFirstHead())
2397                         os << "\\endfirsthead\n";
2398                 if (endhead.topDL)
2399                         os << "\\hline\n";
2400                 for (row_type r = 0; r < nrows(); ++r) {
2401                         if (row_info[r].endhead)
2402                                 TeXRow(os, r, runparams);
2403                 }
2404                 if (endhead.bottomDL)
2405                         os << "\\hline\n";
2406                 os << "\\endhead\n";
2407         }
2408         // output footer info
2409         if (haveLTFoot()) {
2410                 if (endfoot.topDL)
2411                         os << "\\hline\n";
2412                 for (row_type r = 0; r < nrows(); ++r) {
2413                         if (row_info[r].endfoot)
2414                                 TeXRow(os, r, runparams);
2415                 }
2416                 if (endfoot.bottomDL)
2417                         os << "\\hline\n";
2418                 os << "\\endfoot\n";
2419                 if (endlastfoot.empty && !haveLTLastFoot())
2420                         os << "\\endlastfoot\n";
2421         }
2422         // output lastfooter info
2423         if (haveLTLastFoot()) {
2424                 if (endlastfoot.topDL)
2425                         os << "\\hline\n";
2426                 for (row_type r = 0; r < nrows(); ++r) {
2427                         if (row_info[r].endlastfoot)
2428                                 TeXRow(os, r, runparams);
2429                 }
2430                 if (endlastfoot.bottomDL)
2431                         os << "\\hline\n";
2432                 os << "\\endlastfoot\n";
2433         }
2434 }
2435
2436
2437 bool Tabular::isValidRow(row_type row) const
2438 {
2439         if (!is_long_tabular)
2440                 return true;
2441         return !row_info[row].endhead && !row_info[row].endfirsthead
2442                 && !row_info[row].endfoot && !row_info[row].endlastfoot
2443                 && !row_info[row].caption;
2444 }
2445
2446
2447 void Tabular::TeXRow(otexstream & os, row_type row,
2448                      OutputParams const & runparams) const
2449 {
2450         idx_type cell = cellIndex(row, 0);
2451         shared_ptr<InsetTableCell> inset = cellInset(cell);
2452         Paragraph const & par = inset->paragraphs().front();
2453         string const lang = par.getParLanguage(buffer().params())->lang();
2454
2455         //output the top line
2456         TeXTopHLine(os, row, lang);
2457
2458         if (row_info[row].top_space_default) {
2459                 if (use_booktabs)
2460                         os << "\\addlinespace\n";
2461                 else
2462                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2463         } else if(!row_info[row].top_space.zero()) {
2464                 if (use_booktabs)
2465                         os << "\\addlinespace["
2466                            << from_ascii(row_info[row].top_space.asLatexString())
2467                            << "]\n";
2468                 else {
2469                         os << "\\noalign{\\vskip"
2470                            << from_ascii(row_info[row].top_space.asLatexString())
2471                            << "}\n";
2472                 }
2473         }
2474         bool ismulticol = false;
2475         bool ismultirow = false;
2476         for (col_type c = 0; c < ncols(); ++c) {
2477                 if (isPartOfMultiColumn(row, c))
2478                         continue;
2479
2480                 cell = cellIndex(row, c);
2481
2482                 if (isPartOfMultiRow(row, c)
2483                     && column_info[c].alignment != LYX_ALIGN_DECIMAL) {
2484                         if (cell != getLastCellInRow(row))
2485                                 os << " & "; 
2486                         continue;
2487                 }
2488
2489                 TeXCellPreamble(os, cell, ismulticol, ismultirow);
2490                 shared_ptr<InsetTableCell> inset = cellInset(cell);
2491
2492                 Paragraph const & par = inset->paragraphs().front();
2493                 bool rtl = par.isRTL(buffer().params())
2494                         && !par.empty()
2495                         && getPWidth(cell).zero();
2496
2497                 if (rtl) {
2498                         string const lang =
2499                                 par.getParLanguage(buffer().params())->lang();
2500                         if (lang == "farsi")
2501                                 os << "\\textFR{";
2502                         else if (lang == "arabic_arabi")
2503                                 os << "\\textAR{";
2504                         // currently, remaining RTL languages are
2505                         // arabic_arabtex and hebrew
2506                         else
2507                                 os << "\\R{";
2508                 }
2509                 // pass to the OutputParams that we are in a cell and
2510                 // which alignment we have set.
2511                 // InsetNewline needs this context information.
2512                 OutputParams newrp(runparams);
2513                 newrp.inTableCell = (getAlignment(cell) == LYX_ALIGN_BLOCK)
2514                                     ? OutputParams::PLAIN
2515                                     : OutputParams::ALIGNED;
2516
2517                 if (getAlignment(cell) == LYX_ALIGN_DECIMAL) {
2518                         // copy cell and split in 2
2519                         InsetTableCell head = InsetTableCell(*cellInset(cell).get());
2520                         head.setBuffer(buffer());
2521                         DocIterator dit = cellInset(cell)->getText(0)->macrocontextPosition();
2522                         dit.pop_back();
2523                         dit.push_back(CursorSlice(head));
2524                         head.setMacrocontextPositionRecursive(dit);
2525                         bool hassep = false;
2526                         InsetTableCell tail = splitCell(head, column_info[c].decimal_point, hassep);
2527                         head.latex(os, newrp);
2528                         if (hassep) {
2529                                 os << '&';
2530                                 tail.setBuffer(head.buffer());
2531                                 dit.pop_back();
2532                                 dit.push_back(CursorSlice(tail));
2533                                 tail.setMacrocontextPositionRecursive(dit);
2534                                 tail.latex(os, newrp);
2535                         }
2536                 } else if (!isPartOfMultiRow(row, c)) {
2537                         if (!runparams.nice)
2538                                 os.texrow().start(par.id(), 0);
2539                         inset->latex(os, newrp);
2540                 }
2541
2542                 runparams.encoding = newrp.encoding;
2543                 if (rtl)
2544                         os << '}';
2545
2546                 TeXCellPostamble(os, cell, ismulticol, ismultirow);
2547                 if (cell != getLastCellInRow(row)) { // not last cell in row
2548                         if (runparams.nice)
2549                                 os << " & ";
2550                         else
2551                                 os << " &\n";
2552                 }
2553         }
2554         os << "\\tabularnewline";
2555         if (row_info[row].bottom_space_default) {
2556                 if (use_booktabs)
2557                         os << "\\addlinespace";
2558                 else
2559                         os << "[\\doublerulesep]";
2560         } else if (!row_info[row].bottom_space.zero()) {
2561                 if (use_booktabs)
2562                         os << "\\addlinespace";
2563                 os << '['
2564                    << from_ascii(row_info[row].bottom_space.asLatexString())
2565                    << ']';
2566         }
2567         os << '\n';
2568
2569         //output the bottom line
2570         TeXBottomHLine(os, row, lang);
2571
2572         if (row_info[row].interline_space_default) {
2573                 if (use_booktabs)
2574                         os << "\\addlinespace\n";
2575                 else
2576                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2577         } else if (!row_info[row].interline_space.zero()) {
2578                 if (use_booktabs)
2579                         os << "\\addlinespace["
2580                            << from_ascii(row_info[row].interline_space.asLatexString())
2581                            << "]\n";
2582                 else
2583                         os << "\\noalign{\\vskip"
2584                            << from_ascii(row_info[row].interline_space.asLatexString())
2585                            << "}\n";
2586         }
2587 }
2588
2589
2590 void Tabular::latex(otexstream & os, OutputParams const & runparams) const
2591 {
2592         bool const is_tabular_star = !tabular_width.zero();
2593
2594         //+---------------------------------------------------------------------
2595         //+                      first the opening preamble                    +
2596         //+---------------------------------------------------------------------
2597
2598         os << safebreakln;
2599         if (runparams.lastid != -1)
2600                 os.texrow().start(runparams.lastid, runparams.lastpos);
2601
2602         if (rotate != 0)
2603                 os << "\\begin{turn}{" << convert<string>(rotate) << "}\n";
2604
2605         if (is_long_tabular) {
2606                 os << "\\begin{longtable}";
2607                 switch (longtabular_alignment) {
2608                 case LYX_LONGTABULAR_ALIGN_LEFT:
2609                         os << "[l]";
2610                         break;
2611                 case LYX_LONGTABULAR_ALIGN_CENTER:
2612                         break;
2613                 case LYX_LONGTABULAR_ALIGN_RIGHT:
2614                         os << "[r]";
2615                         break;
2616                 }
2617         } else {
2618                 if (is_tabular_star)
2619                         os << "\\begin{tabular*}{" << from_ascii(tabular_width.asLatexString()) << "}";
2620                 else
2621                         os << "\\begin{tabular}";
2622                 switch (tabular_valignment) {
2623                 case LYX_VALIGN_TOP:
2624                         os << "[t]";
2625                         break;
2626                 case LYX_VALIGN_MIDDLE:
2627                         break;
2628                 case LYX_VALIGN_BOTTOM:
2629                         os << "[b]";
2630                         break;
2631                 }
2632         }
2633         
2634         os << "{";
2635
2636         if (is_tabular_star)
2637                 os << "@{\\extracolsep{\\fill}}";
2638
2639         for (col_type c = 0; c < ncols(); ++c) {
2640                 if (columnLeftLine(c))
2641                         os << '|';
2642                 if (!column_info[c].align_special.empty()) {
2643                         os << column_info[c].align_special;
2644                 } else {
2645                         if (!column_info[c].p_width.zero()) {
2646                                 switch (column_info[c].alignment) {
2647                                 case LYX_ALIGN_LEFT:
2648                                         os << ">{\\raggedright}";
2649                                         break;
2650                                 case LYX_ALIGN_RIGHT:
2651                                         os << ">{\\raggedleft}";
2652                                         break;
2653                                 case LYX_ALIGN_CENTER:
2654                                         os << ">{\\centering}";
2655                                         break;
2656                                 case LYX_ALIGN_NONE:
2657                                 case LYX_ALIGN_BLOCK:
2658                                 case LYX_ALIGN_LAYOUT:
2659                                 case LYX_ALIGN_SPECIAL:
2660                                 case LYX_ALIGN_DECIMAL:
2661                                         break;
2662                                 }
2663
2664                                 switch (column_info[c].valignment) {
2665                                 case LYX_VALIGN_TOP:
2666                                         os << 'p';
2667                                         break;
2668                                 case LYX_VALIGN_MIDDLE:
2669                                         os << 'm';
2670                                         break;
2671                                 case LYX_VALIGN_BOTTOM:
2672                                         os << 'b';
2673                                         break;
2674                         }
2675                                 os << '{'
2676                                    << from_ascii(column_info[c].p_width.asLatexString())
2677                                    << '}';
2678                         } else {
2679                                 switch (column_info[c].alignment) {
2680                                 case LYX_ALIGN_LEFT:
2681                                         os << 'l';
2682                                         break;
2683                                 case LYX_ALIGN_RIGHT:
2684                                         os << 'r';
2685                                         break;
2686                                 case LYX_ALIGN_DECIMAL:
2687                                         os << "r@{\\extracolsep{0pt}" << column_info[c].decimal_point << "}l";
2688                                         break;
2689                                 default:
2690                                         os << 'c';
2691                                         break;
2692                                 }
2693                         } // end if else !column_info[i].p_width
2694                 } // end if else !column_info[i].align_special
2695                 if (columnRightLine(c))
2696                         os << '|';
2697         }
2698         os << "}\n";
2699
2700         TeXLongtableHeaderFooter(os, runparams);
2701
2702         //+---------------------------------------------------------------------
2703         //+                      the single row and columns (cells)            +
2704         //+---------------------------------------------------------------------
2705
2706         for (row_type r = 0; r < nrows(); ++r) {
2707                 if (isValidRow(r)) {
2708                         TeXRow(os, r, runparams);
2709                         if (is_long_tabular && row_info[r].newpage)
2710                                 os << "\\newpage\n";
2711                 }
2712         }
2713
2714         //+---------------------------------------------------------------------
2715         //+                      the closing of the tabular                    +
2716         //+---------------------------------------------------------------------
2717
2718         if (is_long_tabular)
2719                 os << "\\end{longtable}";
2720         else {
2721                 if (is_tabular_star)
2722                         os << "\\end{tabular*}";
2723                 else
2724                         os << "\\end{tabular}";
2725         }
2726
2727         if (rotate != 0)
2728                 os << breakln << "\\end{turn}";
2729 }
2730
2731
2732 int Tabular::docbookRow(odocstream & os, row_type row,
2733                            OutputParams const & runparams) const
2734 {
2735         int ret = 0;
2736         idx_type cell = getFirstCellInRow(row);
2737
2738         os << "<row>\n";
2739         for (col_type c = 0; c < ncols(); ++c) {
2740                 if (isPartOfMultiColumn(row, c))
2741                         continue;
2742
2743                 os << "<entry align=\"";
2744                 switch (getAlignment(cell)) {
2745                 case LYX_ALIGN_LEFT:
2746                         os << "left";
2747                         break;
2748                 case LYX_ALIGN_RIGHT:
2749                         os << "right";
2750                         break;
2751                 default:
2752                         os << "center";
2753                         break;
2754                 }
2755
2756                 os << "\" valign=\"";
2757                 switch (getVAlignment(cell)) {
2758                 case LYX_VALIGN_TOP:
2759                         os << "top";
2760                         break;
2761                 case LYX_VALIGN_BOTTOM:
2762                         os << "bottom";
2763                         break;
2764                 case LYX_VALIGN_MIDDLE:
2765                         os << "middle";
2766                 }
2767                 os << '"';
2768
2769                 if (isMultiColumn(cell)) {
2770                         os << " namest=\"col" << c << "\" ";
2771                         os << "nameend=\"col" << c + columnSpan(cell) - 1 << '"';
2772                 }
2773
2774                 os << '>';
2775                 ret += cellInset(cell)->docbook(os, runparams);
2776                 os << "</entry>\n";
2777                 ++cell;
2778         }
2779         os << "</row>\n";
2780         return ret;
2781 }
2782
2783
2784 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
2785 {
2786         int ret = 0;
2787
2788         //+---------------------------------------------------------------------
2789         //+                      first the opening preamble                    +
2790         //+---------------------------------------------------------------------
2791
2792         os << "<tgroup cols=\"" << ncols()
2793            << "\" colsep=\"1\" rowsep=\"1\">\n";
2794
2795         for (col_type c = 0; c < ncols(); ++c) {
2796                 os << "<colspec colname=\"col" << c << "\" align=\"";
2797                 switch (column_info[c].alignment) {
2798                 case LYX_ALIGN_LEFT:
2799                         os << "left";
2800                         break;
2801                 case LYX_ALIGN_RIGHT:
2802                         os << "right";
2803                         break;
2804                 default:
2805                         os << "center";
2806                         break;
2807                 }
2808                 os << '"';
2809                 if (runparams.flavor == OutputParams::XML)
2810                         os << '/';
2811                 os << ">\n";
2812                 ++ret;
2813         }
2814
2815         //+---------------------------------------------------------------------
2816         //+                      Long Tabular case                             +
2817         //+---------------------------------------------------------------------
2818
2819         // output caption info
2820         // The caption flag wins over head/foot
2821         if (haveLTCaption()) {
2822                 os << "<caption>\n";
2823                 ++ret;
2824                 for (row_type r = 0; r < nrows(); ++r) {
2825                         if (row_info[r].caption) {
2826                                 ret += docbookRow(os, r, runparams);
2827                         }
2828                 }
2829                 os << "</caption>\n";
2830                 ++ret;
2831         }
2832         // output header info
2833         if (haveLTHead(false) || haveLTFirstHead(false)) {
2834                 os << "<thead>\n";
2835                 ++ret;
2836                 for (row_type r = 0; r < nrows(); ++r) {
2837                         if ((row_info[r].endhead || row_info[r].endfirsthead) &&
2838                             !row_info[r].caption) {
2839                                 ret += docbookRow(os, r, runparams);
2840                         }
2841                 }
2842                 os << "</thead>\n";
2843                 ++ret;
2844         }
2845         // output footer info
2846         if (haveLTFoot(false) || haveLTLastFoot(false)) {
2847                 os << "<tfoot>\n";
2848                 ++ret;
2849                 for (row_type r = 0; r < nrows(); ++r) {
2850                         if ((row_info[r].endfoot || row_info[r].endlastfoot) &&
2851                             !row_info[r].caption) {
2852                                 ret += docbookRow(os, r, runparams);
2853                         }
2854                 }
2855                 os << "</tfoot>\n";
2856                 ++ret;
2857         }
2858
2859         //+---------------------------------------------------------------------
2860         //+                      the single row and columns (cells)            +
2861         //+---------------------------------------------------------------------
2862
2863         os << "<tbody>\n";
2864         ++ret;
2865         for (row_type r = 0; r < nrows(); ++r) {
2866                 if (isValidRow(r)) {
2867                         ret += docbookRow(os, r, runparams);
2868                 }
2869         }
2870         os << "</tbody>\n";
2871         ++ret;
2872         //+---------------------------------------------------------------------
2873         //+                      the closing of the tabular                    +
2874         //+---------------------------------------------------------------------
2875
2876         os << "</tgroup>";
2877         ++ret;
2878
2879         return ret;
2880 }
2881
2882
2883 docstring Tabular::xhtmlRow(XHTMLStream & xs, row_type row,
2884                            OutputParams const & runparams, bool header) const
2885 {
2886         docstring ret;
2887         string const celltag = header ? "th" : "td";
2888         idx_type cell = getFirstCellInRow(row);
2889
2890         xs << html::StartTag("tr");
2891         for (col_type c = 0; c < ncols(); ++c) {
2892                 if (isPartOfMultiColumn(row, c) || isPartOfMultiRow(row, c))
2893                         continue;
2894
2895                 stringstream attr;
2896                 attr << "align='";
2897                 switch (getAlignment(cell)) {
2898                 case LYX_ALIGN_LEFT:
2899                         attr << "left";
2900                         break;
2901                 case LYX_ALIGN_RIGHT:
2902                         attr << "right";
2903                         break;
2904                 default:
2905                         attr << "center";
2906                         break;
2907                 }
2908                 attr << "'";
2909                 attr << " valign='";
2910                 switch (getVAlignment(cell)) {
2911                 case LYX_VALIGN_TOP:
2912                         attr << "top";
2913                         break;
2914                 case LYX_VALIGN_BOTTOM:
2915                         attr << "bottom";
2916                         break;
2917                 case LYX_VALIGN_MIDDLE:
2918                         attr << "middle";
2919                 }
2920                 attr << "'";
2921
2922                 if (isMultiColumn(cell))
2923                         attr << " colspan='" << columnSpan(cell) << "'";
2924                 else if (isMultiRow(cell))
2925                         attr << " rowspan='" << rowSpan(cell) << "'";
2926
2927                 xs << html::StartTag(celltag, attr.str()) << html::CR();
2928                 ret += cellInset(cell)->xhtml(xs, runparams);
2929                 xs << html::EndTag(celltag) << html::CR();
2930                 ++cell;
2931         }
2932         xs << html::EndTag("tr");
2933         return ret;
2934 }
2935
2936
2937 docstring Tabular::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
2938 {
2939         docstring ret;
2940
2941         if (is_long_tabular) {
2942                 // we'll wrap it in a div, so as to deal with alignment
2943                 string align;
2944                 switch (longtabular_alignment) {
2945                 case LYX_LONGTABULAR_ALIGN_LEFT:
2946                         align = "left";
2947                         break;
2948                 case LYX_LONGTABULAR_ALIGN_CENTER:
2949                         align = "center";
2950                         break;
2951                 case LYX_LONGTABULAR_ALIGN_RIGHT:
2952                         align = "right";
2953                         break;
2954                 }
2955                 xs << html::StartTag("div", "class='longtable' style='text-align: " + align + ";'")
2956                    << html::CR();
2957                 // The caption flag wins over head/foot
2958                 if (haveLTCaption()) {
2959                         xs << html::StartTag("div", "class='longtable-caption' style='text-align: " + align + ";'")
2960                            << html::CR();
2961                         for (row_type r = 0; r < nrows(); ++r)
2962                                 if (row_info[r].caption)
2963                                         ret += xhtmlRow(xs, r, runparams);
2964                         xs << html::EndTag("div") << html::CR();
2965                 }
2966         }
2967
2968         xs << html::StartTag("table") << html::CR();
2969
2970         // output header info
2971         bool const havefirsthead = haveLTFirstHead(false);
2972         // if we have a first head, then we are going to ignore the
2973         // headers for the additional pages, since there aren't any
2974         // in XHTML. this test accomplishes that.
2975         bool const havehead = !havefirsthead && haveLTHead(false);
2976         if (havehead || havefirsthead) {
2977                 xs << html::StartTag("thead") << html::CR();
2978                 for (row_type r = 0; r < nrows(); ++r) {
2979                         if (((havefirsthead && row_info[r].endfirsthead) ||
2980                              (havehead && row_info[r].endhead)) &&
2981                             !row_info[r].caption) {
2982                                 ret += xhtmlRow(xs, r, runparams, true);
2983                         }
2984                 }
2985                 xs << html::EndTag("thead") << html::CR();
2986         }
2987         // output footer info
2988         bool const havelastfoot = haveLTLastFoot(false);
2989         // as before.
2990         bool const havefoot = !havelastfoot && haveLTFoot(false);
2991         if (havefoot || havelastfoot) {
2992                 xs << html::StartTag("tfoot") << html::CR();
2993                 for (row_type r = 0; r < nrows(); ++r) {
2994                         if (((havelastfoot && row_info[r].endlastfoot) ||
2995                              (havefoot && row_info[r].endfoot)) &&
2996                             !row_info[r].caption) {
2997                                 ret += xhtmlRow(xs, r, runparams);
2998                         }
2999                 }
3000                 xs << html::EndTag("tfoot") << html::CR();
3001         }
3002
3003         xs << html::StartTag("tbody") << html::CR();
3004         for (row_type r = 0; r < nrows(); ++r) {
3005                 if (isValidRow(r)) {
3006                         ret += xhtmlRow(xs, r, runparams);
3007                 }
3008         }
3009         xs << html::EndTag("tbody")
3010            << html::CR()
3011            << html::EndTag("table")
3012            << html::CR();
3013         if (is_long_tabular)
3014                 xs << html::EndTag("div") << html::CR();
3015         return ret;
3016 }
3017
3018
3019 bool Tabular::plaintextTopHLine(odocstream & os, row_type row,
3020                                    vector<unsigned int> const & clen) const
3021 {
3022         idx_type const fcell = getFirstCellInRow(row);
3023         idx_type const n = numberOfCellsInRow(row) + fcell;
3024         idx_type tmp = 0;
3025
3026         for (idx_type i = fcell; i < n; ++i) {
3027                 if (topLine(i)) {
3028                         ++tmp;
3029                         break;
3030                 }
3031         }
3032         if (!tmp)
3033                 return false;
3034
3035         char_type ch;
3036         for (idx_type i = fcell; i < n; ++i) {
3037                 if (topLine(i)) {
3038                         if (leftLine(i))
3039                                 os << "+-";
3040                         else
3041                                 os << "--";
3042                         ch = '-';
3043                 } else {
3044                         os << "  ";
3045                         ch = ' ';
3046                 }
3047                 col_type column = cellColumn(i);
3048                 int len = clen[column];
3049                 while (column < ncols() - 1
3050                        && isPartOfMultiColumn(row, ++column))
3051                         len += clen[column] + 4;
3052                 os << docstring(len, ch);
3053                 if (topLine(i)) {
3054                         if (rightLine(i))
3055                                 os << "-+";
3056                         else
3057                                 os << "--";
3058                 } else {
3059                         os << "  ";
3060                 }
3061         }
3062         os << endl;
3063         return true;
3064 }
3065
3066
3067 bool Tabular::plaintextBottomHLine(odocstream & os, row_type row,
3068                                       vector<unsigned int> const & clen) const
3069 {
3070         idx_type const fcell = getFirstCellInRow(row);
3071         idx_type const n = numberOfCellsInRow(row) + fcell;
3072         idx_type tmp = 0;
3073
3074         for (idx_type i = fcell; i < n; ++i) {
3075                 if (bottomLine(i)) {
3076                         ++tmp;
3077                         break;
3078                 }
3079         }
3080         if (!tmp)
3081                 return false;
3082
3083         char_type ch;
3084         for (idx_type i = fcell; i < n; ++i) {
3085                 if (bottomLine(i)) {
3086                         if (leftLine(i))
3087                                 os << "+-";
3088                         else
3089                                 os << "--";
3090                         ch = '-';
3091                 } else {
3092                         os << "  ";
3093                         ch = ' ';
3094                 }
3095                 col_type column = cellColumn(i);
3096                 int len = clen[column];
3097                 while (column < ncols() - 1 && isPartOfMultiColumn(row, ++column))
3098                         len += clen[column] + 4;
3099                 os << docstring(len, ch);
3100                 if (bottomLine(i)) {
3101                         if (rightLine(i))
3102                                 os << "-+";
3103                         else
3104                                 os << "--";
3105                 } else {
3106                         os << "  ";
3107                 }
3108         }
3109         os << endl;
3110         return true;
3111 }
3112
3113
3114 void Tabular::plaintextPrintCell(odocstream & os,
3115                                OutputParams const & runparams,
3116                                idx_type cell, row_type row, col_type column,
3117                                vector<unsigned int> const & clen,
3118                                bool onlydata) const
3119 {
3120         odocstringstream sstr;
3121         cellInset(cell)->plaintext(sstr, runparams);
3122
3123         if (onlydata) {
3124                 os << sstr.str();
3125                 return;
3126         }
3127
3128         if (leftLine(cell))
3129                 os << "| ";
3130         else
3131                 os << "  ";
3132
3133         unsigned int len1 = sstr.str().length();
3134         unsigned int len2 = clen[column];
3135         while (column < ncols() - 1 && isPartOfMultiColumn(row, ++column))
3136                 len2 += clen[column] + 4;
3137         len2 -= len1;
3138
3139         switch (getAlignment(cell)) {
3140         default:
3141         case LYX_ALIGN_LEFT:
3142                 len1 = 0;
3143                 break;
3144         case LYX_ALIGN_RIGHT:
3145                 len1 = len2;
3146                 len2 = 0;
3147                 break;
3148         case LYX_ALIGN_CENTER:
3149                 len1 = len2 / 2;
3150                 len2 -= len1;
3151                 break;
3152         }
3153
3154         os << docstring(len1, ' ') << sstr.str()
3155            << docstring(len2, ' ');
3156
3157         if (rightLine(cell))
3158                 os << " |";
3159         else
3160                 os << "  ";
3161 }
3162
3163
3164 void Tabular::plaintext(odocstream & os,
3165                            OutputParams const & runparams, int const depth,
3166                            bool onlydata, char_type delim) const
3167 {
3168         // first calculate the width of the single columns
3169         vector<unsigned int> clen(ncols());
3170
3171         if (!onlydata) {
3172                 // first all non multicolumn cells!
3173                 for (col_type c = 0; c < ncols(); ++c) {
3174                         clen[c] = 0;
3175                         for (row_type r = 0; r < nrows(); ++r) {
3176                                 idx_type cell = cellIndex(r, c);
3177                                 if (isMultiColumn(cell))
3178                                         continue;
3179                                 odocstringstream sstr;
3180                                 cellInset(cell)->plaintext(sstr, runparams);
3181                                 if (clen[c] < sstr.str().length())
3182                                         clen[c] = sstr.str().length();
3183                         }
3184                 }
3185                 // then all multicolumn cells!
3186                 for (col_type c = 0; c < ncols(); ++c) {
3187                         for (row_type r = 0; r < nrows(); ++r) {
3188                                 idx_type cell = cellIndex(r, c);
3189                                 if (cell_info[r][c].multicolumn != CELL_BEGIN_OF_MULTICOLUMN)
3190                                         continue;
3191                                 odocstringstream sstr;
3192                                 cellInset(cell)->plaintext(sstr, runparams);
3193                                 int len = int(sstr.str().length());
3194                                 idx_type const n = columnSpan(cell);
3195                                 for (col_type k = c; len > 0 && k < c + n - 1; ++k)
3196                                         len -= clen[k];
3197                                 if (len > int(clen[c + n - 1]))
3198                                         clen[c + n - 1] = len;
3199                         }
3200                 }
3201         }
3202         idx_type cell = 0;
3203         for (row_type r = 0; r < nrows(); ++r) {
3204                 if (!onlydata && plaintextTopHLine(os, r, clen))
3205                         os << docstring(depth * 2, ' ');
3206                 for (col_type c = 0; c < ncols(); ++c) {
3207                         if (isPartOfMultiColumn(r, c) || isPartOfMultiRow(r,c))
3208                                 continue;
3209                         if (onlydata && c > 0)
3210                                 // we don't use operator<< for single UCS4 character.
3211                                 // see explanation in docstream.h
3212                                 os.put(delim);
3213                         plaintextPrintCell(os, runparams, cell, r, c, clen, onlydata);
3214                         ++cell;
3215                 }
3216                 os << endl;
3217                 if (!onlydata) {
3218                         os << docstring(depth * 2, ' ');
3219                         if (plaintextBottomHLine(os, r, clen))
3220                                 os << docstring(depth * 2, ' ');
3221                 }
3222         }
3223 }
3224
3225
3226 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell) const
3227 {
3228         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
3229 }
3230
3231
3232 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row,
3233                                                col_type column) const
3234 {
3235         return cell_info[row][column].inset;
3236 }
3237
3238
3239 void Tabular::setCellInset(row_type row, col_type column,
3240                               shared_ptr<InsetTableCell> ins) const
3241 {
3242         CellData & cd = cell_info[row][column];
3243         cd.inset = ins;
3244 }
3245
3246
3247 void Tabular::validate(LaTeXFeatures & features) const
3248 {
3249         features.require("NeedTabularnewline");
3250         if (use_booktabs)
3251                 features.require("booktabs");
3252         if (is_long_tabular)
3253                 features.require("longtable");
3254         if (needRotating())
3255                 features.require("rotating");
3256         for (idx_type cell = 0; cell < numberofcells; ++cell) {
3257                 if (isMultiRow(cell))
3258                         features.require("multirow");
3259                 if (getVAlignment(cell) != LYX_VALIGN_TOP
3260                     || !getPWidth(cell).zero())
3261                         features.require("array");
3262                 cellInset(cell)->validate(features);
3263         }
3264 }
3265
3266
3267 Tabular::BoxType Tabular::useParbox(idx_type cell) const
3268 {
3269         ParagraphList const & parlist = cellInset(cell)->paragraphs();
3270         ParagraphList::const_iterator cit = parlist.begin();
3271         ParagraphList::const_iterator end = parlist.end();
3272
3273         for (; cit != end; ++cit)
3274                 for (int i = 0; i < cit->size(); ++i)
3275                         if (cit->isNewline(i))
3276                                 return BOX_PARBOX;
3277
3278         return BOX_NONE;
3279 }
3280
3281
3282 /////////////////////////////////////////////////////////////////////
3283 //
3284 // InsetTableCell
3285 //
3286 /////////////////////////////////////////////////////////////////////
3287
3288 InsetTableCell::InsetTableCell(Buffer * buf)
3289         : InsetText(buf, InsetText::PlainLayout), isFixedWidth(false),
3290           contentAlign(LYX_ALIGN_CENTER)
3291 {}
3292
3293
3294 bool InsetTableCell::forcePlainLayout(idx_type) const
3295 {
3296         return !isFixedWidth;
3297 }
3298
3299
3300 bool InsetTableCell::allowParagraphCustomization(idx_type) const
3301 {
3302         return isFixedWidth;
3303 }
3304
3305
3306 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
3307         FuncStatus & status) const
3308 {
3309         bool enabled = true;
3310         switch (cmd.action()) {
3311         case LFUN_LAYOUT:
3312                 enabled = !forcePlainLayout();
3313                 break;
3314         case LFUN_LAYOUT_PARAGRAPH:
3315                 enabled = allowParagraphCustomization();
3316                 break;
3317
3318         case LFUN_MATH_DISPLAY:
3319                 if (!hasFixedWidth()) {
3320                         enabled = false;
3321                         break;
3322                 } //fall-through
3323         default:
3324                 return InsetText::getStatus(cur, cmd, status);
3325         }
3326         status.setEnabled(enabled);
3327         return true;
3328 }
3329
3330 docstring InsetTableCell::asString(bool intoInsets) 
3331 {
3332         docstring retval;
3333         if (paragraphs().empty())
3334                 return retval;
3335         ParagraphList::const_iterator it = paragraphs().begin();
3336         ParagraphList::const_iterator en = paragraphs().end();
3337         bool first = true;
3338         for (; it != en; ++it) {
3339                 if (!first)
3340                         retval += "\n";
3341                 else
3342                         first = false;
3343                 retval += it->asString(intoInsets ? AS_STR_INSETS : AS_STR_NONE);
3344         }
3345         return retval;
3346 }
3347
3348
3349 docstring InsetTableCell::xhtml(XHTMLStream & xs, OutputParams const & rp) const
3350 {
3351         if (!isFixedWidth)
3352                 return InsetText::insetAsXHTML(xs, rp, InsetText::JustText);
3353         return InsetText::xhtml(xs, rp);
3354 }
3355
3356
3357
3358 /////////////////////////////////////////////////////////////////////
3359 //
3360 // InsetTabular
3361 //
3362 /////////////////////////////////////////////////////////////////////
3363
3364 InsetTabular::InsetTabular(Buffer * buf, row_type rows,
3365                            col_type columns)
3366         : Inset(buf), tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))), scx_(0), 
3367         rowselect_(false), colselect_(false)
3368 {
3369 }
3370
3371
3372 InsetTabular::InsetTabular(InsetTabular const & tab)
3373         : Inset(tab), tabular(tab.tabular),  scx_(0)
3374 {
3375 }
3376
3377
3378 InsetTabular::~InsetTabular()
3379 {
3380         hideDialogs("tabular", this);
3381 }
3382
3383
3384 void InsetTabular::setBuffer(Buffer & buf)
3385 {
3386         tabular.setBuffer(buf);
3387         Inset::setBuffer(buf);
3388 }
3389
3390
3391 bool InsetTabular::insetAllowed(InsetCode code) const
3392 {
3393         switch (code) {
3394         case FLOAT_CODE:
3395         case MARGIN_CODE:
3396         case MATHMACRO_CODE:
3397         case WRAP_CODE:
3398                 return false;
3399
3400         case CAPTION_CODE:
3401                 return tabular.is_long_tabular;
3402
3403         default:
3404                 return true;
3405         }
3406 }
3407
3408
3409 void InsetTabular::write(ostream & os) const
3410 {
3411         os << "Tabular" << endl;
3412         tabular.write(os);
3413 }
3414
3415
3416 string InsetTabular::contextMenu(BufferView const &, int, int) const
3417 {
3418         // FIXME: depending on the selection state,
3419         // we could offer a different menu.
3420         return cell(0)->contextMenuName() + ";" + contextMenuName();
3421 }
3422
3423
3424 string InsetTabular::contextMenuName() const
3425 {
3426         return "context-tabular";
3427 }
3428
3429
3430 void InsetTabular::read(Lexer & lex)
3431 {
3432         //bool const old_format = (lex.getString() == "\\LyXTable");
3433
3434         tabular.read(lex);
3435
3436         //if (old_format)
3437         //      return;
3438
3439         lex.next();
3440         string token = lex.getString();
3441         while (lex && token != "\\end_inset") {
3442                 lex.next();
3443                 token = lex.getString();
3444         }
3445         if (!lex)
3446                 lex.printError("Missing \\end_inset at this point. ");
3447 }
3448
3449
3450 int InsetTabular::rowFromY(Cursor & cur, int y) const
3451 {
3452         // top y coordinate of tabular
3453         int h = yo(cur.bv()) - tabular.rowAscent(0) + offset_valign_;
3454         row_type r = 0;
3455         for (; r < tabular.nrows() && y > h; ++r)
3456                 h += tabular.rowAscent(r) + tabular.rowDescent(r)
3457                         + tabular.interRowSpace(r);
3458
3459         return r - 1;
3460 }
3461
3462
3463 int InsetTabular::columnFromX(Cursor & cur, int x) const
3464 {
3465         // left x coordinate of tabular
3466         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
3467         col_type c = 0;
3468         for (; c < tabular.ncols() && x > w; ++c)
3469                 w += tabular.cellWidth(c);
3470         return c - 1;
3471 }
3472
3473
3474 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
3475 {
3476         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
3477         //      mi.base.textwidth << "\n";
3478         if (!mi.base.bv) {
3479                 LYXERR0("need bv");
3480                 LASSERT(false, /**/);
3481         }
3482
3483         for (row_type r = 0; r < tabular.nrows(); ++r) {
3484                 int maxasc = 0;
3485                 int maxdes = 0;
3486                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3487                         if (tabular.isPartOfMultiColumn(r, c)
3488                                 || tabular.isPartOfMultiRow(r, c))
3489                                 // multicolumn or multirow cell, but not first one
3490                                 continue;
3491                         idx_type const cell = tabular.cellIndex(r, c);
3492                         Dimension dim;
3493                         MetricsInfo m = mi;
3494                         Length const p_width = tabular.getPWidth(cell);
3495                         if (!p_width.zero())
3496                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
3497                         tabular.cellInset(cell)->metrics(m, dim);
3498                         if (!p_width.zero())
3499                                 dim.wid = m.base.textwidth;
3500                         tabular.cellInfo(cell).width = dim.wid + 2 * WIDTH_OF_LINE 
3501                                 + tabular.interColumnSpace(cell);
3502
3503                         // FIXME(?): do we need a second metrics call?
3504                         TextMetrics const & tm = 
3505                                 mi.base.bv->textMetrics(tabular.cellInset(cell)->getText(0));
3506
3507                         // determine horizontal offset because of decimal align (if necessary)
3508                         int decimal_width = 0;
3509                         if (tabular.getAlignment(cell) == LYX_ALIGN_DECIMAL) {
3510                                 InsetTableCell tail = InsetTableCell(*tabular.cellInset(cell).get());
3511                                 tail.setBuffer(tabular.buffer());
3512                                 // we need to set macrocontext position everywhere
3513                                 // otherwise we crash with nested insets (e.g. footnotes)
3514                                 // after decimal point
3515                                 DocIterator dit = tabular.cellInset(cell)->getText(0)->macrocontextPosition();
3516                                 dit.pop_back();
3517                                 dit.push_back(CursorSlice(tail));
3518                                 tail.setMacrocontextPositionRecursive(dit);
3519
3520                                 // remove text leading decimal point
3521                                 docstring const align_d = tabular.column_info[c].decimal_point;
3522                                 dit = separatorPos(&tail, align_d);
3523
3524                                 pit_type const psize = tail.paragraphs().front().size();
3525                                 if (dit) {
3526                                         tail.paragraphs().front().eraseChars(0,
3527                                                 dit.pos() < psize ? dit.pos() + 1 : psize, false);
3528                                         Dimension dim1;
3529                                         tail.metrics(m, dim1);
3530                                         decimal_width = dim1.width();
3531                                 }
3532                         }
3533                         tabular.cell_info[r][c].decimal_hoffset = tm.width() - decimal_width;
3534                         tabular.cell_info[r][c].decimal_width = decimal_width;
3535
3536                         // with LYX_VALIGN_BOTTOM the descent is relative to the last par
3537                         // = descent of text in last par + TEXT_TO_INSET_OFFSET:
3538                         int const lastpardes = tm.last().second->descent()
3539                                 + TEXT_TO_INSET_OFFSET;
3540                         int offset = 0;
3541                         switch (tabular.getVAlignment(cell)) { 
3542                                 case Tabular::LYX_VALIGN_TOP:
3543                                         break; 
3544                                 case Tabular::LYX_VALIGN_MIDDLE:
3545                                         offset = -(dim.des - lastpardes)/2; 
3546                                         break; 
3547                                 case Tabular::LYX_VALIGN_BOTTOM:
3548                                         offset = -(dim.des - lastpardes); 
3549                                         break;
3550                         }
3551                         tabular.cell_info[r][c].voffset = offset;
3552                         maxasc = max(maxasc, dim.asc - offset);
3553                         maxdes = max(maxdes, dim.des + offset);
3554                 }
3555                 int const top_space = tabular.row_info[r].top_space_default ?
3556                         default_line_space :
3557                         tabular.row_info[r].top_space.inPixels(mi.base.textwidth);
3558                 tabular.setRowAscent(r, maxasc + ADD_TO_HEIGHT + top_space);
3559                 int const bottom_space = tabular.row_info[r].bottom_space_default ?
3560                         default_line_space :
3561                         tabular.row_info[r].bottom_space.inPixels(mi.base.textwidth);
3562                 tabular.setRowDescent(r, maxdes + ADD_TO_HEIGHT + bottom_space);
3563         }
3564
3565         // for top-alignment the first horizontal table line must be exactly at
3566         // the position of the base line of the surrounding text line
3567         // for bottom alignment, the same is for the last table line
3568         switch (tabular.tabular_valignment) {
3569         case Tabular::LYX_VALIGN_BOTTOM:
3570                 offset_valign_ = tabular.rowAscent(0) - tabular.height();
3571                 break;
3572         case Tabular::LYX_VALIGN_MIDDLE:
3573                 offset_valign_ = (- tabular.height()) / 2 + tabular.rowAscent(0);
3574                 break;
3575         case Tabular::LYX_VALIGN_TOP:
3576                 offset_valign_ = tabular.rowAscent(0);
3577                 break;
3578         }
3579
3580         tabular.updateColumnWidths();
3581         dim.asc = tabular.rowAscent(0) - offset_valign_;        
3582         dim.des = tabular.height() - dim.asc;
3583         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3584 }
3585
3586
3587 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col) 
3588         const
3589 {
3590         if (&cur.inset() == this && cur.selection()) {
3591                 if (cur.selIsMultiCell()) {
3592                         row_type rs, re;
3593                         col_type cs, ce;
3594                         getSelection(cur, rs, re, cs, ce);
3595                         
3596                         idx_type const cell = tabular.cellIndex(row, col);
3597                         col_type const cspan = tabular.columnSpan(cell);
3598                         row_type const rspan = tabular.rowSpan(cell);
3599                         if (col + cspan - 1 >= cs && col <= ce 
3600                                 && row + rspan - 1 >= rs && row <= re)
3601                                 return true;
3602                 } else 
3603                         if (col == tabular.cellColumn(cur.idx()) 
3604                                 && row == tabular.cellRow(cur.idx())) {
3605                         CursorSlice const & beg = cur.selBegin();
3606                         CursorSlice const & end = cur.selEnd();
3607
3608                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3609                                   && end.pos() == end.lastpos() && beg.pos() == 0
3610                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3611                                 return true;
3612                 }
3613         }
3614         return false;
3615 }
3616
3617
3618 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3619 {
3620         x += scx_ + ADD_TO_TABULAR_WIDTH;
3621
3622         BufferView * bv = pi.base.bv;
3623         Cursor & cur = pi.base.bv->cursor();
3624         resetPos(cur);
3625
3626         // FIXME: As the full background is painted in drawBackground(),
3627         // we have no choice but to do a full repaint for the Text cells.
3628         pi.full_repaint = true;
3629
3630         bool const original_selection_state = pi.selected;
3631
3632         idx_type idx = 0;
3633         first_visible_cell = Tabular::npos;
3634
3635         int yy = y + offset_valign_;
3636         for (row_type r = 0; r < tabular.nrows(); ++r) {
3637                 int nx = x;
3638                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3639                         if (tabular.isPartOfMultiColumn(r, c))
3640                                 continue;
3641                         
3642                         idx = tabular.cellIndex(r, c);
3643                         
3644                         if (tabular.isPartOfMultiRow(r, c)) {
3645                                 nx += tabular.cellWidth(idx);
3646                                 continue;
3647                         }
3648
3649                         if (first_visible_cell == Tabular::npos)
3650                                 first_visible_cell = idx;
3651
3652                         pi.selected |= isCellSelected(cur, r, c);
3653                         int const cx = nx + tabular.textHOffset(idx);
3654                         int const cy = yy + tabular.textVOffset(idx);
3655                         // Cache the Inset position.
3656                         bv->coordCache().insets().add(cell(idx).get(), cx, cy);
3657                         cell(idx)->draw(pi, cx, cy);
3658                         drawCellLines(pi, nx, yy, r, idx);
3659                         nx += tabular.cellWidth(idx);
3660                         pi.selected = original_selection_state;
3661                 }
3662
3663                 if (r + 1 < tabular.nrows())
3664                         yy += tabular.rowDescent(r) + tabular.rowAscent(r + 1) 
3665                                 + tabular.interRowSpace(r + 1);
3666         }
3667 }
3668
3669
3670 void InsetTabular::drawBackground(PainterInfo & pi, int x, int y) const
3671 {
3672         x += scx_ + ADD_TO_TABULAR_WIDTH;
3673         y += offset_valign_ - tabular.rowAscent(0);
3674         pi.pain.fillRectangle(x, y, tabular.width(), tabular.height(),
3675                 pi.backgroundColor(this));
3676 }
3677
3678
3679 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3680 {
3681         Cursor & cur = pi.base.bv->cursor();
3682         resetPos(cur);
3683
3684         x += scx_ + ADD_TO_TABULAR_WIDTH;
3685
3686         if (!cur.selection())
3687                 return;
3688         if (&cur.inset() != this)
3689                 return;
3690
3691         //resetPos(cur);
3692
3693         bool const full_cell_selected = isCellSelected(cur,
3694                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3695
3696         if (cur.selIsMultiCell() || full_cell_selected) {
3697                 for (row_type r = 0; r < tabular.nrows(); ++r) {
3698                         int xx = x;
3699                         for (col_type c = 0; c < tabular.ncols(); ++c) {
3700                                 if (tabular.isPartOfMultiColumn(r, c))
3701                                         continue;
3702
3703                                 idx_type const cell = tabular.cellIndex(r, c);
3704
3705                                 if (tabular.isPartOfMultiRow(r, c)) {
3706                                         xx += tabular.cellWidth(cell);
3707                                         continue;
3708                                 }
3709                                 int const w = tabular.cellWidth(cell);
3710                                 int const h = tabular.cellHeight(cell);
3711                                 int const yy = y - tabular.rowAscent(r) + offset_valign_;
3712                                 if (isCellSelected(cur, r, c))
3713                                         pi.pain.fillRectangle(xx, yy, w, h, Color_selection);
3714                                 xx += w;
3715                         }
3716                         if (r + 1 < tabular.nrows())
3717                                 y += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
3718                                      + tabular.interRowSpace(r + 1);
3719                 }
3720
3721         } 
3722         // FIXME: This code has no effect because InsetTableCell does not handle
3723         // drawSelection other than the trivial implementation in Inset.
3724         //else {
3725         //      x += cellXPos(cur.idx());
3726         //      x += tabular.textHOffset(cur.idx());
3727         //      cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3728         //}
3729 }
3730
3731
3732 void InsetTabular::drawCellLines(PainterInfo & pi, int x, int y,
3733                                  row_type row, idx_type cell) const
3734 {
3735         y -= tabular.rowAscent(row);
3736         int const w = tabular.cellWidth(cell);
3737         int const h = tabular.cellHeight(cell);
3738         Color const linecolor = pi.textColor(Color_tabularline);
3739         Color const gridcolor = pi.textColor(Color_tabularonoffline);
3740
3741         // Top
3742         bool drawline = tabular.topLine(cell)
3743                 || (row > 0 && tabular.bottomLine(tabular.cellAbove(cell)));
3744         pi.pain.line(x, y, x + w, y,
3745                 drawline ? linecolor : gridcolor,
3746                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3747
3748         // Bottom
3749         drawline = tabular.bottomLine(cell);
3750         pi.pain.line(x, y + h, x + w, y + h,
3751                 drawline ? linecolor : gridcolor,
3752                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3753
3754         // Left
3755         col_type const col = tabular.cellColumn(cell);
3756         drawline = tabular.leftLine(cell)
3757                 || (col > 0 && tabular.rightLine(tabular.cellIndex(row, col - 1)));
3758         pi.pain.line(x, y, x, y + h,
3759                 drawline ? linecolor : gridcolor,
3760                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3761
3762         // Right
3763         x -= tabular.interColumnSpace(cell);
3764         drawline = tabular.rightLine(cell)
3765                    || (col + 1 < tabular.ncols()
3766                        && tabular.leftLine(tabular.cellIndex(row, col + 1)));
3767         pi.pain.line(x + w, y, x + w, y + h,
3768                 drawline ? linecolor : gridcolor,
3769                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3770 }
3771
3772
3773 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3774 {
3775         //lyxerr << "InsetTabular::edit: " << this << endl;
3776         cur.finishUndo();
3777         cur.setSelection(false);
3778         cur.push(*this);
3779         if (front) {
3780                 if (isRightToLeft(cur))
3781                         cur.idx() = tabular.getLastCellInRow(0);
3782                 else
3783                         cur.idx() = 0;
3784                 cur.pit() = 0;
3785                 cur.pos() = 0;
3786         } else {
3787                 if (isRightToLeft(cur))
3788                         cur.idx() = tabular.getFirstCellInRow(tabular.nrows() - 1);
3789                 else
3790                         cur.idx() = tabular.numberofcells - 1;
3791                 cur.pit() = 0;
3792                 cur.pos() = cur.lastpos(); // FIXME crude guess
3793         }
3794         cur.setCurrentFont();
3795         // FIXME: this accesses the position cache before it is initialized
3796         //resetPos(cur);
3797         //cur.bv().fitCursor();
3798 }
3799
3800
3801 void InsetTabular::updateBuffer(ParIterator const & it, UpdateType utype)
3802 {
3803         // In a longtable, tell captions what the current float is
3804         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
3805         string const saveflt = cnts.current_float();
3806         if (tabular.is_long_tabular)
3807                 cnts.current_float("table");
3808
3809         ParIterator it2 = it;
3810         it2.forwardPos();
3811         size_t const end = it2.nargs();
3812         for ( ; it2.idx() < end; it2.top().forwardIdx())
3813                 buffer().updateBuffer(it2, utype);
3814
3815         //reset afterwards
3816         if (tabular.is_long_tabular)
3817                 cnts.current_float(saveflt);
3818 }
3819
3820
3821 void InsetTabular::addToToc(DocIterator const & cpit) const
3822 {
3823         DocIterator dit = cpit;
3824         dit.forwardPos();
3825         size_t const end = dit.nargs();
3826         for ( ; dit.idx() < end; dit.top().forwardIdx())
3827                 cell(dit.idx())->addToToc(dit);
3828 }
3829
3830
3831 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3832 {
3833         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3834                              << "\n  cur:" << cur);
3835         CursorSlice sl = cur.top();
3836         Cursor & bvcur = cur.bv().cursor();
3837
3838         FuncCode const act = cmd.action();
3839         
3840         switch (act) {
3841
3842         case LFUN_MOUSE_PRESS: {
3843                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3844                 // select row
3845                 if (cmd.x() < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3846                         || cmd.x() > xo(cur.bv()) + tabular.width()) {
3847                         row_type r = rowFromY(cur, cmd.y());
3848                         cur.idx() = tabular.getFirstCellInRow(r);
3849                         cur.pos() = 0;
3850                         cur.resetAnchor();
3851                         cur.idx() = tabular.getLastCellInRow(r);
3852                         cur.pos() = cur.lastpos();
3853                         cur.setSelection(true);
3854                         bvcur = cur; 
3855                         rowselect_ = true;
3856                         break;
3857                 }
3858                 // select column
3859                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0) + offset_valign_;
3860                 if (cmd.y() < y0 + ADD_TO_TABULAR_WIDTH 
3861                         || cmd.y() > y0 + tabular.height()) {
3862                         col_type c = columnFromX(cur, cmd.x());
3863                         cur.idx() = tabular.cellIndex(0, c);
3864                         cur.pos() = 0;
3865                         cur.resetAnchor();
3866                         cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
3867                         cur.pos() = cur.lastpos();
3868                         cur.setSelection(true);
3869                         bvcur = cur; 
3870                         colselect_ = true;
3871                         break;
3872                 }
3873                 // do not reset cursor/selection if we have selected
3874                 // some cells (bug 2715).
3875                 if (cmd.button() == mouse_button::button3
3876                     && &bvcur.selBegin().inset() == this 
3877                     && bvcur.selIsMultiCell()) 
3878                         ;
3879                 else
3880                         // Let InsetTableCell do it
3881                         cell(cur.idx())->dispatch(cur, cmd);
3882                 break;
3883         }
3884         case LFUN_MOUSE_MOTION:
3885                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3886                 if (cmd.button() == mouse_button::button1) {
3887                         // only accept motions to places not deeper nested than the real anchor
3888                         if (!bvcur.realAnchor().hasPart(cur)) {
3889                                 cur.undispatched();
3890                                 break;
3891                         }
3892                         // select (additional) row
3893                         if (rowselect_) {
3894                                 row_type r = rowFromY(cur, cmd.y());
3895                                 cur.idx() = tabular.getLastCellInRow(r);
3896                                 // we need to reset the cursor's pit and pos now, as the old ones
3897                                 // may no longer be valid.
3898                                 cur.pit() = 0;
3899                                 cur.pos() = 0;
3900                                 bvcur.setCursor(cur);
3901                                 bvcur.setSelection(true);
3902                                 break;
3903                         }
3904                         // select (additional) column
3905                         if (colselect_) {
3906                                 col_type c = columnFromX(cur, cmd.x());
3907                                 cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
3908                                 // we need to reset the cursor's pit and pos now, as the old ones
3909                                 // may no longer be valid.
3910                                 cur.pit() = 0;
3911                                 cur.pos() = 0;
3912                                 bvcur.setCursor(cur);
3913                                 bvcur.setSelection(true);
3914                                 break;
3915                         }
3916                         // only update if selection changes
3917                         if (bvcur.idx() == cur.idx() &&
3918                                 !(bvcur.realAnchor().idx() == cur.idx() && bvcur.pos() != cur.pos()))
3919                                 cur.noScreenUpdate();
3920                         setCursorFromCoordinates(cur, cmd.x(), cmd.y());
3921                         bvcur.setCursor(cur);
3922                         bvcur.setSelection(true);
3923                         // if this is a multicell selection, we just set the cursor to
3924                         // the beginning of the cell's text.
3925                         if (bvcur.selIsMultiCell()) {
3926                                 bvcur.pit() = bvcur.lastpit();
3927                                 bvcur.pos() = bvcur.lastpos();
3928                         }
3929                 }
3930                 break;
3931
3932         case LFUN_MOUSE_RELEASE:
3933                 rowselect_ = false;
3934                 colselect_ = false;
3935                 break;
3936
3937         case LFUN_CELL_BACKWARD:
3938                 movePrevCell(cur);
3939                 cur.setSelection(false);
3940                 break;
3941
3942         case LFUN_CELL_FORWARD:
3943                 moveNextCell(cur);
3944                 cur.setSelection(false);
3945                 break;
3946
3947         case LFUN_CHAR_FORWARD_SELECT:
3948         case LFUN_CHAR_FORWARD:
3949         case LFUN_CHAR_BACKWARD_SELECT:
3950         case LFUN_CHAR_BACKWARD:
3951         case LFUN_CHAR_RIGHT_SELECT:
3952         case LFUN_CHAR_RIGHT:
3953         case LFUN_CHAR_LEFT_SELECT:
3954         case LFUN_CHAR_LEFT: 
3955         case LFUN_WORD_FORWARD:
3956         case LFUN_WORD_FORWARD_SELECT:
3957         case LFUN_WORD_BACKWARD:
3958         case LFUN_WORD_BACKWARD_SELECT:
3959         case LFUN_WORD_RIGHT:
3960         case LFUN_WORD_RIGHT_SELECT:
3961         case LFUN_WORD_LEFT:
3962         case LFUN_WORD_LEFT_SELECT: {
3963                 // determine whether we move to next or previous cell, where to enter 
3964                 // the new cell from, and which command to "finish" (i.e., exit the
3965                 // inset) with:
3966                 bool next_cell;
3967                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
3968                 FuncCode finish_lfun;
3969
3970                 if (act == LFUN_CHAR_FORWARD 
3971                                 || act == LFUN_CHAR_FORWARD_SELECT
3972                                 || act == LFUN_WORD_FORWARD
3973                                 || act == LFUN_WORD_FORWARD_SELECT) {
3974                         next_cell = true;
3975                         finish_lfun = LFUN_FINISHED_FORWARD;
3976                 }
3977                 else if (act == LFUN_CHAR_BACKWARD
3978                                 || act == LFUN_CHAR_BACKWARD_SELECT
3979                                 || act == LFUN_WORD_BACKWARD
3980                                 || act == LFUN_WORD_BACKWARD_SELECT) {
3981                         next_cell = false;
3982                         finish_lfun = LFUN_FINISHED_BACKWARD;
3983                 }
3984                 // LEFT or RIGHT commands --- the interpretation will depend on the 
3985                 // table's direction.
3986                 else {
3987                         bool const right = act == LFUN_CHAR_RIGHT
3988                                 || act == LFUN_CHAR_RIGHT_SELECT
3989                                 || act == LFUN_WORD_RIGHT
3990                                 || act == LFUN_WORD_RIGHT_SELECT;
3991                         next_cell = isRightToLeft(cur) != right;
3992                         
3993                         if (lyxrc.visual_cursor)
3994                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
3995
3996                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
3997                 }
3998
3999                 bool const select =     act == LFUN_CHAR_FORWARD_SELECT 
4000                     || act == LFUN_CHAR_BACKWARD_SELECT
4001                     || act == LFUN_CHAR_RIGHT_SELECT
4002                     || act == LFUN_CHAR_LEFT_SELECT
4003                         || act == LFUN_WORD_FORWARD_SELECT
4004                         || act == LFUN_WORD_RIGHT_SELECT
4005                         || act == LFUN_WORD_BACKWARD_SELECT
4006                         || act == LFUN_WORD_LEFT_SELECT;
4007
4008                 // If we have a multicell selection or we're 
4009                 // not doing some LFUN_*_SELECT thing anyway...
4010                 if (!cur.selIsMultiCell() || !select) {
4011                         col_type const c = tabular.cellColumn(cur.idx());
4012                         row_type const r = tabular.cellRow(cur.idx());
4013                         // Are we trying to select the whole cell and is the whole cell 
4014                         // not yet selected?
4015                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
4016                                 ((next_cell && cur.pit() == cur.lastpit() 
4017                                 && cur.pos() == cur.lastpos())
4018                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
4019
4020                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
4021
4022                         // ...try to dispatch to the cell's inset.
4023                         cell(cur.idx())->dispatch(cur, cmd);
4024
4025                         // When we already have a selection we want to select the whole cell
4026                         // before going to the next cell.
4027                         if (select_whole && !empty_cell){
4028                                 getText(cur.idx())->selectAll(cur);
4029                                 cur.dispatched();
4030                                 break;
4031                         }
4032
4033                         // FIXME: When we support the selection of an empty cell, remove 
4034                         // the !empty_cell from this condition. For now we jump to the next
4035                         // cell if the current cell is empty.
4036                         if (cur.result().dispatched() && !empty_cell)
4037                                 break;
4038                 }
4039
4040                 // move to next/prev cell, as appropriate
4041                 // note that we will always do this if we're selecting and we have
4042                 // a multicell selection
4043                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
4044                         << " cell from: " << int(entry_from));
4045                 if (next_cell)
4046                         moveNextCell(cur, entry_from);
4047                 else
4048                         movePrevCell(cur, entry_from);
4049                 // if we're exiting the table, call the appropriate FINISHED lfun
4050                 if (sl == cur.top())
4051                         cmd = FuncRequest(finish_lfun);
4052                 else
4053                         cur.dispatched();
4054
4055                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4056                 break;
4057
4058         }
4059
4060         case LFUN_DOWN_SELECT:
4061         case LFUN_DOWN:
4062                 if (!(cur.selection() && cur.selIsMultiCell()))
4063                         cell(cur.idx())->dispatch(cur, cmd);
4064                 
4065                 cur.dispatched(); // override the cell's decision
4066                 if (sl == cur.top()) {
4067                         // if our Text didn't do anything to the cursor
4068                         // then we try to put the cursor into the cell below
4069                         // setting also the right targetX.
4070                         cur.selHandle(act == LFUN_DOWN_SELECT);
4071                         if (tabular.cellRow(cur.idx()) != tabular.nrows() - 1) {
4072                                 int const xtarget = cur.targetX();
4073                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4074                                 // an inconsistent state until pos() has been set. Be careful
4075                                 // what you do with it!
4076                                 cur.idx() = tabular.cellBelow(cur.idx());
4077                                 cur.pit() = 0;
4078                                 TextMetrics const & tm =
4079                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
4080                                 cur.pos() = tm.x2pos(cur.pit(), 0, xtarget);
4081                                 cur.setCurrentFont();
4082                         }
4083                 }
4084                 if (sl == cur.top()) {
4085                         // we trick it to go to forward after leaving the
4086                         // tabular.
4087                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
4088                         cur.undispatched();
4089                 }
4090                 if (cur.selIsMultiCell()) {
4091                         cur.pit() = cur.lastpit();
4092                         cur.pos() = cur.lastpos();
4093                         cur.setCurrentFont();
4094                         return;
4095                 }
4096                 cur.screenUpdateFlags(Update::FitCursor);
4097                 break;
4098
4099         case LFUN_UP_SELECT:
4100         case LFUN_UP:
4101                 if (!(cur.selection() && cur.selIsMultiCell()))
4102                         cell(cur.idx())->dispatch(cur, cmd);
4103                 cur.dispatched(); // override the cell's decision
4104                 if (sl == cur.top()) {
4105                         // if our Text didn't do anything to the cursor
4106                         // then we try to put the cursor into the cell above
4107                         // setting also the right targetX.
4108                         cur.selHandle(act == LFUN_UP_SELECT);
4109                         if (tabular.cellRow(cur.idx()) != 0) {
4110                                 int const xtarget = cur.targetX();
4111                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4112                                 // an inconsistent state until pos() has been set. Be careful
4113                                 // what you do with it!
4114                                 cur.idx() = tabular.cellAbove(cur.idx());
4115                                 cur.pit() = cur.lastpit();
4116                                 Text const * text = cell(cur.idx())->getText(0);
4117                                 TextMetrics const & tm = cur.bv().textMetrics(text);
4118                                 ParagraphMetrics const & pm =
4119                                         tm.parMetrics(cur.lastpit());
4120                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, xtarget);
4121                                 cur.setCurrentFont();
4122                         }
4123                 }
4124                 if (sl == cur.top()) {
4125                         cmd = FuncRequest(LFUN_UP);
4126                         cur.undispatched();
4127                 }
4128                 if (cur.selIsMultiCell()) {
4129                         cur.pit() = 0;
4130                         cur.pos() = cur.lastpos();
4131                         cur.setCurrentFont();
4132                         return;
4133                 }
4134                 cur.screenUpdateFlags(Update::FitCursor);
4135                 break;
4136
4137 //      case LFUN_SCREEN_DOWN: {
4138 //              //if (hasSelection())
4139 //              //      cur.selection() = false;
4140 //              col_type const col = tabular.cellColumn(cur.idx());
4141 //              int const t =   cur.bv().top_y() + cur.bv().height();
4142 //              if (t < yo() + tabular.getHeightOfTabular()) {
4143 //                      cur.bv().scrollDocView(t, true);
4144 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
4145 //              } else {
4146 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
4147 //              }
4148 //              cur.par() = 0;
4149 //              cur.pos() = 0;
4150 //              break;
4151 //      }
4152 //
4153 //      case LFUN_SCREEN_UP: {
4154 //              //if (hasSelection())
4155 //              //      cur.selection() = false;
4156 //              col_type const col = tabular.cellColumn(cur.idx());
4157 //              int const t =   cur.bv().top_y() + cur.bv().height();
4158 //              if (yo() < 0) {
4159 //                      cur.bv().scrollDocView(t, true);
4160 //                      if (yo() > 0)
4161 //                              cur.idx() = col;
4162 //                      else
4163 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
4164 //              } else {
4165 //                      cur.idx() = col;
4166 //              }
4167 //              cur.par() = cur.lastpar();
4168 //              cur.pos() = cur.lastpos();
4169 //              break;
4170 //      }
4171
4172         case LFUN_LAYOUT_TABULAR:
4173                 cur.bv().showDialog("tabular");
4174                 break;
4175
4176         case LFUN_INSET_MODIFY: {
4177                 string arg;
4178                 if (cmd.getArg(1) == "from-dialog")
4179                         arg = cmd.getArg(0) + to_utf8(cmd.argument().substr(19));
4180                 else
4181                         arg = to_utf8(cmd.argument());
4182                 if (!tabularFeatures(cur, arg))
4183                         cur.undispatched();
4184                 break;
4185         }
4186
4187         // insert file functions
4188         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
4189         case LFUN_FILE_INSERT_PLAINTEXT:
4190                 // FIXME UNICODE
4191                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
4192                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
4193                                 FileName(to_utf8(cmd.argument())));
4194                         if (tmpstr.empty())
4195                                 break;
4196                         cur.recordUndoInset(INSERT_UNDO);
4197                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
4198                                 // content has been replaced,
4199                                 // so cursor might be invalid
4200                                 cur.pos() = cur.lastpos();
4201                                 cur.pit() = cur.lastpit();
4202                                 bvcur.setCursor(cur);
4203                         } else
4204                                 cur.undispatched();
4205                 }
4206                 break;
4207
4208         case LFUN_CUT:
4209                 if (cur.selIsMultiCell()) {
4210                         if (copySelection(cur)) {
4211                                 cur.recordUndoInset(DELETE_UNDO);
4212                                 cutSelection(cur);
4213                         }
4214                 } else
4215                         cell(cur.idx())->dispatch(cur, cmd);
4216                 break;
4217
4218         case LFUN_SELF_INSERT:
4219                 if (cur.selIsMultiCell()) {
4220                         cur.recordUndoInset(DELETE_UNDO);
4221                         cutSelection(cur);
4222                 }
4223                 cell(cur.idx())->dispatch(cur, cmd);
4224                 break;
4225
4226         case LFUN_CHAR_DELETE_BACKWARD:
4227         case LFUN_CHAR_DELETE_FORWARD:
4228                 if (cur.selIsMultiCell()) {
4229                         cur.recordUndoInset(DELETE_UNDO);
4230                         cutSelection(cur);
4231                 } else
4232                         cell(cur.idx())->dispatch(cur, cmd);
4233                 break;
4234
4235         case LFUN_COPY:
4236                 if (!cur.selection())
4237                         break;
4238                 if (cur.selIsMultiCell()) {
4239                         cur.finishUndo();
4240                         copySelection(cur);
4241                 } else
4242                         cell(cur.idx())->dispatch(cur, cmd);
4243                 break;
4244
4245         case LFUN_CLIPBOARD_PASTE:
4246         case LFUN_PRIMARY_SELECTION_PASTE: {
4247                 docstring const clip = (act == LFUN_CLIPBOARD_PASTE) ?
4248                         theClipboard().getAsText() :
4249                         theSelection().get();
4250                 if (clip.empty())
4251                         break;
4252                 // pass to InsertPlaintextString, but
4253                 // only if we have multi-cell content
4254                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
4255                         cur.recordUndoInset(INSERT_UNDO);
4256                         if (insertPlaintextString(cur.bv(), clip, false)) {
4257                                 // content has been replaced,
4258                                 // so cursor might be invalid
4259                                 cur.pos() = cur.lastpos();
4260                                 cur.pit() = cur.lastpit();
4261                                 bvcur.setCursor(cur);
4262                                 break;
4263                         }
4264                 }
4265                 // Let the cell handle normal text
4266                 cell(cur.idx())->dispatch(cur, cmd);
4267                 break;
4268         }
4269
4270         case LFUN_PASTE:
4271                 if (!tabularStackDirty()) {
4272                         if (!cur.selIsMultiCell())
4273                                 cell(cur.idx())->dispatch(cur, cmd);
4274                         break;
4275                 }
4276                 if (theClipboard().isInternal()) {
4277                         cur.recordUndoInset(INSERT_UNDO);
4278                         pasteClipboard(cur);
4279                 }
4280                 break;
4281
4282         case LFUN_FONT_EMPH:
4283         case LFUN_FONT_BOLD:
4284         case LFUN_FONT_BOLDSYMBOL:
4285         case LFUN_FONT_ROMAN:
4286         case LFUN_FONT_NOUN:
4287         case LFUN_FONT_ITAL:
4288         case LFUN_FONT_FRAK:
4289         case LFUN_FONT_TYPEWRITER:
4290         case LFUN_FONT_SANS:
4291         case LFUN_TEXTSTYLE_APPLY:
4292         case LFUN_TEXTSTYLE_UPDATE:
4293         case LFUN_FONT_SIZE:
4294         case LFUN_FONT_UNDERLINE:
4295         case LFUN_FONT_STRIKEOUT:
4296         case LFUN_FONT_UULINE:
4297         case LFUN_FONT_UWAVE:
4298         case LFUN_LANGUAGE:
4299         case LFUN_WORD_CAPITALIZE:
4300         case LFUN_WORD_UPCASE:
4301         case LFUN_WORD_LOWCASE:
4302         case LFUN_CHARS_TRANSPOSE:
4303                 if (cur.selIsMultiCell()) {
4304                         row_type rs, re;
4305                         col_type cs, ce;
4306                         getSelection(cur, rs, re, cs, ce);
4307                         Cursor tmpcur = cur;
4308                         for (row_type r = rs; r <= re; ++r) {
4309                                 for (col_type c = cs; c <= ce; ++c) {
4310                                         // cursor follows cell:
4311                                         tmpcur.idx() = tabular.cellIndex(r, c);
4312                                         // select this cell only:
4313                                         tmpcur.pit() = 0;
4314                                         tmpcur.pos() = 0;
4315                                         tmpcur.resetAnchor();
4316                                         tmpcur.pit() = tmpcur.lastpit();
4317                                         tmpcur.pos() = tmpcur.top().lastpos();
4318                                         tmpcur.setCursor(tmpcur);
4319                                         tmpcur.setSelection();
4320                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
4321                                 }
4322                         }
4323                         break;
4324                 } else {
4325                         cell(cur.idx())->dispatch(cur, cmd);
4326                         break;
4327                 }
4328
4329         case LFUN_INSET_SETTINGS:
4330                 // relay this lfun to Inset, not to the cell.
4331                 Inset::doDispatch(cur, cmd);
4332                 break;
4333
4334         default:
4335                 // we try to handle this event in the insets dispatch function.
4336                 cell(cur.idx())->dispatch(cur, cmd);
4337                 break;
4338         }
4339 }
4340
4341
4342 // function sets an object as defined in func_status.h:
4343 // states OK, Unknown, Disabled, On, Off.
4344 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
4345         FuncStatus & status) const
4346 {
4347         switch (cmd.action()) {
4348         case LFUN_INSET_MODIFY: {
4349                 if (&cur.inset() != this || cmd.getArg(0) != "tabular") 
4350                         break;
4351
4352                 // FIXME: We only check for the very first argument...
4353                 string const s = cmd.getArg(1);
4354                 // We always enable the lfun if it is coming from the dialog
4355                 // because the dialog makes sure all the settings are valid,
4356                 // even though the first argument might not be valid now.
4357                 if (s == "from-dialog") {
4358                         status.setEnabled(true);
4359                         return true;
4360                 }
4361
4362                 int action = Tabular::LAST_ACTION;
4363                 int i = 0;
4364                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4365                         if (tabularFeature[i].feature == s) {
4366                                 action = tabularFeature[i].action;
4367                                 break;
4368                         }
4369                 }
4370                 if (action == Tabular::LAST_ACTION) {
4371                         status.clear();
4372                         status.setUnknown(true);
4373                         return true;
4374                 }
4375
4376                 string const argument = cmd.getLongArg(2);
4377
4378                 row_type sel_row_start = 0;
4379                 row_type sel_row_end = 0;
4380                 col_type sel_col_start = 0;
4381                 col_type sel_col_end = 0;
4382                 Tabular::ltType dummyltt;
4383                 bool flag = true;
4384
4385                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4386
4387                 switch (action) {
4388                 case Tabular::SET_PWIDTH:
4389                 case Tabular::SET_MPWIDTH:
4390                 case Tabular::SET_SPECIAL_COLUMN:
4391                 case Tabular::SET_SPECIAL_MULTICOLUMN:
4392                 case Tabular::APPEND_ROW:
4393                 case Tabular::APPEND_COLUMN:
4394                 case Tabular::DELETE_ROW:
4395                 case Tabular::DELETE_COLUMN:
4396                 case Tabular::COPY_ROW:
4397                 case Tabular::COPY_COLUMN:
4398                 case Tabular::SET_TOP_SPACE:
4399                 case Tabular::SET_BOTTOM_SPACE:
4400                 case Tabular::SET_INTERLINE_SPACE:
4401                         status.clear();
4402                         return true;
4403
4404                 case Tabular::SET_TABULAR_WIDTH:
4405                         status.setEnabled(!tabular.rotate &&  !tabular.is_long_tabular
4406                                 && tabular.tabular_valignment == Tabular::LYX_VALIGN_MIDDLE);
4407                         break;
4408
4409                 case Tabular::SET_DECIMAL_POINT:
4410                         status.setEnabled(
4411                                 tabular.getAlignment(cur.idx()) == LYX_ALIGN_DECIMAL);
4412                         break;
4413
4414                 case Tabular::SET_MULTICOLUMN:
4415                 case Tabular::UNSET_MULTICOLUMN:
4416                 case Tabular::MULTICOLUMN:
4417                         // If a row is set as longtable caption, it must not be allowed
4418                         // to unset that this row is a multicolumn.
4419                         status.setEnabled(sel_row_start == sel_row_end
4420                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4421                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
4422                         break;
4423
4424                 case Tabular::SET_MULTIROW:
4425                 case Tabular::UNSET_MULTIROW:
4426                 case Tabular::MULTIROW:
4427                         // If a row is set as longtable caption, it must not be allowed
4428                         // to unset that this row is a multirow.
4429                         status.setEnabled(sel_col_start == sel_col_end
4430                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4431                         status.setOnOff(tabular.isMultiRow(cur.idx()));
4432                         break;
4433
4434                 case Tabular::SET_ALL_LINES:
4435                 case Tabular::UNSET_ALL_LINES:
4436                 case Tabular::SET_BORDER_LINES:
4437                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4438                         break;
4439
4440                 case Tabular::SET_LINE_TOP:
4441                 case Tabular::SET_LINE_BOTTOM:
4442                 case Tabular::SET_LINE_LEFT:
4443                 case Tabular::SET_LINE_RIGHT:
4444                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4445                         break;
4446
4447                 case Tabular::TOGGLE_LINE_TOP:
4448                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4449                         status.setOnOff(tabular.topLine(cur.idx()));
4450                         break;
4451
4452                 case Tabular::TOGGLE_LINE_BOTTOM:
4453                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4454                         status.setOnOff(tabular.bottomLine(cur.idx()));
4455                         break;
4456
4457                 case Tabular::TOGGLE_LINE_LEFT:
4458                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4459                         status.setOnOff(tabular.leftLine(cur.idx()));
4460                         break;
4461
4462                 case Tabular::TOGGLE_LINE_RIGHT:
4463                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4464                         status.setOnOff(tabular.rightLine(cur.idx()));
4465                         break;
4466
4467                 // multirow cells only inherit the alignment of the column if the column has
4468                 // no width, otherwise they are left-aligned
4469                 // therefore allow always left but right and center only if there is no width
4470                 case Tabular::M_ALIGN_LEFT:
4471                         flag = false;
4472                 case Tabular::ALIGN_LEFT:
4473                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
4474                         break;
4475
4476                 case Tabular::M_ALIGN_RIGHT:
4477                         flag = false;
4478                 case Tabular::ALIGN_RIGHT:
4479                         status.setEnabled(!(tabular.isMultiRow(cur.idx()) 
4480                                 && !tabular.getPWidth(cur.idx()).zero()));
4481                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
4482                         break;
4483
4484                 case Tabular::M_ALIGN_CENTER:
4485                         flag = false;
4486                 case Tabular::ALIGN_CENTER:
4487                         status.setEnabled(!(tabular.isMultiRow(cur.idx()) 
4488                                 && !tabular.getPWidth(cur.idx()).zero()));
4489                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
4490                         break;
4491
4492                 case Tabular::ALIGN_BLOCK:
4493                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4494                                 && !tabular.isMultiRow(cur.idx()));
4495                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
4496                         break;
4497
4498                 case Tabular::ALIGN_DECIMAL:
4499                         status.setEnabled(!tabular.isMultiRow(cur.idx()) 
4500                                 && !tabular.isMultiColumn(cur.idx()));
4501                         status.setOnOff(tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_DECIMAL);
4502                         break;
4503
4504                 case Tabular::M_VALIGN_TOP:
4505                         flag = false;
4506                 case Tabular::VALIGN_TOP:
4507                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4508                                 && !tabular.isMultiRow(cur.idx()));
4509                         status.setOnOff(
4510                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
4511                         break;
4512
4513                 case Tabular::M_VALIGN_BOTTOM:
4514                         flag = false;
4515                 case Tabular::VALIGN_BOTTOM:
4516                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4517                                 && !tabular.isMultiRow(cur.idx()));
4518                         status.setOnOff(
4519                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
4520                         break;
4521
4522                 case Tabular::M_VALIGN_MIDDLE:
4523                         flag = false;
4524                 case Tabular::VALIGN_MIDDLE:
4525                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4526                                 && !tabular.isMultiRow(cur.idx()));
4527                         status.setOnOff(
4528                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
4529                         break;
4530
4531                 case Tabular::SET_LONGTABULAR:
4532                         // setting as longtable is not allowed when table is inside a float
4533                         if (cur.innerInsetOfType(FLOAT_CODE) != 0
4534                                 || cur.innerInsetOfType(WRAP_CODE) != 0)
4535                                 status.setEnabled(false);
4536                         else
4537                                 status.setEnabled(true);
4538                         status.setOnOff(tabular.is_long_tabular);
4539                         break;
4540
4541                 case Tabular::UNSET_LONGTABULAR:
4542                         status.setOnOff(!tabular.is_long_tabular);
4543                         break;
4544
4545                 case Tabular::TOGGLE_ROTATE_TABULAR:
4546                 case Tabular::SET_ROTATE_TABULAR:
4547                         status.setOnOff(tabular.rotate != 0);
4548                         break;
4549
4550                 case Tabular::TABULAR_VALIGN_TOP:
4551                         status.setEnabled(tabular.tabular_width.zero());
4552                         status.setOnOff(tabular.tabular_valignment 
4553                                 == Tabular::LYX_VALIGN_TOP);
4554                         break;
4555                 case Tabular::TABULAR_VALIGN_MIDDLE:
4556                         status.setEnabled(tabular.tabular_width.zero());
4557                         status.setOnOff(tabular.tabular_valignment 
4558                                 == Tabular::LYX_VALIGN_MIDDLE);
4559                         break;
4560                 case Tabular::TABULAR_VALIGN_BOTTOM:
4561                         status.setEnabled(tabular.tabular_width.zero());
4562                         status.setOnOff(tabular.tabular_valignment 
4563                                 == Tabular::LYX_VALIGN_BOTTOM);
4564                         break;
4565
4566                 case Tabular::LONGTABULAR_ALIGN_LEFT:
4567                         status.setOnOff(tabular.longtabular_alignment 
4568                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
4569                         break;
4570                 case Tabular::LONGTABULAR_ALIGN_CENTER:
4571                         status.setOnOff(tabular.longtabular_alignment 
4572                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
4573                         break;
4574                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
4575                         status.setOnOff(tabular.longtabular_alignment 
4576                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
4577                         break;
4578
4579                 case Tabular::UNSET_ROTATE_TABULAR:
4580                         status.setOnOff(tabular.rotate == 0);
4581                         break;
4582
4583                 case Tabular::TOGGLE_ROTATE_CELL:
4584                 case Tabular::SET_ROTATE_CELL:
4585                         status.setOnOff(!oneCellHasRotationState(false,
4586                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4587                         break;
4588
4589                 case Tabular::UNSET_ROTATE_CELL:
4590                         status.setOnOff(!oneCellHasRotationState(true,
4591                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4592                         break;
4593
4594                 case Tabular::SET_USEBOX:
4595                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4596                         break;
4597
4598                 // every row can only be one thing:
4599                 // either a footer or header
4600                 case Tabular::SET_LTFIRSTHEAD:
4601                         status.setEnabled(sel_row_start == sel_row_end);
4602                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4603                         break;
4604
4605                 case Tabular::UNSET_LTFIRSTHEAD:
4606                         status.setEnabled(sel_row_start == sel_row_end && !tabular.ltCaption(sel_row_start));
4607                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4608                         break;
4609
4610                 case Tabular::SET_LTHEAD:
4611                         status.setEnabled(sel_row_start == sel_row_end);
4612                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4613                         break;
4614
4615                 case Tabular::UNSET_LTHEAD:
4616                         status.setEnabled(sel_row_start == sel_row_end && !tabular.ltCaption(sel_row_start));
4617                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4618                         break;
4619
4620                 case Tabular::SET_LTFOOT:
4621                         status.setEnabled(sel_row_start == sel_row_end);
4622                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4623                         break;
4624
4625                 case Tabular::UNSET_LTFOOT:
4626                         status.setEnabled(sel_row_start == sel_row_end && !tabular.ltCaption(sel_row_start));
4627                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4628                         break;
4629
4630                 case Tabular::SET_LTLASTFOOT:
4631                         status.setEnabled(sel_row_start == sel_row_end);
4632                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4633                         break;
4634
4635                 case Tabular::UNSET_LTLASTFOOT:
4636                         status.setEnabled(sel_row_start == sel_row_end && !tabular.ltCaption(sel_row_start));
4637                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4638                         break;
4639
4640                 case Tabular::SET_LTNEWPAGE:
4641                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4642                         break;
4643
4644                 // only one row in head/firsthead/foot/lasthead can be the caption
4645                 // and a multirow cannot be set as caption
4646                 case Tabular::SET_LTCAPTION:
4647                         status.setEnabled(sel_row_start == sel_row_end
4648                                 && (!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4649                                  || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
4650                                 && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
4651                                  || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
4652                                 && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4653                                  || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
4654                                 && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4655                                  || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT))
4656                                 && !tabular.isMultiRow(sel_row_start));
4657                         status.setOnOff(tabular.ltCaption(sel_row_start));
4658                         break;
4659
4660                 case Tabular::UNSET_LTCAPTION:
4661                         status.setEnabled(sel_row_start == sel_row_end && tabular.ltCaption(sel_row_start));
4662                         break;
4663
4664                 case Tabular::TOGGLE_LTCAPTION:
4665                         status.setEnabled(sel_row_start == sel_row_end && (tabular.ltCaption(sel_row_start)
4666                                 || ((!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4667                                   || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
4668                                  && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
4669                                   || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
4670                                  && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4671                                   || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
4672                                  && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4673                                   || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT)))));
4674                         status.setOnOff(tabular.ltCaption(sel_row_start));
4675                         break;
4676
4677                 case Tabular::SET_BOOKTABS:
4678                         status.setOnOff(tabular.use_booktabs);
4679                         break;
4680
4681                 case Tabular::UNSET_BOOKTABS:
4682                         status.setOnOff(!tabular.use_booktabs);
4683                         break;
4684
4685                 default:
4686                         status.clear();
4687                         status.setEnabled(false);
4688                         break;
4689                 }
4690                 return true;
4691         }
4692
4693         // These are only enabled inside tabular
4694         case LFUN_CELL_BACKWARD:
4695         case LFUN_CELL_FORWARD:
4696                 status.setEnabled(true);
4697                 return true;
4698
4699         // disable these with multiple cells selected
4700         case LFUN_INSET_INSERT:
4701         case LFUN_TABULAR_INSERT:
4702         case LFUN_FLEX_INSERT:
4703         case LFUN_FLOAT_INSERT:
4704         case LFUN_FLOAT_WIDE_INSERT:
4705         case LFUN_FOOTNOTE_INSERT:
4706         case LFUN_MARGINALNOTE_INSERT:
4707         case LFUN_MATH_INSERT:
4708         case LFUN_MATH_MODE:
4709         case LFUN_MATH_MUTATE:
4710         case LFUN_MATH_DISPLAY:
4711         case LFUN_NOTE_INSERT:
4712         case LFUN_ARGUMENT_INSERT:
4713         case LFUN_BOX_INSERT:
4714         case LFUN_BRANCH_INSERT:
4715         case LFUN_PHANTOM_INSERT:
4716         case LFUN_WRAP_INSERT:
4717         case LFUN_PREVIEW_INSERT:
4718         case LFUN_ERT_INSERT: {
4719                 if (cur.selIsMultiCell()) {
4720                         status.setEnabled(false);
4721                         return true;
4722                 } else
4723                         return cell(cur.idx())->getStatus(cur, cmd, status);
4724         }
4725
4726         // disable in non-fixed-width cells
4727         case LFUN_BREAK_PARAGRAPH:
4728                 // multirow does not allow paragraph breaks
4729                 if (tabular.isMultiRow(cur.idx())) {
4730                         status.setEnabled(false);
4731                         return true;
4732                 }
4733         case LFUN_NEWLINE_INSERT: {
4734                 if (tabular.getPWidth(cur.idx()).zero()) {
4735                         status.setEnabled(false);
4736                         return true;
4737                 } else
4738                         return cell(cur.idx())->getStatus(cur, cmd, status);
4739         }
4740
4741         case LFUN_NEWPAGE_INSERT:
4742                 status.setEnabled(false);
4743                 return true;
4744
4745         case LFUN_PASTE:
4746                 if (tabularStackDirty() && theClipboard().isInternal()) {
4747                         if (cur.selIsMultiCell()) {
4748                                 row_type rs, re;
4749                                 col_type cs, ce;
4750                                 getSelection(cur, rs, re, cs, ce);
4751                                 if (paste_tabular && paste_tabular->ncols() == ce - cs + 1
4752                                           && paste_tabular->nrows() == re - rs + 1)
4753                                         status.setEnabled(true);        
4754                                 else {
4755                                         status.setEnabled(false);
4756                                         status.message(_("Selection size should match clipboard content."));
4757                                 }
4758                         } else
4759                                 status.setEnabled(true);
4760                         return true;
4761                 }
4762                 return cell(cur.idx())->getStatus(cur, cmd, status);
4763
4764         case LFUN_INSET_SETTINGS:
4765                 // relay this lfun to Inset, not to the cell.
4766                 return Inset::getStatus(cur, cmd, status);
4767
4768         default:
4769                 // we try to handle this event in the insets dispatch function.
4770                 return cell(cur.idx())->getStatus(cur, cmd, status);
4771         }
4772         return false;
4773 }
4774
4775
4776 Inset::DisplayType InsetTabular::display() const
4777 {
4778                 if (tabular.is_long_tabular) {
4779                         switch (tabular.longtabular_alignment) {
4780                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
4781                                 return AlignLeft;
4782                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
4783                                 return AlignCenter;
4784                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
4785                                 return AlignRight;
4786                         default:
4787                                 return AlignCenter;
4788                         }
4789                 } else
4790                         return Inline;
4791 }
4792
4793
4794 void InsetTabular::latex(otexstream & os, OutputParams const & runparams) const
4795 {
4796         tabular.latex(os, runparams);
4797 }
4798
4799
4800 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
4801 {
4802         os << '\n'; // output table on a new line
4803         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
4804         tabular.plaintext(os, runparams, dp, false, 0);
4805         return PLAINTEXT_NEWLINE;
4806 }
4807
4808
4809 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
4810 {
4811         int ret = 0;
4812         Inset * master = 0;
4813
4814         // FIXME: Why not pass a proper DocIterator here?
4815 #if 0
4816         // if the table is inside a float it doesn't need the informaltable
4817         // wrapper. Search for it.
4818         for (master = owner(); master; master = master->owner())
4819                 if (master->lyxCode() == FLOAT_CODE)
4820                         break;
4821 #endif
4822
4823         if (!master) {
4824                 os << "<informaltable>";
4825                 ++ret;
4826         }
4827         ret += tabular.docbook(os, runparams);
4828         if (!master) {
4829                 os << "</informaltable>";
4830                 ++ret;
4831         }
4832         return ret;
4833 }
4834
4835
4836 docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
4837 {
4838         return tabular.xhtml(xs, rp);
4839 }
4840
4841
4842 void InsetTabular::validate(LaTeXFeatures & features) const
4843 {
4844         tabular.validate(features);
4845         // FIXME XHTML
4846         // It'd be better to be able to get this from an InsetLayout, but at present
4847         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
4848         if (features.runparams().flavor == OutputParams::HTML)
4849                 features.addCSSSnippet(
4850                         "table { border: 1px solid black; display: inline-block; }\n"
4851                         "td { border: 1px solid black; padding: 0.5ex; }");
4852 }
4853
4854
4855 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
4856 {
4857         return tabular.cellInset(idx);
4858 }
4859
4860
4861 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
4862 {
4863         return tabular.cellInset(idx);
4864 }
4865
4866
4867 void InsetTabular::cursorPos(BufferView const & bv,
4868                 CursorSlice const & sl, bool boundary, int & x, int & y) const
4869 {
4870         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
4871
4872         // y offset     correction
4873         y += cellYPos(sl.idx());
4874         y += tabular.textVOffset(sl.idx());
4875         y += offset_valign_;
4876
4877         // x offset correction
4878         x += cellXPos(sl.idx());
4879         x += tabular.textHOffset(sl.idx());
4880         x += ADD_TO_TABULAR_WIDTH;
4881         x += scx_;
4882 }
4883
4884
4885 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
4886 {
4887         int xx = 0;
4888         int yy = 0;
4889         Inset const & inset = *tabular.cellInset(cell);
4890         Point o = bv.coordCache().getInsets().xy(&inset);
4891         int const xbeg = o.x_ - tabular.textHOffset(cell);
4892         int const xend = xbeg + tabular.cellWidth(cell);
4893         row_type const row = tabular.cellRow(cell);
4894         int const ybeg = o.y_ - tabular.rowAscent(row)
4895                 - tabular.interRowSpace(row) - tabular.textVOffset(cell);
4896         int const yend = ybeg + tabular.cellHeight(cell);
4897
4898         if (x < xbeg)
4899                 xx = xbeg - x;
4900         else if (x > xend)
4901                 xx = x - xend;
4902
4903         if (y < ybeg)
4904                 yy = ybeg - y;
4905         else if (y > yend)
4906                 yy = y - yend;
4907
4908         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
4909         //       << " ybeg=" << ybeg << " yend=" << yend
4910         //       << " xx=" << xx << " yy=" << yy
4911         //       << " dist=" << xx + yy << endl;
4912         return xx + yy;
4913 }
4914
4915
4916 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
4917 {
4918         //lyxerr << "InsetTabular::editXY: " << this << endl;
4919         cur.setSelection(false);
4920         cur.push(*this);
4921         cur.idx() = getNearestCell(cur.bv(), x, y);
4922         resetPos(cur);
4923         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
4924 }
4925
4926
4927 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
4928 {
4929         cur.idx() = getNearestCell(cur.bv(), x, y);
4930         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
4931 }
4932
4933
4934 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
4935 {
4936         idx_type idx_min = 0;
4937         int dist_min = numeric_limits<int>::max();
4938         for (idx_type i = 0, n = nargs(); i != n; ++i) {
4939                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
4940                         int const d = dist(bv, i, x, y);
4941                         if (d < dist_min) {
4942                                 dist_min = d;
4943                                 idx_min = i;
4944                         }
4945                 }
4946         }
4947         return idx_min;
4948 }
4949
4950
4951 int InsetTabular::cellYPos(idx_type const cell) const
4952 {
4953         row_type row = tabular.cellRow(cell);
4954         int ly = 0;
4955         for (row_type r = 0; r < row; ++r)
4956                 ly += tabular.rowDescent(r) + tabular.rowAscent(r + 1) 
4957                         + tabular.interRowSpace(r + 1);
4958         return ly;
4959 }
4960
4961
4962 int InsetTabular::cellXPos(idx_type const cell) const
4963 {
4964         col_type col = tabular.cellColumn(cell);
4965         int lx = 0;
4966         for (col_type c = 0; c < col; ++c)
4967                 lx += tabular.column_info[c].width;
4968         return lx;
4969 }
4970
4971
4972 void InsetTabular::resetPos(Cursor & cur) const
4973 {
4974         BufferView & bv = cur.bv();
4975         int const maxwidth = bv.workWidth();
4976
4977         int const scx_old = scx_;
4978         int const i = cur.find(this);
4979         if (i == -1) {
4980                 scx_ = 0;
4981         } else {
4982                 int const X1 = 0;
4983                 int const X2 = maxwidth;
4984                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
4985                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
4986                 int const x2 = x1 + tabular.cellWidth(cur[i].idx());
4987
4988                 if (x1 < X1)
4989                         scx_ = X1 + 20 - x1;
4990                 else if (x2 > X2)
4991                         scx_ = X2 - 20 - x2;
4992                 else
4993                         scx_ = 0;
4994         }
4995
4996         // only update if offset changed
4997         if (scx_ != scx_old)
4998                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4999 }
5000
5001
5002 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
5003 {
5004         row_type const row = tabular.cellRow(cur.idx());
5005         col_type const col = tabular.cellColumn(cur.idx());
5006
5007         if (isRightToLeft(cur)) {
5008                 if (tabular.cellColumn(cur.idx()) == 0) {
5009                         if (row == tabular.nrows() - 1)
5010                                 return;
5011                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
5012                 } else {
5013                         if (cur.idx() == 0)
5014                                 return;
5015                         if (col == 0)
5016                                 cur.idx() = tabular.getLastCellInRow(row - 1);
5017                         else
5018                                 cur.idx() = tabular.cellIndex(row, col - 1);
5019                 }
5020         } else {
5021                 if (tabular.isLastCell(cur.idx()))
5022                         return;
5023                 if (cur.idx() == tabular.getLastCellInRow(row))
5024                         cur.idx() = tabular.cellIndex(row + 1, 0);
5025                 else {
5026                         col_type const colnextcell = col + tabular.columnSpan(cur.idx());
5027                         cur.idx() = tabular.cellIndex(row, colnextcell);
5028                 }
5029         }
5030
5031         cur.boundary(false);
5032
5033         if (cur.selIsMultiCell()) {
5034                 cur.pit() = cur.lastpit();
5035                 cur.pos() = cur.lastpos();
5036                 resetPos(cur);
5037                 return;
5038         }
5039
5040         cur.pit() = 0;
5041         cur.pos() = 0;
5042
5043         // in visual mode, place cursor at extreme left or right
5044         
5045         switch(entry_from) {
5046
5047         case ENTRY_DIRECTION_RIGHT:
5048                 cur.posVisToRowExtremity(false /* !left */);
5049                 break;
5050         case ENTRY_DIRECTION_LEFT:
5051                 cur.posVisToRowExtremity(true /* left */);
5052                 break;
5053         case ENTRY_DIRECTION_IGNORE:
5054                 // nothing to do in this case
5055                 break;
5056
5057         }
5058         cur.setCurrentFont();
5059         resetPos(cur);
5060 }
5061
5062
5063 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
5064 {
5065         row_type const row = tabular.cellRow(cur.idx());
5066         col_type const col = tabular.cellColumn(cur.idx());
5067
5068         if (isRightToLeft(cur)) {
5069                 if (cur.idx() == tabular.getLastCellInRow(row)) {
5070                         if (row == 0)
5071                                 return;
5072                         cur.idx() = tabular.getFirstCellInRow(row);
5073                         cur.idx() = tabular.cellAbove(cur.idx());
5074                 } else {
5075                         if (tabular.isLastCell(cur.idx()))
5076                                 return;
5077                         if (cur.idx() == tabular.getLastCellInRow(row))
5078                                 cur.idx() = tabular.cellIndex(row + 1, 0);
5079                         else
5080                                 cur.idx() = tabular.cellIndex(row, col + 1);
5081                 }
5082         } else {
5083                 if (cur.idx() == 0) // first cell
5084                         return;
5085                 if (col == 0)
5086                         cur.idx() = tabular.getLastCellInRow(row - 1);
5087                 else
5088                         cur.idx() = tabular.cellIndex(row, col - 1);
5089         }
5090
5091         if (cur.selIsMultiCell()) {
5092                 cur.pit() = cur.lastpit();
5093                 cur.pos() = cur.lastpos();
5094                 resetPos(cur);
5095                 return;
5096         }
5097
5098         cur.pit() = cur.lastpit();
5099         cur.pos() = cur.lastpos();
5100
5101         // in visual mode, place cursor at extreme left or right
5102         
5103         switch(entry_from) {
5104
5105         case ENTRY_DIRECTION_RIGHT:
5106                 cur.posVisToRowExtremity(false /* !left */);
5107                 break;
5108         case ENTRY_DIRECTION_LEFT:
5109                 cur.posVisToRowExtremity(true /* left */);
5110                 break;
5111         case ENTRY_DIRECTION_IGNORE:
5112                 // nothing to do in this case
5113                 break;
5114
5115         }
5116         cur.setCurrentFont();
5117         resetPos(cur);
5118 }
5119
5120
5121 bool InsetTabular::tabularFeatures(Cursor & cur, string const & argument)
5122 {
5123         istringstream is(argument);
5124         string s;
5125         is >> s;
5126         if (insetCode(s) != TABULAR_CODE)
5127                 return false;
5128
5129         // Safe guard.
5130         size_t safe_guard = 0;
5131         for (;;) {
5132                 if (is.eof())
5133                         break;
5134                 safe_guard++;
5135                 if (safe_guard > 1000) {
5136                         LYXERR0("parameter max count reached!");
5137                         break;
5138                 }
5139                 is >> s;
5140                 Tabular::Feature action = Tabular::LAST_ACTION;
5141
5142                 size_t i = 0;
5143                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
5144                         if (s != tabularFeature[i].feature)
5145                                 continue;
5146                         action = tabularFeature[i].action;
5147                         break;
5148                 }
5149                 if (action == Tabular::LAST_ACTION) {
5150                         LYXERR0("Feature not found " << s);
5151                         continue;
5152                 }
5153                 string val;
5154                 if (tabularFeature[i].need_value)
5155                         is >> val;
5156                 LYXERR(Debug::DEBUG, "Feature: " << s << "\t\tvalue: " << val);
5157                 tabularFeatures(cur, action, val);
5158         }
5159         return true;
5160 }
5161
5162
5163 static void checkLongtableSpecial(Tabular::ltType & ltt,
5164                           string const & special, bool & flag)
5165 {
5166         if (special == "dl_above") {
5167                 ltt.topDL = flag;
5168                 ltt.set = false;
5169         } else if (special == "dl_below") {
5170                 ltt.bottomDL = flag;
5171                 ltt.set = false;
5172         } else if (special == "empty") {
5173                 ltt.empty = flag;
5174                 ltt.set = false;
5175         } else if (flag) {
5176                 ltt.empty = false;
5177                 ltt.set = true;
5178         }
5179 }
5180
5181
5182 bool InsetTabular::oneCellHasRotationState(bool rotated,
5183                 row_type row_start, row_type row_end,
5184                 col_type col_start, col_type col_end) const 
5185 {
5186         for (row_type r = row_start; r <= row_end; ++r)
5187                 for (col_type c = col_start; c <= col_end; ++c)
5188                         if (rotated) {
5189                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) != 0)
5190                                         return true;
5191                         } else {
5192                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) == 0)
5193                                         return true;
5194                         }
5195         return false;
5196 }
5197
5198
5199 void InsetTabular::tabularFeatures(Cursor & cur,
5200         Tabular::Feature feature, string const & value)
5201 {
5202         col_type sel_col_start;
5203         col_type sel_col_end;
5204         row_type sel_row_start;
5205         row_type sel_row_end;
5206         bool setLines = false;
5207         LyXAlignment setAlign = LYX_ALIGN_LEFT;
5208         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
5209
5210         switch (feature) {
5211
5212         case Tabular::M_ALIGN_LEFT:
5213         case Tabular::ALIGN_LEFT:
5214                 setAlign = LYX_ALIGN_LEFT;
5215                 break;
5216
5217         case Tabular::M_ALIGN_RIGHT:
5218         case Tabular::ALIGN_RIGHT:
5219                 setAlign = LYX_ALIGN_RIGHT;
5220                 break;
5221
5222         case Tabular::M_ALIGN_CENTER:
5223         case Tabular::ALIGN_CENTER:
5224                 setAlign = LYX_ALIGN_CENTER;
5225                 break;
5226
5227         case Tabular::ALIGN_BLOCK:
5228                 setAlign = LYX_ALIGN_BLOCK;
5229                 break;
5230
5231         case Tabular::ALIGN_DECIMAL:
5232                 setAlign = LYX_ALIGN_DECIMAL;
5233                 break;
5234
5235         case Tabular::M_VALIGN_TOP:
5236         case Tabular::VALIGN_TOP:
5237                 setVAlign = Tabular::LYX_VALIGN_TOP;
5238                 break;
5239
5240         case Tabular::M_VALIGN_BOTTOM:
5241         case Tabular::VALIGN_BOTTOM:
5242                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
5243                 break;
5244
5245         case Tabular::M_VALIGN_MIDDLE:
5246         case Tabular::VALIGN_MIDDLE:
5247                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
5248                 break;
5249
5250         default:
5251                 break;
5252         }
5253
5254         cur.recordUndoInset(ATOMIC_UNDO, this);
5255
5256         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5257         row_type const row = tabular.cellRow(cur.idx());
5258         col_type const column = tabular.cellColumn(cur.idx());
5259         bool flag = true;
5260         Tabular::ltType ltt;
5261
5262         switch (feature) {
5263
5264         case Tabular::SET_TABULAR_WIDTH:
5265                 tabular.setTabularWidth(Length(value));
5266                 break;
5267
5268         case Tabular::SET_PWIDTH: {
5269                 Length const len(value);
5270                 tabular.setColumnPWidth(cur, cur.idx(), len);
5271                 if (len.zero()
5272                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
5273                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
5274                 break;
5275         }
5276
5277         case Tabular::SET_MPWIDTH:
5278                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
5279                 break;
5280
5281         case Tabular::SET_MROFFSET:
5282                 tabular.setMROffset(cur, cur.idx(), Length(value));
5283                 break;
5284
5285         case Tabular::SET_SPECIAL_COLUMN:
5286         case Tabular::SET_SPECIAL_MULTICOLUMN:
5287                 if (value == "none")
5288                         tabular.setAlignSpecial(cur.idx(), docstring(), feature);
5289                 else
5290                         tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
5291                 break;
5292
5293         case Tabular::APPEND_ROW:
5294                 // append the row into the tabular
5295                 tabular.appendRow(row);
5296                 break;
5297
5298         case Tabular::APPEND_COLUMN:
5299                 // append the column into the tabular
5300                 tabular.appendColumn(column);
5301                 cur.idx() = tabular.cellIndex(row, column);
5302                 break;
5303
5304         case Tabular::DELETE_ROW:
5305                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5306                         tabular.deleteRow(sel_row_start);
5307                 if (sel_row_start >= tabular.nrows())
5308                         --sel_row_start;
5309                 cur.idx() = tabular.cellIndex(sel_row_start, column);
5310                 cur.pit() = 0;
5311                 cur.pos() = 0;
5312                 cur.setSelection(false);
5313                 break;
5314
5315         case Tabular::DELETE_COLUMN:
5316                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5317                         tabular.deleteColumn(sel_col_start);
5318                 if (sel_col_start >= tabular.ncols())
5319                         --sel_col_start;
5320                 cur.idx() = tabular.cellIndex(row, sel_col_start);
5321                 cur.pit() = 0;
5322                 cur.pos() = 0;
5323                 cur.setSelection(false);
5324                 break;
5325
5326         case Tabular::COPY_ROW:
5327                 tabular.copyRow(row);
5328                 break;
5329
5330         case Tabular::COPY_COLUMN:
5331                 tabular.copyColumn(column);
5332                 cur.idx() = tabular.cellIndex(row, column);
5333                 break;
5334
5335         case Tabular::SET_LINE_TOP:
5336         case Tabular::TOGGLE_LINE_TOP: {
5337                 bool lineSet = (feature == Tabular::SET_LINE_TOP)
5338                                ? (value == "true") : !tabular.topLine(cur.idx());
5339                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5340                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5341                                 tabular.setTopLine(tabular.cellIndex(r, c), lineSet);
5342                 break;
5343         }
5344
5345         case Tabular::SET_LINE_BOTTOM:
5346         case Tabular::TOGGLE_LINE_BOTTOM: {
5347                 bool lineSet = (feature == Tabular::SET_LINE_BOTTOM)
5348                                ? (value == "true") : !tabular.bottomLine(cur.idx());
5349                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5350                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5351                                 tabular.setBottomLine(tabular.cellIndex(r, c), lineSet);
5352                 break;
5353         }
5354
5355         case Tabular::SET_LINE_LEFT:
5356         case Tabular::TOGGLE_LINE_LEFT: {
5357                 bool lineSet = (feature == Tabular::SET_LINE_LEFT)
5358                                ? (value == "true") : !tabular.leftLine(cur.idx());
5359                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5360                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5361                                 tabular.setLeftLine(tabular.cellIndex(r, c), lineSet);
5362                 break;
5363         }
5364
5365         case Tabular::SET_LINE_RIGHT:
5366         case Tabular::TOGGLE_LINE_RIGHT: {
5367                 bool lineSet = (feature == Tabular::SET_LINE_RIGHT)
5368                                ? (value == "true") : !tabular.rightLine(cur.idx());
5369                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5370                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5371                                 tabular.setRightLine(tabular.cellIndex(r, c), lineSet);
5372                 break;
5373         }
5374
5375         case Tabular::M_ALIGN_LEFT:
5376         case Tabular::M_ALIGN_RIGHT:
5377         case Tabular::M_ALIGN_CENTER:
5378         case Tabular::ALIGN_LEFT:
5379         case Tabular::ALIGN_RIGHT:
5380         case Tabular::ALIGN_CENTER:
5381         case Tabular::ALIGN_BLOCK:
5382         case Tabular::ALIGN_DECIMAL:
5383                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5384                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5385                                 tabular.setAlignment(tabular.cellIndex(r, c), setAlign,
5386                                 !tabular.getPWidth(c).zero());
5387                 break;
5388
5389         case Tabular::M_VALIGN_TOP:
5390         case Tabular::M_VALIGN_BOTTOM:
5391         case Tabular::M_VALIGN_MIDDLE:
5392                 flag = false;
5393         case Tabular::VALIGN_TOP:
5394         case Tabular::VALIGN_BOTTOM:
5395         case Tabular::VALIGN_MIDDLE:
5396                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5397                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5398                                 tabular.setVAlignment(tabular.cellIndex(r, c), setVAlign, flag);
5399                 break;
5400
5401         case Tabular::SET_MULTICOLUMN: {
5402                 if (!cur.selection()) {
5403                         // just multicol for one single cell
5404                         // check whether we are completely in a multicol
5405                         if (!tabular.isMultiColumn(cur.idx()))
5406                                 tabular.setMultiColumn(cur.idx(), 1,
5407                                         tabular.rightLine(cur.idx()));
5408                         break;
5409                 }
5410                 // we have a selection so this means we just add all this
5411                 // cells to form a multicolumn cell
5412                 idx_type const s_start = cur.selBegin().idx();
5413                 row_type const col_start = tabular.cellColumn(s_start);
5414                 row_type const col_end = tabular.cellColumn(cur.selEnd().idx());
5415                 cur.idx() = tabular.setMultiColumn(s_start, col_end - col_start + 1,
5416                                                    tabular.rightLine(cur.selEnd().idx()));
5417                 cur.pit() = 0;
5418                 cur.pos() = 0;
5419                 cur.setSelection(false);
5420                 break;
5421         }
5422
5423         case Tabular::UNSET_MULTICOLUMN: {
5424                 if (!cur.selection()) {
5425                         if (tabular.isMultiColumn(cur.idx()))
5426                                 tabular.unsetMultiColumn(cur.idx());
5427                 }
5428                 break;
5429         }
5430
5431         case Tabular::MULTICOLUMN: {
5432                 if (!cur.selection()) {
5433                         if (tabular.isMultiColumn(cur.idx()))
5434                                 tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5435                         else
5436                                 tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5437                         break;
5438                 }
5439                 bool merge = false;
5440                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5441                         row_type const r = sel_row_start;
5442                         if (!tabular.isMultiColumn(tabular.cellIndex(r, c))
5443                             || (r > sel_row_start && !tabular.isPartOfMultiColumn(r, c)))
5444                                 merge = true;
5445                 }
5446                 // If the selection contains at least one singlecol cell
5447                 // or multiple multicol cells,
5448                 // we assume the user will merge is to a single multicol
5449                 if (merge)
5450                         tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5451                 else
5452                         tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5453                 break;
5454         }
5455
5456         case Tabular::SET_MULTIROW: {
5457                 if (!cur.selection()) {
5458                         // just multirow for one single cell
5459                         // check whether we are completely in a multirow
5460                         if (!tabular.isMultiRow(cur.idx()))
5461                                 tabular.setMultiRow(cur.idx(), 1,
5462                                                     tabular.bottomLine(cur.idx()));
5463                         break;
5464                 }
5465                 // we have a selection so this means we just add all this
5466                 // cells to form a multirow cell
5467                 idx_type const s_start = cur.selBegin().idx();
5468                 row_type const row_start = tabular.cellRow(s_start);
5469                 row_type const row_end = tabular.cellRow(cur.selEnd().idx());
5470                 cur.idx() = tabular.setMultiRow(s_start, row_end - row_start + 1,
5471                                                 tabular.bottomLine(cur.selEnd().idx()));
5472                 cur.pit() = 0;
5473                 cur.pos() = 0;
5474                 cur.setSelection(false);
5475                 break;
5476         }
5477
5478         case Tabular::UNSET_MULTIROW: {
5479                 if (!cur.selection()) {
5480                         if (tabular.isMultiRow(cur.idx()))
5481                                 tabular.unsetMultiRow(cur.idx());
5482                 }
5483                 break;
5484         }
5485
5486         case Tabular::MULTIROW: {
5487                 if (!cur.selection()) {
5488                         if (tabular.isMultiRow(cur.idx()))
5489                                 tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5490                         else
5491                                 tabularFeatures(cur, Tabular::SET_MULTIROW);
5492                         break;
5493                 }
5494                 bool merge = false;
5495                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5496                         col_type const c = sel_col_start;
5497                         if (!tabular.isMultiRow(tabular.cellIndex(r, c))
5498                             || (r > sel_row_start && !tabular.isPartOfMultiRow(r, c)))
5499                                 merge = true;
5500                 }
5501                 // If the selection contains at least one singlerow cell
5502                 // or multiple multirow cells,
5503                 // we assume the user will merge is to a single multirow
5504                 if (merge)
5505                         tabularFeatures(cur, Tabular::SET_MULTIROW);
5506                 else
5507                         tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5508                 break;
5509         }
5510
5511         case Tabular::SET_ALL_LINES:
5512                 setLines = true;
5513         case Tabular::UNSET_ALL_LINES:
5514                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5515                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5516                                 idx_type const cell = tabular.cellIndex(r, c);
5517                                 tabular.setTopLine(cell, setLines);
5518                                 tabular.setBottomLine(cell, setLines);
5519                                 tabular.setRightLine(cell, setLines);
5520                                 tabular.setLeftLine(cell, setLines);
5521                         }
5522                 break;
5523
5524         case Tabular::SET_BORDER_LINES:
5525                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5526                         tabular.setLeftLine(tabular.cellIndex(r, sel_col_start), true);
5527                         tabular.setRightLine(tabular.cellIndex(r, sel_col_end), true);
5528                 }
5529                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5530                         tabular.setTopLine(tabular.cellIndex(sel_row_start, c), true);
5531                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, c), true);
5532                 }
5533                 break;
5534
5535         case Tabular::SET_LONGTABULAR:
5536                 tabular.is_long_tabular = true;
5537                 break;
5538
5539         case Tabular::UNSET_LONGTABULAR:
5540                 for (row_type r = 0; r < tabular.nrows(); ++r) {
5541                         if (tabular.ltCaption(r)) {
5542                                 cur.idx() = tabular.cellIndex(r, 0);
5543                                 cur.pit() = 0;
5544                                 cur.pos() = 0;
5545                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
5546                         }
5547                 }
5548                 tabular.is_long_tabular = false;
5549                 break;
5550
5551         case Tabular::SET_ROTATE_TABULAR:
5552                 tabular.rotate = convert<int>(value);
5553                 break;
5554
5555         case Tabular::UNSET_ROTATE_TABULAR:
5556                 tabular.rotate = 0;
5557                 break;
5558
5559         case Tabular::TOGGLE_ROTATE_TABULAR:
5560                 // when pressing the rotate button we default to 90° rotation
5561                 tabular.rotate != 0 ? tabular.rotate = 0 : tabular.rotate = 90;
5562                 break;
5563
5564         case Tabular::TABULAR_VALIGN_TOP:
5565                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
5566                 break;
5567
5568         case Tabular::TABULAR_VALIGN_MIDDLE:
5569                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
5570                 break;
5571
5572         case Tabular::TABULAR_VALIGN_BOTTOM:
5573                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
5574                 break;
5575
5576         case Tabular::LONGTABULAR_ALIGN_LEFT:
5577                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
5578                 break;
5579
5580         case Tabular::LONGTABULAR_ALIGN_CENTER:
5581                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
5582                 break;
5583
5584         case Tabular::LONGTABULAR_ALIGN_RIGHT:
5585                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
5586                 break;
5587
5588                 
5589
5590         case Tabular::SET_ROTATE_CELL:
5591                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5592                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5593                                 tabular.setRotateCell(tabular.cellIndex(r, c), convert<int>(value));
5594                 break;
5595
5596         case Tabular::UNSET_ROTATE_CELL:
5597                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5598                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5599                                 tabular.setRotateCell(tabular.cellIndex(r, c), 0);
5600                 break;
5601
5602         case Tabular::TOGGLE_ROTATE_CELL:
5603                 {
5604                 bool oneNotRotated = oneCellHasRotationState(false,
5605                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5606
5607                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5608                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5609                                 // when pressing the rotate cell button we default to 90° rotation
5610                                 if (oneNotRotated)
5611                                         tabular.setRotateCell(tabular.cellIndex(r, c), 90);
5612                                 else
5613                                         tabular.setRotateCell(tabular.cellIndex(r, c), 0);
5614                         }
5615                 }
5616                 break;
5617
5618         case Tabular::SET_USEBOX: {
5619                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
5620                 if (val == tabular.getUsebox(cur.idx()))
5621                         val = Tabular::BOX_NONE;
5622                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5623                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5624                                 tabular.setUsebox(tabular.cellIndex(r, c), val);
5625                 break;
5626         }
5627
5628         case Tabular::UNSET_LTFIRSTHEAD:
5629                 flag = false;
5630         case Tabular::SET_LTFIRSTHEAD:
5631                 tabular.getRowOfLTFirstHead(row, ltt);
5632                 checkLongtableSpecial(ltt, value, flag);
5633                 tabular.setLTHead(row, flag, ltt, true);
5634                 break;
5635
5636         case Tabular::UNSET_LTHEAD:
5637                 flag = false;
5638         case Tabular::SET_LTHEAD:
5639                 tabular.getRowOfLTHead(row, ltt);
5640                 checkLongtableSpecial(ltt, value, flag);
5641                 tabular.setLTHead(row, flag, ltt, false);
5642                 break;
5643
5644         case Tabular::UNSET_LTFOOT:
5645                 flag = false;
5646         case Tabular::SET_LTFOOT:
5647                 tabular.getRowOfLTFoot(row, ltt);
5648                 checkLongtableSpecial(ltt, value, flag);
5649                 tabular.setLTFoot(row, flag, ltt, false);
5650                 break;
5651
5652         case Tabular::UNSET_LTLASTFOOT:
5653                 flag = false;
5654         case Tabular::SET_LTLASTFOOT:
5655                 tabular.getRowOfLTLastFoot(row, ltt);
5656                 checkLongtableSpecial(ltt, value, flag);
5657                 tabular.setLTFoot(row, flag, ltt, true);
5658                 break;
5659
5660         case Tabular::SET_LTNEWPAGE:
5661                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
5662                 break;
5663
5664         case Tabular::SET_LTCAPTION: {
5665                 if (tabular.ltCaption(row))
5666                         break;
5667                 cur.idx() = tabular.setLTCaption(row, true);
5668                 cur.pit() = 0;
5669                 cur.pos() = 0;
5670                 cur.setSelection(false);
5671                 // If a row is set as caption, then also insert
5672                 // a caption. Otherwise the LaTeX output is broken.
5673                 lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
5674                 lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
5675                 break;
5676         }
5677         
5678         case Tabular::UNSET_LTCAPTION: {
5679                 if (!tabular.ltCaption(row))
5680                         break;
5681                 cur.idx() = tabular.setLTCaption(row, false);
5682                 cur.pit() = 0;
5683                 cur.pos() = 0;
5684                 cur.setSelection(false);
5685                 FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
5686                 if (lyx::getStatus(fr).enabled())
5687                         lyx::dispatch(fr);
5688                 break;
5689         }
5690
5691         case Tabular::TOGGLE_LTCAPTION: {
5692                 if (tabular.ltCaption(row))
5693                         tabularFeatures(cur, Tabular::UNSET_LTCAPTION);
5694                 else
5695                         tabularFeatures(cur, Tabular::SET_LTCAPTION);
5696                 break;
5697         }
5698
5699         case Tabular::SET_BOOKTABS:
5700                 tabular.use_booktabs = true;
5701                 break;
5702
5703         case Tabular::UNSET_BOOKTABS:
5704                 tabular.use_booktabs = false;
5705                 break;
5706
5707         case Tabular::SET_TOP_SPACE: {
5708                 Length len;
5709                 if (value == "default")
5710                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5711                                 tabular.row_info[r].top_space_default = true;
5712                 else if (value == "none")
5713                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5714                                 tabular.row_info[r].top_space_default = false;
5715                                 tabular.row_info[r].top_space = len;
5716                         }
5717                 else if (isValidLength(value, &len))
5718                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5719                                 tabular.row_info[r].top_space_default = false;
5720                                 tabular.row_info[r].top_space = len;
5721                         }
5722                 break;
5723         }
5724
5725         case Tabular::SET_BOTTOM_SPACE: {
5726                 Length len;
5727                 if (value == "default")
5728                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5729                                 tabular.row_info[r].bottom_space_default = true;
5730                 else if (value == "none")
5731                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5732                                 tabular.row_info[r].bottom_space_default = false;
5733                                 tabular.row_info[r].bottom_space = len;
5734                         }
5735                 else if (isValidLength(value, &len))
5736                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5737                                 tabular.row_info[r].bottom_space_default = false;
5738                                 tabular.row_info[r].bottom_space = len;
5739                         }
5740                 break;
5741         }
5742
5743         case Tabular::SET_INTERLINE_SPACE: {
5744                 Length len;
5745                 if (value == "default")
5746                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5747                                 tabular.row_info[r].interline_space_default = true;
5748                 else if (value == "none")
5749                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5750                                 tabular.row_info[r].interline_space_default = false;
5751                                 tabular.row_info[r].interline_space = len;
5752                         }
5753                 else if (isValidLength(value, &len))
5754                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5755                                 tabular.row_info[r].interline_space_default = false;
5756                                 tabular.row_info[r].interline_space = len;
5757                         }
5758                 break;
5759         }
5760
5761         case Tabular::SET_DECIMAL_POINT:
5762                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5763                         tabular.column_info[c].decimal_point = from_utf8(value);
5764                 break;
5765
5766         // dummy stuff just to avoid warnings
5767         case Tabular::LAST_ACTION:
5768                 break;
5769         }
5770 }
5771
5772
5773 bool InsetTabular::copySelection(Cursor & cur)
5774 {
5775         if (!cur.selection())
5776                 return false;
5777
5778         row_type rs, re;
5779         col_type cs, ce;
5780         getSelection(cur, rs, re, cs, ce);
5781
5782         paste_tabular.reset(new Tabular(tabular));
5783
5784         for (row_type r = 0; r < rs; ++r)
5785                 paste_tabular->deleteRow(0);
5786
5787         row_type const rows = re - rs + 1;
5788         while (paste_tabular->nrows() > rows)
5789                 paste_tabular->deleteRow(rows);
5790
5791         for (col_type c = 0; c < cs; ++c)
5792                 paste_tabular->deleteColumn(0);
5793
5794         col_type const columns = ce - cs + 1;
5795         while (paste_tabular->ncols() > columns)
5796                 paste_tabular->deleteColumn(columns);
5797
5798         paste_tabular->setBuffer(tabular.buffer());
5799
5800         odocstringstream os;
5801         OutputParams const runparams(0);
5802         paste_tabular->plaintext(os, runparams, 0, true, '\t');
5803         // Needed for the "Edit->Paste recent" menu and the system clipboard.
5804         cap::copySelection(cur, os.str());
5805
5806         // mark tabular stack dirty
5807         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
5808         // when we (hopefully) have a one-for-all paste mechanism.
5809         // This must be called after cap::copySelection.
5810         dirtyTabularStack(true);
5811
5812         return true;
5813 }
5814
5815
5816 bool InsetTabular::pasteClipboard(Cursor & cur)
5817 {
5818         if (!paste_tabular)
5819                 return false;
5820         col_type actcol = tabular.cellColumn(cur.idx());
5821         row_type actrow = tabular.cellRow(cur.idx());
5822
5823         if (cur.selIsMultiCell()) {
5824                 row_type re;
5825                 col_type ce;
5826                 getSelection(cur, actrow, re, actcol, ce);
5827         }
5828
5829         for (row_type r1 = 0, r2 = actrow;
5830              r1 < paste_tabular->nrows() && r2 < tabular.nrows();
5831              ++r1, ++r2) {
5832                 for (col_type c1 = 0, c2 = actcol;
5833                     c1 < paste_tabular->ncols() && c2 < tabular.ncols();
5834                     ++c1, ++c2) {
5835                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
5836                               tabular.isPartOfMultiColumn(r2, c2))
5837                                 continue;
5838                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
5839                                 --c2;
5840                                 continue;
5841                         }
5842                         if (tabular.isPartOfMultiColumn(r2, c2)) {
5843                                 --c1;
5844                                 continue;
5845                         }
5846                         shared_ptr<InsetTableCell> inset(
5847                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
5848                         tabular.setCellInset(r2, c2, inset);
5849                         // FIXME?: why do we need to do this explicitly? (EL)
5850                         tabular.cellInset(r2, c2)->setBuffer(tabular.buffer());
5851
5852                         // FIXME: change tracking (MG)
5853                         inset->setChange(Change(buffer().params().trackChanges ?
5854                                                 Change::INSERTED : Change::UNCHANGED));
5855                         cur.pos() = 0;
5856                 }
5857         }
5858         return true;
5859 }
5860
5861
5862 void InsetTabular::cutSelection(Cursor & cur)
5863 {
5864         if (!cur.selection())
5865                 return;
5866
5867         row_type rs, re;
5868         col_type cs, ce;
5869         getSelection(cur, rs, re, cs, ce);
5870         for (row_type r = rs; r <= re; ++r) {
5871                 for (col_type c = cs; c <= ce; ++c) {
5872                         shared_ptr<InsetTableCell> t
5873                                 = cell(tabular.cellIndex(r, c));
5874                         if (buffer().params().trackChanges)
5875                                 // FIXME: Change tracking (MG)
5876                                 t->setChange(Change(Change::DELETED));
5877                         else
5878                                 t->clear();
5879                 }
5880         }
5881
5882         // cursor position might be invalid now
5883         if (cur.pit() > cur.lastpit())
5884                 cur.pit() = cur.lastpit();
5885         if (cur.pos() > cur.lastpos())
5886                 cur.pos() = cur.lastpos();
5887         cur.clearSelection();
5888 }
5889
5890
5891 bool InsetTabular::isRightToLeft(Cursor & cur) const
5892 {
5893         LASSERT(cur.depth() > 1, /**/);
5894         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
5895         pos_type const parentpos = cur[cur.depth() - 2].pos();
5896         return parentpar.getFontSettings(buffer().params(),
5897                                          parentpos).language()->rightToLeft();
5898 }
5899
5900
5901 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
5902                                  bool intoInsets)
5903 {
5904         LASSERT(stidx <= enidx, return docstring());
5905         docstring retval;
5906         col_type const col1 = tabular.cellColumn(stidx);
5907         col_type const col2 = tabular.cellColumn(enidx);
5908         row_type const row1 = tabular.cellRow(stidx);
5909         row_type const row2 = tabular.cellRow(enidx);
5910         bool first = true;
5911         for (col_type col = col1; col <= col2; col++)
5912                 for (row_type row = row1; row <= row2; row++) {
5913                         if (!first)
5914                                 retval += "\n";
5915                         else
5916                                 first = false;
5917                         retval += tabular.cellInset(row, col)->asString(intoInsets);
5918                 }
5919         return retval;
5920 }
5921
5922
5923 void InsetTabular::getSelection(Cursor & cur,
5924         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
5925 {
5926         CursorSlice const & beg = cur.selBegin();
5927         CursorSlice const & end = cur.selEnd();
5928         cs = tabular.cellColumn(beg.idx());
5929         ce = tabular.cellColumn(end.idx());
5930         if (cs > ce)
5931                 swap(cs, ce);
5932
5933         rs = tabular.cellRow(beg.idx());
5934         re = tabular.cellRow(end.idx());
5935         if (rs > re)
5936                 swap(rs, re);
5937 }
5938
5939
5940 Text * InsetTabular::getText(int idx) const
5941 {
5942         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
5943 }
5944
5945
5946 void InsetTabular::setChange(Change const & change)
5947 {
5948         for (idx_type idx = 0; idx < nargs(); ++idx)
5949                 cell(idx)->setChange(change);
5950 }
5951
5952
5953 void InsetTabular::acceptChanges()
5954 {
5955         for (idx_type idx = 0; idx < nargs(); ++idx)
5956                 cell(idx)->acceptChanges();
5957 }
5958
5959
5960 void InsetTabular::rejectChanges()
5961 {
5962         for (idx_type idx = 0; idx < nargs(); ++idx)
5963                 cell(idx)->rejectChanges();
5964 }
5965
5966
5967 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
5968 {
5969         return tabular.getPWidth(cell).zero();
5970 }
5971
5972
5973 bool InsetTabular::forcePlainLayout(idx_type cell) const
5974 {
5975         return !tabular.getPWidth(cell).zero();
5976 }
5977
5978
5979 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
5980                                      bool usePaste)
5981 {
5982         if (buf.length() <= 0)
5983                 return true;
5984
5985         col_type cols = 1;
5986         row_type rows = 1;
5987         col_type maxCols = 1;
5988         size_t const len = buf.length();
5989         size_t p = 0;
5990
5991         while (p < len &&
5992                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
5993                 switch (buf[p]) {
5994                 case '\t':
5995                         ++cols;
5996                         break;
5997                 case '\n':
5998                         if (p + 1 < len)
5999                                 ++rows;
6000                         maxCols = max(cols, maxCols);
6001                         cols = 1;
6002                         break;
6003                 }
6004                 ++p;
6005         }
6006         maxCols = max(cols, maxCols);
6007         Tabular * loctab;
6008         idx_type cell = 0;
6009         col_type ocol = 0;
6010         row_type row = 0;
6011         if (usePaste) {
6012                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
6013                 loctab = paste_tabular.get();
6014                 cols = 0;
6015                 dirtyTabularStack(true);
6016         } else {
6017                 loctab = &tabular;
6018                 cell = bv.cursor().idx();
6019                 ocol = tabular.cellColumn(cell);
6020                 row = tabular.cellRow(cell);
6021         }
6022
6023         size_t op = 0;
6024         idx_type const cells = loctab->numberofcells;
6025         p = 0;
6026         cols = ocol;
6027         rows = loctab->nrows();
6028         col_type const columns = loctab->ncols();
6029
6030         while (cell < cells && p < len && row < rows &&
6031                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
6032         {
6033                 if (p >= len)
6034                         break;
6035                 switch (buf[p]) {
6036                 case '\t':
6037                         // we can only set this if we are not too far right
6038                         if (cols < columns) {
6039                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6040                                 Font const font = bv.textMetrics(&inset->text()).
6041                                         displayFont(0, 0);
6042                                 inset->setText(buf.substr(op, p - op), font,
6043                                                buffer().params().trackChanges);
6044                                 ++cols;
6045                                 ++cell;
6046                         }
6047                         break;
6048                 case '\n':
6049                         // we can only set this if we are not too far right
6050                         if (cols < columns) {
6051                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
6052                                 Font const font = bv.textMetrics(&inset->text()).
6053                                         displayFont(0, 0);
6054                                 inset->setText(buf.substr(op, p - op), font,
6055                                                buffer().params().trackChanges);
6056                         }
6057                         cols = ocol;
6058                         ++row;
6059                         if (row < rows)
6060                                 cell = loctab->cellIndex(row, cols);
6061                         break;
6062                 }
6063                 ++p;
6064                 op = p;
6065         }
6066         // check for the last cell if there is no trailing '\n'
6067         if (cell < cells && op < len) {
6068                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6069                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
6070                 inset->setText(buf.substr(op, len - op), font,
6071                         buffer().params().trackChanges);
6072         }
6073         return true;
6074 }
6075
6076
6077 void InsetTabular::addPreview(DocIterator const & inset_pos,
6078         PreviewLoader & loader) const
6079 {
6080         DocIterator cell_pos = inset_pos;
6081
6082         cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
6083         for (row_type r = 0; r < tabular.nrows(); ++r) {
6084                 for (col_type c = 0; c < tabular.ncols(); ++c) {
6085                         cell_pos.top().idx() = tabular.cellIndex(r, c);
6086                         tabular.cellInset(r, c)->addPreview(cell_pos, loader);
6087                 }
6088         }
6089 }
6090
6091
6092 bool InsetTabular::completionSupported(Cursor const & cur) const
6093 {
6094         Cursor const & bvCur = cur.bv().cursor();
6095         if (&bvCur.inset() != this)
6096                 return false;
6097         return cur.text()->completionSupported(cur);
6098 }
6099
6100
6101 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
6102 {
6103         return completionSupported(cur);
6104 }
6105
6106
6107 bool InsetTabular::automaticInlineCompletion() const
6108 {
6109         return lyxrc.completion_inline_text;
6110 }
6111
6112
6113 bool InsetTabular::automaticPopupCompletion() const
6114 {
6115         return lyxrc.completion_popup_text;
6116 }
6117
6118
6119 bool InsetTabular::showCompletionCursor() const
6120 {
6121         return lyxrc.completion_cursor_text;
6122 }
6123
6124
6125 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
6126 {
6127         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
6128 }
6129
6130
6131 docstring InsetTabular::completionPrefix(Cursor const & cur) const
6132 {
6133         if (!completionSupported(cur))
6134                 return docstring();
6135         return cur.text()->completionPrefix(cur);
6136 }
6137
6138
6139 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
6140 {
6141         if (!completionSupported(cur))
6142                 return false;
6143
6144         return cur.text()->insertCompletion(cur, s, finished);
6145 }
6146
6147
6148 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
6149                                     Dimension & dim) const
6150 {
6151         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
6152         tm.completionPosAndDim(cur, x, y, dim);
6153 }
6154
6155
6156 void InsetTabular::string2params(string const & in, InsetTabular & inset)
6157 {
6158         istringstream data(in);
6159         Lexer lex;
6160         lex.setStream(data);
6161
6162         if (in.empty())
6163                 return;
6164
6165         string token;
6166         lex >> token;
6167         if (!lex || token != "tabular") {
6168                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
6169                 return;
6170         }
6171
6172         // This is part of the inset proper that is usually swallowed
6173         // by Buffer::readInset
6174         lex >> token;
6175         if (!lex || token != "Tabular") {
6176                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
6177                 return;
6178         }
6179
6180         inset.read(lex);
6181 }
6182
6183
6184 string InsetTabular::params2string(InsetTabular const & inset)
6185 {
6186         ostringstream data;
6187         data << "tabular" << ' ';
6188         inset.write(data);
6189         data << "\\end_inset\n";
6190         return data.str();
6191 }
6192
6193
6194 } // namespace lyx