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