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