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