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