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