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