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