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