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