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