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