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