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