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