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