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