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