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