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