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