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