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