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