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