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