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