]> git.lyx.org Git - features.git/blob - src/insets/InsetTabular.cpp
Center longtable explicitly (#10690)
[features.git] / src / insets / InsetTabular.cpp
1 /**
2  * \file InsetTabular.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Matthias Ettrich
8  * \author José Matos
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Jürgen Vigna
14  * \author Uwe Stöhr
15  * \author Edwin Leuven
16  * \author Scott Kostyshak
17  *
18  * Full author contact details are available in file CREDITS.
19  */
20
21 #include <config.h>
22
23 #include "InsetTabular.h"
24
25 #include "buffer_funcs.h"
26 #include "Buffer.h"
27 #include "BufferParams.h"
28 #include "BufferView.h"
29 #include "CoordCache.h"
30 #include "Counters.h"
31 #include "Cursor.h"
32 #include "CutAndPaste.h"
33 #include "DispatchResult.h"
34 #include "FuncRequest.h"
35 #include "FuncStatus.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
38 #include "Language.h"
39 #include "LaTeXFeatures.h"
40 #include "Lexer.h"
41 #include "LyX.h"
42 #include "LyXRC.h"
43 #include "MetricsInfo.h"
44 #include "OutputParams.h"
45 #include "output_xhtml.h"
46 #include "Paragraph.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
49 #include "TexRow.h"
50 #include "texstream.h"
51 #include "TextClass.h"
52 #include "TextMetrics.h"
53
54 #include "frontends/Application.h"
55 #include "frontends/alert.h"
56 #include "frontends/Clipboard.h"
57 #include "frontends/Painter.h"
58 #include "frontends/Selection.h"
59
60 #include "support/convert.h"
61 #include "support/debug.h"
62 #include "support/docstream.h"
63 #include "support/FileName.h"
64 #include "support/gettext.h"
65 #include "support/lassert.h"
66 #include "support/lstrings.h"
67 #include "support/unique_ptr.h"
68
69 #include <cstring>
70 #include <iomanip>
71 #include <iostream>
72 #include <limits>
73 #include <sstream>
74
75 using namespace std;
76 using namespace lyx::support;
77
78
79
80 namespace lyx {
81
82 using cap::dirtyTabularStack;
83 using cap::tabularStackDirty;
84
85 using graphics::PreviewLoader;
86
87 using frontend::Painter;
88 using frontend::Clipboard;
89
90 namespace Alert = frontend::Alert;
91
92
93 namespace {
94
95 int const ADD_TO_HEIGHT = 2; // in cell
96 int const ADD_TO_TABULAR_WIDTH = 6; // horizontal space before and after the table
97 int const default_line_space = 10; // ?
98 int const WIDTH_OF_LINE = 5; // space between double lines
99
100
101 ///
102 unique_ptr<Tabular> paste_tabular;
103
104
105 struct TabularFeature {
106         Tabular::Feature action;
107         string feature;
108         bool need_value;
109 };
110
111
112 TabularFeature tabularFeature[] =
113 {
114         // the SET/UNSET actions are used by the table dialog,
115         // the TOGGLE actions by the table toolbar buttons
116         // FIXME: these values have been hardcoded in InsetMathGrid and other
117         // math insets.
118         { Tabular::APPEND_ROW, "append-row", false },
119         { Tabular::APPEND_COLUMN, "append-column", false },
120         { Tabular::DELETE_ROW, "delete-row", false },
121         { Tabular::DELETE_COLUMN, "delete-column", false },
122         { Tabular::COPY_ROW, "copy-row", false },
123         { Tabular::COPY_COLUMN, "copy-column", false },
124         { Tabular::MOVE_COLUMN_RIGHT, "move-column-right", false },
125         { Tabular::MOVE_COLUMN_LEFT, "move-column-left", false },
126         { Tabular::MOVE_ROW_DOWN, "move-row-down", false },
127         { Tabular::MOVE_ROW_UP, "move-row-up", false },
128         { Tabular::SET_LINE_TOP, "set-line-top", true },
129         { Tabular::SET_LINE_BOTTOM, "set-line-bottom", true },
130         { Tabular::SET_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 cidx = cellIndex(r, c);
1166                 // because of multicolumns
1167                 toggleFixedWidth(cur, cellInset(cidx).get(),
1168                                  !getPWidth(cidx).zero());
1169                 if (isMultiRow(cidx))
1170                         setAlignment(cidx, 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,
2178                           list<col_type> columns) const
2179 {
2180         // we only output complete row lines and the 1st row here, the rest
2181         // is done in Tabular::TeXBottomHLine(...)
2182
2183         // get for each column the topline (if any)
2184         map<col_type, bool> topline;
2185         col_type nset = 0;
2186         for (auto const & c : columns) {
2187                 topline[c] = topLine(cellIndex(row, c));
2188                 // If cell is part of a multirow and not the first cell of the
2189                 // multirow, no line must be drawn.
2190                 if (row != 0)
2191                         if (isMultiRow(cellIndex(row, c))
2192                             && cell_info[row][c].multirow != CELL_BEGIN_OF_MULTIROW)
2193                                 topline[c] = false;
2194                 if (topline.find(c) != topline.end() && topline.find(c)->second)
2195                         ++nset;
2196         }
2197
2198         // do nothing if empty first row, or incomplete row line after
2199         if ((row == 0 && nset == 0) || (row > 0 && nset != ncols()))
2200                 return;
2201
2202         // only output complete row lines and the 1st row's clines
2203         if (nset == ncols()) {
2204                 if (use_booktabs) {
2205                         os << (row == 0 ? "\\toprule " : "\\midrule ");
2206                 } else {
2207                         os << "\\hline ";
2208                 }
2209         } else if (row == 0) {
2210                 for (auto & c : columns) {
2211                         if (topline.find(c)->second) {
2212                                 col_type offset = 0;
2213                                 for (col_type j = 0 ; j < c; ++j)
2214                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2215                                                 ++offset;
2216
2217                                 //babel makes the "-" character an active one, so we have to suppress this here
2218                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
2219                                 if (lang == "slovak" || lang == "czech")
2220                                         os << "\\expandafter" << (use_booktabs ? "\\cmidrule" : "\\cline")
2221                                         << "\\expandafter{\\expandafter" << c + 1 + offset << "\\string-";
2222                                 else
2223                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 + offset << '-';
2224
2225                                 col_type cstart = c;
2226                                 for ( ; c < ncols() && topline.find(c)->second; ++c) {}
2227
2228                                 for (col_type j = cstart ; j < c ; ++j)
2229                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2230                                                 ++offset;
2231
2232                                 os << c + offset << "} ";
2233                         }
2234                 }
2235         }
2236         os << "\n";
2237 }
2238
2239
2240 void Tabular::TeXBottomHLine(otexstream & os, row_type row, string const & lang,
2241                              list<col_type> columns) const
2242 {
2243         // we output bottomlines of row r and the toplines of row r+1
2244         // if the latter do not span the whole tabular
2245
2246         // get the bottomlines of row r, and toplines in next row
2247         bool lastrow = row == nrows() - 1;
2248         map<col_type, bool> bottomline, topline;
2249         bool nextrowset = true;
2250         for (auto const & c : columns) {
2251                 bottomline[c] = bottomLine(cellIndex(row, c));
2252                 topline[c] =  !lastrow && topLine(cellIndex(row + 1, c));
2253                 // If cell is part of a multirow and not the last cell of the
2254                 // multirow, no line must be drawn.
2255                 if (!lastrow)
2256                         if (isMultiRow(cellIndex(row, c))
2257                             && isMultiRow(cellIndex(row + 1, c))
2258                             && cell_info[row + 1][c].multirow != CELL_BEGIN_OF_MULTIROW) {
2259                                 bottomline[c] = false;
2260                                 topline[c] = false;
2261                                 }
2262                 nextrowset &= topline.find(c) != topline.end() && topline.find(c)->second;
2263         }
2264
2265         // combine this row's bottom lines and next row's toplines if necessary
2266         col_type nset = 0;
2267         for (auto const & c : columns) {
2268                 if (!nextrowset)
2269                         bottomline[c] = bottomline.find(c)->second || topline.find(c)->second;
2270                 if (bottomline.find(c)->second)
2271                         ++nset;
2272         }
2273
2274         // do nothing if empty, OR incomplete row line with a topline in next row
2275         if (nset == 0 || (nextrowset && nset != ncols()))
2276                 return;
2277
2278         if (nset == ncols()) {
2279                 if (use_booktabs)
2280                         os << (lastrow ? "\\bottomrule" : "\\midrule");
2281                 else
2282                         os << "\\hline ";
2283         } else {
2284                 for (auto & c : columns) {
2285                         if (bottomline.find(c)->second) {
2286                                 col_type offset = 0;
2287                                 for (col_type j = 0 ; j < c; ++j)
2288                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2289                                                 ++offset;
2290
2291                                 //babel makes the "-" character an active one, so we have to suppress this here
2292                                 //see http://groups.google.com/group/comp.text.tex/browse_thread/thread/af769424a4a0f289#
2293                                 if (lang == "slovak" || lang == "czech")
2294                                         os << "\\expandafter" << (use_booktabs ? "\\cmidrule" : "\\cline")
2295                                         << "\\expandafter{\\expandafter" << c + 1 + offset << "\\string-";
2296                                 else
2297                                         os << (use_booktabs ? "\\cmidrule{" : "\\cline{") << c + 1 + offset << '-';
2298
2299                                 col_type cstart = c;
2300                                 for ( ; c < ncols() && bottomline.find(c)->second; ++c) {}
2301
2302                                 for (col_type j = cstart ; j < c ; ++j)
2303                                         if (column_info[j].alignment == LYX_ALIGN_DECIMAL)
2304                                                 ++offset;
2305
2306                                 os << c + offset << "} ";
2307                         }
2308                 }
2309         }
2310         os << "\n";
2311 }
2312
2313
2314 void Tabular::TeXCellPreamble(otexstream & os, idx_type cell,
2315                               bool & ismulticol, bool & ismultirow,
2316                               bool const bidi) const
2317 {
2318         row_type const r = cellRow(cell);
2319         if (is_long_tabular && row_info[r].caption)
2320                 return;
2321
2322         Tabular::VAlignment valign =  getVAlignment(cell, !isMultiColumn(cell));
2323         LyXAlignment align = getAlignment(cell, !isMultiColumn(cell));
2324         // figure out how to set the lines
2325         // we always set double lines to the right of the cell
2326         // or left in bidi RTL, respectively.
2327         col_type const c = cellColumn(cell);
2328         col_type const nextcol = c + columnSpan(cell);
2329         bool const decimal = column_info[c].alignment == LYX_ALIGN_DECIMAL;
2330         bool colright = columnRightLine(c);
2331         bool colleft = columnLeftLine(c);
2332         bool nextcolleft = nextcol < ncols() && columnLeftLine(nextcol);
2333         bool nextcellleft = nextcol < ncols()
2334                 && leftLine(cellIndex(r, nextcol));
2335         bool coldouble = colright && nextcolleft;
2336         bool celldouble = rightLine(cell) && nextcellleft;
2337
2338         ismulticol = (isMultiColumn(cell)
2339                       || (c == 0 && colleft != leftLine(cell))
2340                       || ((colright || nextcolleft) && !rightLine(cell) && !nextcellleft)
2341                       || (!colright && !nextcolleft && (rightLine(cell) || nextcellleft))
2342                       || (coldouble != celldouble))
2343                      && !decimal;
2344
2345         // we center in multicol when no decimal point
2346         if (decimal) {
2347                 docstring const align_d = column_info[c].decimal_point;
2348                 DocIterator const dit = separatorPos(cellInset(cell), align_d);
2349                 bool const nosep = !dit;
2350                 ismulticol |= nosep;
2351                 celldouble &= nosep;
2352         }
2353
2354         // up counter by 1 for each decimally aligned col since they use 2 latex cols
2355         int latexcolspan = columnSpan(cell);
2356         for (col_type col = c; col < c + columnSpan(cell); ++col)
2357                 if (column_info[col].alignment == LYX_ALIGN_DECIMAL)
2358                         ++latexcolspan;
2359
2360         if (ismulticol) {
2361                 os << "\\multicolumn{" << latexcolspan << "}{";
2362                 if (((bidi && c == getLastCellInRow(cellRow(0)) && rightLine(cell))
2363                      || (!bidi && c == 0 && leftLine(cell))))
2364                         os << '|';
2365                 if (bidi && celldouble)
2366                         // add extra vertical line if we want a double one
2367                         os << '|';
2368                 if (!cellInfo(cell).align_special.empty()) {
2369                         os << cellInfo(cell).align_special;
2370                 } else {
2371                         if (!getPWidth(cell).zero()) {
2372                                 switch (align) {
2373                                 case LYX_ALIGN_LEFT:
2374                                         os << ">{\\raggedright}";
2375                                         break;
2376                                 case LYX_ALIGN_RIGHT:
2377                                         os << ">{\\raggedleft}";
2378                                         break;
2379                                 case LYX_ALIGN_CENTER:
2380                                         os << ">{\\centering}";
2381                                         break;
2382                                 default:
2383                                         break;
2384                                 }
2385                                 switch (valign) {
2386                                 case LYX_VALIGN_TOP:
2387                                         os << 'p';
2388                                         break;
2389                                 case LYX_VALIGN_MIDDLE:
2390                                         os << 'm';
2391                                         break;
2392                                 case LYX_VALIGN_BOTTOM:
2393                                         os << 'b';
2394                                         break;
2395                                 }
2396                                 os << '{'
2397                                    << from_ascii(getPWidth(cell).asLatexString())
2398                                    << '}';
2399                         } else {
2400                                 switch (align) {
2401                                 case LYX_ALIGN_LEFT:
2402                                         os << 'l';
2403                                         break;
2404                                 case LYX_ALIGN_RIGHT:
2405                                         os << 'r';
2406                                         break;
2407                                 default:
2408                                         os << 'c';
2409                                         break;
2410                                 }
2411                         } // end if else !getPWidth
2412                 } // end if else !cellinfo_of_cell
2413                 if ((bidi && leftLine(cell)) || (!bidi && rightLine(cell)) || nextcellleft)
2414                         os << '|';
2415                 if (!bidi && celldouble)
2416                         // add extra vertical line if we want a double one
2417                         os << '|';
2418                 os << "}{";
2419         } // end if ismulticol
2420
2421         // we only need code for the first multirow cell
2422         ismultirow = isMultiRow(cell);
2423         if (ismultirow) {
2424                 os << "\\multirow{" << rowSpan(cell) << "}{";
2425                 if (!getPWidth(cell).zero())
2426                         os << from_ascii(getPWidth(cell).asLatexString());
2427                 else
2428                         // we need to set a default value
2429                         os << "*";
2430                 os << "}";
2431                 if (!getMROffset(cell).zero())
2432                         os << "[" << from_ascii(getMROffset(cell).asLatexString()) << "]";
2433                 os << "{";
2434         } // end if ismultirow
2435
2436         if (getRotateCell(cell) != 0)
2437                 os << "\\begin{turn}{" << convert<string>(getRotateCell(cell)) << "}\n";
2438
2439         if (getUsebox(cell) == BOX_PARBOX) {
2440                 os << "\\parbox[";
2441                 switch (valign) {
2442                 case LYX_VALIGN_TOP:
2443                         os << 't';
2444                         break;
2445                 case LYX_VALIGN_MIDDLE:
2446                         os << 'c';
2447                         break;
2448                 case LYX_VALIGN_BOTTOM:
2449                         os << 'b';
2450                         break;
2451                 }
2452                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2453                    << "}{";
2454         } else if (getUsebox(cell) == BOX_MINIPAGE) {
2455                 os << "\\begin{minipage}[";
2456                 switch (valign) {
2457                 case LYX_VALIGN_TOP:
2458                         os << 't';
2459                         break;
2460                 case LYX_VALIGN_MIDDLE:
2461                         os << 'm';
2462                         break;
2463                 case LYX_VALIGN_BOTTOM:
2464                         os << 'b';
2465                         break;
2466                 }
2467                 os << "]{" << from_ascii(getPWidth(cell).asLatexString())
2468                    << "}\n";
2469         }
2470 }
2471
2472
2473 void Tabular::TeXCellPostamble(otexstream & os, idx_type cell,
2474                                bool ismulticol, bool ismultirow) const
2475 {
2476         row_type const r = cellRow(cell);
2477         if (is_long_tabular && row_info[r].caption)
2478                 return;
2479
2480         // usual cells
2481         if (getUsebox(cell) == BOX_PARBOX)
2482                 os << '}';
2483         else if (getUsebox(cell) == BOX_MINIPAGE)
2484                 os << breakln << "\\end{minipage}";
2485         if (getRotateCell(cell) != 0)
2486                 os << breakln << "\\end{turn}";
2487         if (ismultirow)
2488                 os << '}';
2489         if (ismulticol)
2490                 os << '}';
2491 }
2492
2493
2494 void Tabular::TeXLongtableHeaderFooter(otexstream & os,
2495                                        OutputParams const & runparams,
2496                                        list<col_type> columns) const
2497 {
2498         if (!is_long_tabular)
2499                 return;
2500
2501         // caption handling
2502         // output caption which is in no header or footer
2503         if (haveLTCaption()) {
2504                 for (row_type r = 0; r < nrows(); ++r) {
2505                         if (row_info[r].caption &&
2506                             !row_info[r].endfirsthead && !row_info[r].endhead &&
2507                             !row_info[r].endfoot && !row_info[r].endlastfoot)
2508                                 TeXRow(os, r, runparams, columns);
2509                 }
2510         }
2511         // output first header info
2512         if (haveLTFirstHead()) {
2513                 if (endfirsthead.topDL)
2514                         os << "\\hline\n";
2515                 for (row_type r = 0; r < nrows(); ++r) {
2516                         if (row_info[r].endfirsthead)
2517                                 TeXRow(os, r, runparams, columns);
2518                 }
2519                 if (endfirsthead.bottomDL)
2520                         os << "\\hline\n";
2521                 os << "\\endfirsthead\n";
2522         }
2523         // output header info
2524         if (haveLTHead()) {
2525                 if (endfirsthead.empty && !haveLTFirstHead())
2526                         os << "\\endfirsthead\n";
2527                 if (endhead.topDL)
2528                         os << "\\hline\n";
2529                 for (row_type r = 0; r < nrows(); ++r) {
2530                         if (row_info[r].endhead)
2531                                 TeXRow(os, r, runparams, columns);
2532                 }
2533                 if (endhead.bottomDL)
2534                         os << "\\hline\n";
2535                 os << "\\endhead\n";
2536         }
2537         // output footer info
2538         if (haveLTFoot()) {
2539                 if (endfoot.topDL)
2540                         os << "\\hline\n";
2541                 for (row_type r = 0; r < nrows(); ++r) {
2542                         if (row_info[r].endfoot)
2543                                 TeXRow(os, r, runparams, columns);
2544                 }
2545                 if (endfoot.bottomDL)
2546                         os << "\\hline\n";
2547                 os << "\\endfoot\n";
2548                 if (endlastfoot.empty && !haveLTLastFoot())
2549                         os << "\\endlastfoot\n";
2550         }
2551         // output lastfooter info
2552         if (haveLTLastFoot()) {
2553                 if (endlastfoot.topDL)
2554                         os << "\\hline\n";
2555                 for (row_type r = 0; r < nrows(); ++r) {
2556                         if (row_info[r].endlastfoot)
2557                                 TeXRow(os, r, runparams, columns);
2558                 }
2559                 if (endlastfoot.bottomDL)
2560                         os << "\\hline\n";
2561                 os << "\\endlastfoot\n";
2562         }
2563 }
2564
2565
2566 bool Tabular::isValidRow(row_type row) const
2567 {
2568         if (!is_long_tabular)
2569                 return true;
2570         return !row_info[row].endhead && !row_info[row].endfirsthead
2571                 && !row_info[row].endfoot && !row_info[row].endlastfoot
2572                 && !row_info[row].caption;
2573 }
2574
2575
2576 void Tabular::TeXRow(otexstream & os, row_type row,
2577                      OutputParams const & runparams,
2578                      list<col_type> columns) const
2579 {
2580         idx_type cell = cellIndex(row, 0);
2581         InsetTableCell const * cinset = cellInset(cell);
2582         Paragraph const & cpar = cinset->paragraphs().front();
2583         string const clang = cpar.getParLanguage(buffer().params())->lang();
2584
2585         //output the top line
2586         TeXTopHLine(os, row, clang, columns);
2587
2588         if (row_info[row].top_space_default) {
2589                 if (use_booktabs)
2590                         os << "\\addlinespace\n";
2591                 else
2592                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2593         } else if(!row_info[row].top_space.zero()) {
2594                 if (use_booktabs)
2595                         os << "\\addlinespace["
2596                            << from_ascii(row_info[row].top_space.asLatexString())
2597                            << "]\n";
2598                 else {
2599                         os << "\\noalign{\\vskip"
2600                            << from_ascii(row_info[row].top_space.asLatexString())
2601                            << "}\n";
2602                 }
2603         }
2604         bool ismulticol = false;
2605         bool ismultirow = false;
2606
2607         // The bidi package (loaded by polyglossia) reverses RTL table columns
2608         bool const bidi_rtl =
2609                 runparams.local_font->isRightToLeft()
2610                 && runparams.use_polyglossia;
2611         idx_type lastcell =
2612                 bidi_rtl ? getFirstCellInRow(row) : getLastCellInRow(row);
2613
2614         for (auto const & c : columns) {
2615                 if (isPartOfMultiColumn(row, c))
2616                         continue;
2617
2618                 cell = cellIndex(row, c);
2619
2620                 if (isPartOfMultiRow(row, c)
2621                     && column_info[c].alignment != LYX_ALIGN_DECIMAL) {
2622                         if (cell != lastcell)
2623                                 os << " & ";
2624                         continue;
2625                 }
2626
2627                 TeXCellPreamble(os, cell, ismulticol, ismultirow, bidi_rtl);
2628                 InsetTableCell const * inset = cellInset(cell);
2629
2630                 Paragraph const & par = inset->paragraphs().front();
2631
2632                 os.texrow().forceStart(par.id(), 0);
2633
2634                 bool rtl = par.isRTL(buffer().params())
2635                         && !par.empty()
2636                         && getPWidth(cell).zero()
2637                         && !runparams.use_polyglossia;
2638
2639                 if (rtl) {
2640                         string const lang =
2641                                 par.getParLanguage(buffer().params())->lang();
2642                         if (lang == "farsi")
2643                                 os << "\\textFR{";
2644                         else if (lang == "arabic_arabi")
2645                                 os << "\\textAR{";
2646                         // currently, remaining RTL languages are
2647                         // arabic_arabtex and hebrew
2648                         else
2649                                 os << "\\R{";
2650                 }
2651                 // pass to the OutputParams that we are in a cell and
2652                 // which alignment we have set.
2653                 // InsetNewline needs this context information.
2654                 OutputParams newrp(runparams);
2655                 newrp.inTableCell = (getAlignment(cell) == LYX_ALIGN_BLOCK)
2656                                     ? OutputParams::PLAIN
2657                                     : OutputParams::ALIGNED;
2658
2659                 if (getAlignment(cell) == LYX_ALIGN_DECIMAL) {
2660                         // copy cell and split in 2
2661                         InsetTableCell head = InsetTableCell(*cellInset(cell));
2662                         head.setBuffer(const_cast<Buffer &>(buffer()));
2663                         DocIterator dit = cellInset(cell)->getText(0)->macrocontextPosition();
2664                         dit.pop_back();
2665                         dit.push_back(CursorSlice(head));
2666                         head.setMacrocontextPositionRecursive(dit);
2667                         bool hassep = false;
2668                         InsetTableCell tail = splitCell(head, column_info[c].decimal_point, hassep);
2669                         if (hassep) {
2670                                 tail.setBuffer(head.buffer());
2671                                 dit.pop_back();
2672                                 dit.push_back(CursorSlice(tail));
2673                                 tail.setMacrocontextPositionRecursive(dit);
2674                         }
2675                         if (bidi_rtl) {
2676                                 if (hassep) {
2677                                         tail.latex(os, newrp);
2678                                         os << '&';
2679                                 }
2680                                 head.latex(os, newrp);
2681                         } else {
2682                                 head.latex(os, newrp);
2683                                 if (hassep) {
2684                                         os << '&';
2685                                         tail.latex(os, newrp);
2686                                 }
2687                         }
2688                 } else if (ltCaption(row)) {
2689                         // Inside longtable caption rows, we must only output the caption inset
2690                         // with its content and omit anything outside of that (see #10791)
2691                         InsetIterator it = inset_iterator_begin(*const_cast<InsetTableCell *>(inset));
2692                         InsetIterator i_end = inset_iterator_end(*const_cast<InsetTableCell *>(inset));
2693                         for (; it != i_end; ++it) {
2694                                 if (it->lyxCode() != CAPTION_CODE)
2695                                         continue;
2696                                 it->latex(os, runparams);
2697                                 break;
2698                         }
2699                 } else if (!isPartOfMultiRow(row, c)) {
2700                         if (!runparams.nice)
2701                                 os.texrow().start(par.id(), 0);
2702                         inset->latex(os, newrp);
2703                 }
2704
2705                 runparams.encoding = newrp.encoding;
2706                 if (rtl)
2707                         os << '}';
2708
2709                 TeXCellPostamble(os, cell, ismulticol, ismultirow);
2710                 if (cell != lastcell) { // not last cell in row
2711                         if (runparams.nice)
2712                                 os << " & ";
2713                         else
2714                                 os << " &\n";
2715                 }
2716         }
2717         os << "\\tabularnewline";
2718         if (row_info[row].bottom_space_default) {
2719                 if (use_booktabs)
2720                         os << "\\addlinespace";
2721                 else
2722                         os << "[\\doublerulesep]";
2723         } else if (!row_info[row].bottom_space.zero()) {
2724                 if (use_booktabs)
2725                         os << "\\addlinespace";
2726                 os << '['
2727                    << from_ascii(row_info[row].bottom_space.asLatexString())
2728                    << ']';
2729         }
2730         os << '\n';
2731
2732         //output the bottom line
2733         TeXBottomHLine(os, row, clang, columns);
2734
2735         if (row_info[row].interline_space_default) {
2736                 if (use_booktabs)
2737                         os << "\\addlinespace\n";
2738                 else
2739                         os << "\\noalign{\\vskip\\doublerulesep}\n";
2740         } else if (!row_info[row].interline_space.zero()) {
2741                 if (use_booktabs)
2742                         os << "\\addlinespace["
2743                            << from_ascii(row_info[row].interline_space.asLatexString())
2744                            << "]\n";
2745                 else
2746                         os << "\\noalign{\\vskip"
2747                            << from_ascii(row_info[row].interline_space.asLatexString())
2748                            << "}\n";
2749         }
2750 }
2751
2752
2753 void Tabular::latex(otexstream & os, OutputParams const & runparams) const
2754 {
2755         bool const is_tabular_star = !tabular_width.zero();
2756         TexRow::RowEntry pos = TexRow::textEntry(runparams.lastid, runparams.lastpos);
2757
2758         //+---------------------------------------------------------------------
2759         //+                      first the opening preamble                    +
2760         //+---------------------------------------------------------------------
2761
2762         os << safebreakln;
2763         if (!TexRow::isNone(pos))
2764                 os.texrow().start(pos);
2765
2766         if (rotate != 0) {
2767                 if (is_long_tabular)
2768                         os << "\\begin{landscape}\n";
2769                 else
2770                         os << "\\begin{turn}{" << convert<string>(rotate) << "}\n";
2771         }
2772
2773         if (is_long_tabular) {
2774                 os << "\\begin{longtable}";
2775                 switch (longtabular_alignment) {
2776                 case LYX_LONGTABULAR_ALIGN_LEFT:
2777                         os << "[l]";
2778                         break;
2779                 case LYX_LONGTABULAR_ALIGN_CENTER:
2780                         os << "[c]";
2781                         break;
2782                 case LYX_LONGTABULAR_ALIGN_RIGHT:
2783                         os << "[r]";
2784                         break;
2785                 }
2786         } else {
2787                 if (is_tabular_star)
2788                         os << "\\begin{tabular*}{" << from_ascii(tabular_width.asLatexString()) << "}";
2789                 else
2790                         os << "\\begin{tabular}";
2791                 switch (tabular_valignment) {
2792                 case LYX_VALIGN_TOP:
2793                         os << "[t]";
2794                         break;
2795                 case LYX_VALIGN_MIDDLE:
2796                         break;
2797                 case LYX_VALIGN_BOTTOM:
2798                         os << "[b]";
2799                         break;
2800                 }
2801         }
2802
2803         os << "{";
2804
2805         if (is_tabular_star)
2806                 os << "@{\\extracolsep{\\fill}}";
2807
2808         // The bidi package (loaded by polyglossia) swaps the column
2809         // order for RTL (#9686). Thus we use this list.
2810         bool const bidi_rtl =
2811                 runparams.local_font->isRightToLeft()
2812                 && runparams.use_polyglossia;
2813         list<col_type> columns;
2814         for (col_type cl = 0; cl < ncols(); ++cl) {
2815                 if (bidi_rtl)
2816                         columns.push_front(cl);
2817                 else
2818                         columns.push_back(cl);
2819         }
2820
2821         for (auto const & c : columns) {
2822                 if ((bidi_rtl && columnRightLine(c)) || (!bidi_rtl && columnLeftLine(c)))
2823                         os << '|';
2824                 if (!column_info[c].align_special.empty()) {
2825                         os << column_info[c].align_special;
2826                 } else {
2827                         if (!column_info[c].p_width.zero()) {
2828                                 bool decimal = false;
2829                                 switch (column_info[c].alignment) {
2830                                 case LYX_ALIGN_LEFT:
2831                                         os << ">{\\raggedright}";
2832                                         break;
2833                                 case LYX_ALIGN_RIGHT:
2834                                         os << ">{\\raggedleft}";
2835                                         break;
2836                                 case LYX_ALIGN_CENTER:
2837                                         os << ">{\\centering}";
2838                                         break;
2839                                 case LYX_ALIGN_NONE:
2840                                 case LYX_ALIGN_BLOCK:
2841                                 case LYX_ALIGN_LAYOUT:
2842                                 case LYX_ALIGN_SPECIAL:
2843                                         break;
2844                                 case LYX_ALIGN_DECIMAL: {
2845                                         if (bidi_rtl)
2846                                                 os << ">{\\raggedright}";
2847                                         else
2848                                                 os << ">{\\raggedleft}";
2849                                         decimal = true;
2850                                         break;
2851                                 }
2852                                 }
2853
2854                                 char valign = 'p';
2855                                 switch (column_info[c].valignment) {
2856                                 case LYX_VALIGN_TOP:
2857                                         // this is the default
2858                                         break;
2859                                 case LYX_VALIGN_MIDDLE:
2860                                         valign = 'm';
2861                                         break;
2862                                 case LYX_VALIGN_BOTTOM:
2863                                         valign = 'b';
2864                                         break;
2865                                 }
2866                                 os << valign;
2867
2868                                 // Fixed-width cells with alignment at decimal separator
2869                                 // are output as two cells of half the width with the decimal
2870                                 // separator as column sep. This effectively puts the content
2871                                 // centered, which differs from the normal decimal sep alignment
2872                                 // and is not ideal, but we cannot do better ATM (see #9568).
2873                                 // FIXME: Implement proper decimal sep alignment, e.g. via siunitx.
2874                                 if (decimal) {
2875                                         docstring const halffixedwith =
2876                                                 from_ascii(Length(column_info[c].p_width.value() / 2,
2877                                                                   column_info[c].p_width.unit()).asLatexString());
2878                                         os << '{'
2879                                            << halffixedwith
2880                                            << '}'
2881                                            << "@{\\extracolsep{0pt}" << column_info[c].decimal_point << "}"
2882                                            << valign
2883                                            << '{'
2884                                            << halffixedwith
2885                                            << '}';
2886                                 } else
2887                                         os << '{'
2888                                            << from_ascii(column_info[c].p_width.asLatexString())
2889                                            << '}';
2890                         } else {
2891                                 switch (column_info[c].alignment) {
2892                                 case LYX_ALIGN_LEFT:
2893                                         os << 'l';
2894                                         break;
2895                                 case LYX_ALIGN_RIGHT:
2896                                         os << 'r';
2897                                         break;
2898                                 case LYX_ALIGN_DECIMAL:
2899                                         os << "r@{\\extracolsep{0pt}" << column_info[c].decimal_point << "}l";
2900                                         break;
2901                                 default:
2902                                         os << 'c';
2903                                         break;
2904                                 }
2905                         } // end if else !column_info[i].p_width
2906                 } // end if else !column_info[i].align_special
2907                 if ((bidi_rtl && columnLeftLine(c)) || (!bidi_rtl && columnRightLine(c)))
2908                         os << '|';
2909         }
2910         os << "}\n";
2911
2912         TeXLongtableHeaderFooter(os, runparams, columns);
2913
2914         //+---------------------------------------------------------------------
2915         //+                      the single row and columns (cells)            +
2916         //+---------------------------------------------------------------------
2917
2918         for (row_type r = 0; r < nrows(); ++r) {
2919                 if (isValidRow(r)) {
2920                         TeXRow(os, r, runparams, columns);
2921                         if (is_long_tabular && row_info[r].newpage)
2922                                 os << "\\newpage\n";
2923                 }
2924         }
2925
2926         //+---------------------------------------------------------------------
2927         //+                      the closing of the tabular                    +
2928         //+---------------------------------------------------------------------
2929
2930         if (is_long_tabular)
2931                 os << "\\end{longtable}";
2932         else {
2933                 if (is_tabular_star)
2934                         os << "\\end{tabular*}";
2935                 else
2936                         os << "\\end{tabular}";
2937         }
2938
2939         if (rotate != 0) {
2940                 if (is_long_tabular)
2941                         os << breakln << "\\end{landscape}";
2942                 else
2943                         os << breakln << "\\end{turn}";
2944         }
2945
2946         if (!TexRow::isNone(pos))
2947                 os.texrow().start(pos);
2948 }
2949
2950
2951 int Tabular::docbookRow(odocstream & os, row_type row,
2952                            OutputParams const & runparams) const
2953 {
2954         int ret = 0;
2955         idx_type cell = getFirstCellInRow(row);
2956
2957         os << "<row>\n";
2958         for (col_type c = 0; c < ncols(); ++c) {
2959                 if (isPartOfMultiColumn(row, c))
2960                         continue;
2961
2962                 os << "<entry align=\"";
2963                 switch (getAlignment(cell)) {
2964                 case LYX_ALIGN_LEFT:
2965                         os << "left";
2966                         break;
2967                 case LYX_ALIGN_RIGHT:
2968                         os << "right";
2969                         break;
2970                 default:
2971                         os << "center";
2972                         break;
2973                 }
2974
2975                 os << "\" valign=\"";
2976                 switch (getVAlignment(cell)) {
2977                 case LYX_VALIGN_TOP:
2978                         os << "top";
2979                         break;
2980                 case LYX_VALIGN_BOTTOM:
2981                         os << "bottom";
2982                         break;
2983                 case LYX_VALIGN_MIDDLE:
2984                         os << "middle";
2985                 }
2986                 os << '"';
2987
2988                 if (isMultiColumn(cell)) {
2989                         os << " namest=\"col" << c << "\" ";
2990                         os << "nameend=\"col" << c + columnSpan(cell) - 1 << '"';
2991                 }
2992
2993                 os << '>';
2994                 ret += cellInset(cell)->docbook(os, runparams);
2995                 os << "</entry>\n";
2996                 ++cell;
2997         }
2998         os << "</row>\n";
2999         return ret;
3000 }
3001
3002
3003 int Tabular::docbook(odocstream & os, OutputParams const & runparams) const
3004 {
3005         int ret = 0;
3006
3007         //+---------------------------------------------------------------------
3008         //+                      first the opening preamble                    +
3009         //+---------------------------------------------------------------------
3010
3011         os << "<tgroup cols=\"" << ncols()
3012            << "\" colsep=\"1\" rowsep=\"1\">\n";
3013
3014         for (col_type c = 0; c < ncols(); ++c) {
3015                 os << "<colspec colname=\"col" << c << "\" align=\"";
3016                 switch (column_info[c].alignment) {
3017                 case LYX_ALIGN_LEFT:
3018                         os << "left";
3019                         break;
3020                 case LYX_ALIGN_RIGHT:
3021                         os << "right";
3022                         break;
3023                 default:
3024                         os << "center";
3025                         break;
3026                 }
3027                 os << '"';
3028                 if (runparams.flavor == OutputParams::XML)
3029                         os << '/';
3030                 os << ">\n";
3031                 ++ret;
3032         }
3033
3034         //+---------------------------------------------------------------------
3035         //+                      Long Tabular case                             +
3036         //+---------------------------------------------------------------------
3037
3038         // output caption info
3039         // The caption flag wins over head/foot
3040         if (haveLTCaption()) {
3041                 os << "<caption>\n";
3042                 ++ret;
3043                 for (row_type r = 0; r < nrows(); ++r) {
3044                         if (row_info[r].caption) {
3045                                 ret += docbookRow(os, r, runparams);
3046                         }
3047                 }
3048                 os << "</caption>\n";
3049                 ++ret;
3050         }
3051         // output header info
3052         if (haveLTHead(false) || haveLTFirstHead(false)) {
3053                 os << "<thead>\n";
3054                 ++ret;
3055                 for (row_type r = 0; r < nrows(); ++r) {
3056                         if ((row_info[r].endhead || row_info[r].endfirsthead) &&
3057                             !row_info[r].caption) {
3058                                 ret += docbookRow(os, r, runparams);
3059                         }
3060                 }
3061                 os << "</thead>\n";
3062                 ++ret;
3063         }
3064         // output footer info
3065         if (haveLTFoot(false) || haveLTLastFoot(false)) {
3066                 os << "<tfoot>\n";
3067                 ++ret;
3068                 for (row_type r = 0; r < nrows(); ++r) {
3069                         if ((row_info[r].endfoot || row_info[r].endlastfoot) &&
3070                             !row_info[r].caption) {
3071                                 ret += docbookRow(os, r, runparams);
3072                         }
3073                 }
3074                 os << "</tfoot>\n";
3075                 ++ret;
3076         }
3077
3078         //+---------------------------------------------------------------------
3079         //+                      the single row and columns (cells)            +
3080         //+---------------------------------------------------------------------
3081
3082         os << "<tbody>\n";
3083         ++ret;
3084         for (row_type r = 0; r < nrows(); ++r) {
3085                 if (isValidRow(r)) {
3086                         ret += docbookRow(os, r, runparams);
3087                 }
3088         }
3089         os << "</tbody>\n";
3090         ++ret;
3091         //+---------------------------------------------------------------------
3092         //+                      the closing of the tabular                    +
3093         //+---------------------------------------------------------------------
3094
3095         os << "</tgroup>";
3096         ++ret;
3097
3098         return ret;
3099 }
3100
3101
3102 docstring Tabular::xhtmlRow(XHTMLStream & xs, row_type row,
3103                            OutputParams const & runparams, bool header) const
3104 {
3105         docstring ret;
3106         string const celltag = header ? "th" : "td";
3107         idx_type cell = getFirstCellInRow(row);
3108
3109         xs << html::StartTag("tr");
3110         for (col_type c = 0; c < ncols(); ++c) {
3111                 if (isPartOfMultiColumn(row, c) || isPartOfMultiRow(row, c))
3112                         continue;
3113
3114                 stringstream attr;
3115
3116                 Length const cwidth = column_info[c].p_width;
3117                 if (!cwidth.zero()) {
3118                         string const hwidth = cwidth.asHTMLString();
3119                         attr << "style =\"width: " << hwidth << ";\" ";
3120                 }
3121
3122                 attr << "align='";
3123                 switch (getAlignment(cell)) {
3124                 case LYX_ALIGN_LEFT:
3125                         attr << "left";
3126                         break;
3127                 case LYX_ALIGN_RIGHT:
3128                         attr << "right";
3129                         break;
3130                 default:
3131                         attr << "center";
3132                         break;
3133                 }
3134                 attr << "'";
3135                 attr << " valign='";
3136                 switch (getVAlignment(cell)) {
3137                 case LYX_VALIGN_TOP:
3138                         attr << "top";
3139                         break;
3140                 case LYX_VALIGN_BOTTOM:
3141                         attr << "bottom";
3142                         break;
3143                 case LYX_VALIGN_MIDDLE:
3144                         attr << "middle";
3145                 }
3146                 attr << "'";
3147
3148                 if (isMultiColumn(cell))
3149                         attr << " colspan='" << columnSpan(cell) << "'";
3150                 else if (isMultiRow(cell))
3151                         attr << " rowspan='" << rowSpan(cell) << "'";
3152
3153                 xs << html::StartTag(celltag, attr.str(), true) << html::CR();
3154                 ret += cellInset(cell)->xhtml(xs, runparams);
3155                 xs << html::EndTag(celltag) << html::CR();
3156                 ++cell;
3157         }
3158         xs << html::EndTag("tr");
3159         return ret;
3160 }
3161
3162
3163 docstring Tabular::xhtml(XHTMLStream & xs, OutputParams const & runparams) const
3164 {
3165         docstring ret;
3166
3167         if (is_long_tabular) {
3168                 // we'll wrap it in a div, so as to deal with alignment
3169                 string align;
3170                 switch (longtabular_alignment) {
3171                 case LYX_LONGTABULAR_ALIGN_LEFT:
3172                         align = "left";
3173                         break;
3174                 case LYX_LONGTABULAR_ALIGN_CENTER:
3175                         align = "center";
3176                         break;
3177                 case LYX_LONGTABULAR_ALIGN_RIGHT:
3178                         align = "right";
3179                         break;
3180                 }
3181                 xs << html::StartTag("div", "class='longtable' style='text-align: " + align + ";'")
3182                    << html::CR();
3183                 // The caption flag wins over head/foot
3184                 if (haveLTCaption()) {
3185                         xs << html::StartTag("div", "class='longtable-caption' style='text-align: " + align + ";'")
3186                            << html::CR();
3187                         for (row_type r = 0; r < nrows(); ++r)
3188                                 if (row_info[r].caption)
3189                                         ret += xhtmlRow(xs, r, runparams);
3190                         xs << html::EndTag("div") << html::CR();
3191                 }
3192         }
3193
3194         xs << html::StartTag("table") << html::CR();
3195
3196         // output header info
3197         bool const havefirsthead = haveLTFirstHead(false);
3198         // if we have a first head, then we are going to ignore the
3199         // headers for the additional pages, since there aren't any
3200         // in XHTML. this test accomplishes that.
3201         bool const havehead = !havefirsthead && haveLTHead(false);
3202         if (havehead || havefirsthead) {
3203                 xs << html::StartTag("thead") << html::CR();
3204                 for (row_type r = 0; r < nrows(); ++r) {
3205                         if (((havefirsthead && row_info[r].endfirsthead) ||
3206                              (havehead && row_info[r].endhead)) &&
3207                             !row_info[r].caption) {
3208                                 ret += xhtmlRow(xs, r, runparams, true);
3209                         }
3210                 }
3211                 xs << html::EndTag("thead") << html::CR();
3212         }
3213         // output footer info
3214         bool const havelastfoot = haveLTLastFoot(false);
3215         // as before.
3216         bool const havefoot = !havelastfoot && haveLTFoot(false);
3217         if (havefoot || havelastfoot) {
3218                 xs << html::StartTag("tfoot") << html::CR();
3219                 for (row_type r = 0; r < nrows(); ++r) {
3220                         if (((havelastfoot && row_info[r].endlastfoot) ||
3221                              (havefoot && row_info[r].endfoot)) &&
3222                             !row_info[r].caption) {
3223                                 ret += xhtmlRow(xs, r, runparams);
3224                         }
3225                 }
3226                 xs << html::EndTag("tfoot") << html::CR();
3227         }
3228
3229         xs << html::StartTag("tbody") << html::CR();
3230         for (row_type r = 0; r < nrows(); ++r) {
3231                 if (isValidRow(r)) {
3232                         ret += xhtmlRow(xs, r, runparams);
3233                 }
3234         }
3235         xs << html::EndTag("tbody")
3236            << html::CR()
3237            << html::EndTag("table")
3238            << html::CR();
3239         if (is_long_tabular)
3240                 xs << html::EndTag("div") << html::CR();
3241         return ret;
3242 }
3243
3244
3245 bool Tabular::plaintextTopHLine(odocstringstream & os, row_type row,
3246                                    vector<unsigned int> const & clen) const
3247 {
3248         idx_type const fcell = getFirstCellInRow(row);
3249         idx_type const n = numberOfCellsInRow(row) + fcell;
3250         idx_type tmp = 0;
3251
3252         for (idx_type i = fcell; i < n; ++i) {
3253                 if (topLine(i)) {
3254                         ++tmp;
3255                         break;
3256                 }
3257         }
3258         if (!tmp)
3259                 return false;
3260
3261         char_type ch;
3262         for (idx_type i = fcell; i < n; ++i) {
3263                 if (topLine(i)) {
3264                         if (leftLine(i))
3265                                 os << "+-";
3266                         else
3267                                 os << "--";
3268                         ch = '-';
3269                 } else {
3270                         os << "  ";
3271                         ch = ' ';
3272                 }
3273                 col_type column = cellColumn(i);
3274                 int len = clen[column];
3275                 while (column < ncols() - 1
3276                        && isPartOfMultiColumn(row, ++column))
3277                         len += clen[column] + 4;
3278                 os << docstring(len, ch);
3279                 if (topLine(i)) {
3280                         if (rightLine(i))
3281                                 os << "-+";
3282                         else
3283                                 os << "--";
3284                 } else {
3285                         os << "  ";
3286                 }
3287         }
3288         os << endl;
3289         return true;
3290 }
3291
3292
3293 bool Tabular::plaintextBottomHLine(odocstringstream & os, row_type row,
3294                                       vector<unsigned int> const & clen) const
3295 {
3296         idx_type const fcell = getFirstCellInRow(row);
3297         idx_type const n = numberOfCellsInRow(row) + fcell;
3298         idx_type tmp = 0;
3299
3300         for (idx_type i = fcell; i < n; ++i) {
3301                 if (bottomLine(i)) {
3302                         ++tmp;
3303                         break;
3304                 }
3305         }
3306         if (!tmp)
3307                 return false;
3308
3309         char_type ch;
3310         for (idx_type i = fcell; i < n; ++i) {
3311                 if (bottomLine(i)) {
3312                         if (leftLine(i))
3313                                 os << "+-";
3314                         else
3315                                 os << "--";
3316                         ch = '-';
3317                 } else {
3318                         os << "  ";
3319                         ch = ' ';
3320                 }
3321                 col_type column = cellColumn(i);
3322                 int len = clen[column];
3323                 while (column < ncols() - 1 && isPartOfMultiColumn(row, ++column))
3324                         len += clen[column] + 4;
3325                 os << docstring(len, ch);
3326                 if (bottomLine(i)) {
3327                         if (rightLine(i))
3328                                 os << "-+";
3329                         else
3330                                 os << "--";
3331                 } else {
3332                         os << "  ";
3333                 }
3334         }
3335         os << endl;
3336         return true;
3337 }
3338
3339
3340 void Tabular::plaintextPrintCell(odocstringstream & os,
3341                                OutputParams const & runparams,
3342                                idx_type cell, row_type row, col_type column,
3343                                vector<unsigned int> const & clen,
3344                                bool onlydata, size_t max_length) const
3345 {
3346         odocstringstream sstr;
3347         cellInset(cell)->plaintext(sstr, runparams, max_length);
3348
3349         if (onlydata) {
3350                 os << sstr.str();
3351                 return;
3352         }
3353
3354         if (leftLine(cell))
3355                 os << "| ";
3356         else
3357                 os << "  ";
3358
3359         unsigned int len1 = sstr.str().length();
3360         unsigned int len2 = clen[column];
3361         while (column < ncols() - 1 && isPartOfMultiColumn(row, ++column))
3362                 len2 += clen[column] + 4;
3363         len2 -= len1;
3364
3365         switch (getAlignment(cell)) {
3366         default:
3367         case LYX_ALIGN_LEFT:
3368                 len1 = 0;
3369                 break;
3370         case LYX_ALIGN_RIGHT:
3371                 len1 = len2;
3372                 len2 = 0;
3373                 break;
3374         case LYX_ALIGN_CENTER:
3375                 len1 = len2 / 2;
3376                 len2 -= len1;
3377                 break;
3378         }
3379
3380         os << docstring(len1, ' ') << sstr.str()
3381            << docstring(len2, ' ');
3382
3383         if (rightLine(cell))
3384                 os << " |";
3385         else
3386                 os << "  ";
3387 }
3388
3389
3390 void Tabular::plaintext(odocstringstream & os,
3391                            OutputParams const & runparams, int const depth,
3392                            bool onlydata, char_type delim, size_t max_length) const
3393 {
3394         // first calculate the width of the single columns
3395         vector<unsigned int> clen(ncols());
3396
3397         if (!onlydata) {
3398                 // first all non multicolumn cells!
3399                 for (col_type c = 0; c < ncols(); ++c) {
3400                         clen[c] = 0;
3401                         for (row_type r = 0; r < nrows(); ++r) {
3402                                 idx_type cell = cellIndex(r, c);
3403                                 if (isMultiColumn(cell))
3404                                         continue;
3405                                 odocstringstream sstr;
3406                                 cellInset(cell)->plaintext(sstr, runparams, max_length);
3407                                 if (clen[c] < sstr.str().length())
3408                                         clen[c] = sstr.str().length();
3409                         }
3410                 }
3411                 // then all multicolumn cells!
3412                 for (col_type c = 0; c < ncols(); ++c) {
3413                         for (row_type r = 0; r < nrows(); ++r) {
3414                                 idx_type cell = cellIndex(r, c);
3415                                 if (cell_info[r][c].multicolumn != CELL_BEGIN_OF_MULTICOLUMN)
3416                                         continue;
3417                                 odocstringstream sstr;
3418                                 cellInset(cell)->plaintext(sstr, runparams, max_length);
3419                                 int len = int(sstr.str().length());
3420                                 idx_type const n = columnSpan(cell);
3421                                 for (col_type k = c; len > 0 && k < c + n - 1; ++k)
3422                                         len -= clen[k];
3423                                 if (len > int(clen[c + n - 1]))
3424                                         clen[c + n - 1] = len;
3425                         }
3426                 }
3427         }
3428         idx_type cell = 0;
3429         for (row_type r = 0; r < nrows(); ++r) {
3430                 if (!onlydata && plaintextTopHLine(os, r, clen))
3431                         os << docstring(depth * 2, ' ');
3432                 for (col_type c = 0; c < ncols(); ++c) {
3433                         if (isPartOfMultiColumn(r, c) || isPartOfMultiRow(r,c))
3434                                 continue;
3435                         if (onlydata && c > 0)
3436                                 // we don't use operator<< for single UCS4 character.
3437                                 // see explanation in docstream.h
3438                                 os.put(delim);
3439                         plaintextPrintCell(os, runparams, cell, r, c, clen, onlydata, max_length);
3440                         ++cell;
3441                         if (os.str().size() > max_length)
3442                                 break;
3443                 }
3444                 os << endl;
3445                 if (!onlydata) {
3446                         os << docstring(depth * 2, ' ');
3447                         if (plaintextBottomHLine(os, r, clen))
3448                                 os << docstring(depth * 2, ' ');
3449                 }
3450                 if (os.str().size() > max_length)
3451                         break;
3452         }
3453 }
3454
3455
3456 shared_ptr<InsetTableCell> Tabular::cellInset(idx_type cell)
3457 {
3458         return cell_info[cellRow(cell)][cellColumn(cell)].inset;
3459 }
3460
3461
3462 shared_ptr<InsetTableCell> Tabular::cellInset(row_type row, col_type column)
3463 {
3464         return cell_info[row][column].inset;
3465 }
3466
3467
3468 InsetTableCell const * Tabular::cellInset(idx_type cell) const
3469 {
3470         return cell_info[cellRow(cell)][cellColumn(cell)].inset.get();
3471 }
3472
3473
3474 void Tabular::setCellInset(row_type row, col_type column,
3475                            shared_ptr<InsetTableCell> ins)
3476 {
3477         CellData & cd = cell_info[row][column];
3478         cd.inset = ins;
3479 }
3480
3481
3482 void Tabular::validate(LaTeXFeatures & features) const
3483 {
3484         features.require("NeedTabularnewline");
3485         if (use_booktabs)
3486                 features.require("booktabs");
3487         if (is_long_tabular)
3488                 features.require("longtable");
3489         if (rotate && is_long_tabular)
3490                 features.require("lscape");
3491         if (needRotating())
3492                 features.require("rotating");
3493         for (idx_type cell = 0; cell < numberofcells; ++cell) {
3494                 if (isMultiRow(cell))
3495                         features.require("multirow");
3496                 if (getVAlignment(cell) != LYX_VALIGN_TOP
3497                     || !getPWidth(cell).zero())
3498                         features.require("array");
3499                 // Tell footnote that we need a savenote
3500                 // environment in non-long tables or
3501                 // longtable headers/footers
3502                 else if (!is_long_tabular && !features.inFloat())
3503                         features.saveNoteEnv("tabular");
3504                 else if (!isValidRow(cellRow(cell)))
3505                         features.saveNoteEnv("longtable");
3506
3507                 cellInset(cell)->validate(features);
3508                 features.saveNoteEnv(string());
3509         }
3510 }
3511
3512
3513 Tabular::BoxType Tabular::useParbox(idx_type cell) const
3514 {
3515         ParagraphList const & parlist = cellInset(cell)->paragraphs();
3516         ParagraphList::const_iterator cit = parlist.begin();
3517         ParagraphList::const_iterator end = parlist.end();
3518
3519         for (; cit != end; ++cit)
3520                 for (int i = 0; i < cit->size(); ++i)
3521                         if (cit->isNewline(i))
3522                                 return BOX_PARBOX;
3523
3524         return BOX_NONE;
3525 }
3526
3527
3528 /////////////////////////////////////////////////////////////////////
3529 //
3530 // InsetTableCell
3531 //
3532 /////////////////////////////////////////////////////////////////////
3533
3534 InsetTableCell::InsetTableCell(Buffer * buf)
3535         : InsetText(buf, InsetText::PlainLayout), isFixedWidth(false),
3536           contentAlign(LYX_ALIGN_CENTER)
3537 {}
3538
3539
3540 bool InsetTableCell::forcePlainLayout(idx_type) const
3541 {
3542         return !isFixedWidth;
3543 }
3544
3545
3546 bool InsetTableCell::allowParagraphCustomization(idx_type) const
3547 {
3548         return isFixedWidth;
3549 }
3550
3551
3552 bool InsetTableCell::forceLocalFontSwitch() const
3553 {
3554         return isFixedWidth;
3555 }
3556
3557
3558 bool InsetTableCell::getStatus(Cursor & cur, FuncRequest const & cmd,
3559         FuncStatus & status) const
3560 {
3561         bool enabled = true;
3562         switch (cmd.action()) {
3563         case LFUN_MATH_DISPLAY:
3564                 if (!hasFixedWidth()) {
3565                         enabled = false;
3566                         break;
3567                 } //fall-through
3568         default:
3569                 return InsetText::getStatus(cur, cmd, status);
3570         }
3571         status.setEnabled(enabled);
3572         return true;
3573 }
3574
3575 docstring InsetTableCell::asString(bool intoInsets)
3576 {
3577         docstring retval;
3578         if (paragraphs().empty())
3579                 return retval;
3580         ParagraphList::const_iterator it = paragraphs().begin();
3581         ParagraphList::const_iterator en = paragraphs().end();
3582         bool first = true;
3583         for (; it != en; ++it) {
3584                 if (!first)
3585                         retval += "\n";
3586                 else
3587                         first = false;
3588                 retval += it->asString(intoInsets ? AS_STR_INSETS : AS_STR_NONE);
3589         }
3590         return retval;
3591 }
3592
3593
3594 void InsetTableCell::addToToc(DocIterator const & di, bool output_active,
3595                                                           UpdateType utype, TocBackend & backend) const
3596 {
3597         InsetText::iterateForToc(di, output_active, utype, backend);
3598 }
3599
3600
3601 docstring InsetTableCell::xhtml(XHTMLStream & xs, OutputParams const & rp) const
3602 {
3603         if (!isFixedWidth)
3604                 return InsetText::insetAsXHTML(xs, rp, InsetText::JustText);
3605         return InsetText::xhtml(xs, rp);
3606 }
3607
3608
3609
3610 /////////////////////////////////////////////////////////////////////
3611 //
3612 // InsetTabular
3613 //
3614 /////////////////////////////////////////////////////////////////////
3615
3616 InsetTabular::InsetTabular(Buffer * buf, row_type rows,
3617                            col_type columns)
3618         : Inset(buf), tabular(buf, max(rows, row_type(1)), max(columns, col_type(1))),
3619           rowselect_(false), colselect_(false)
3620 {
3621 }
3622
3623
3624 InsetTabular::InsetTabular(InsetTabular const & tab)
3625         : Inset(tab), tabular(tab.tabular),
3626           rowselect_(false), colselect_(false)
3627 {
3628 }
3629
3630
3631 InsetTabular::~InsetTabular()
3632 {
3633         hideDialogs("tabular", this);
3634 }
3635
3636
3637 void InsetTabular::setBuffer(Buffer & buf)
3638 {
3639         tabular.setBuffer(buf);
3640         Inset::setBuffer(buf);
3641 }
3642
3643
3644 bool InsetTabular::insetAllowed(InsetCode code) const
3645 {
3646         switch (code) {
3647         case FLOAT_CODE:
3648         case MARGIN_CODE:
3649         case MATHMACRO_CODE:
3650         case WRAP_CODE:
3651                 return false;
3652
3653         case CAPTION_CODE:
3654                 return tabular.is_long_tabular;
3655
3656         default:
3657                 return true;
3658         }
3659 }
3660
3661
3662 bool InsetTabular::allowsCaptionVariation(std::string const & newtype) const
3663 {
3664         return tabular.is_long_tabular &&
3665                 (newtype == "Standard" || newtype == "Unnumbered");
3666 }
3667
3668
3669 void InsetTabular::write(ostream & os) const
3670 {
3671         os << "Tabular" << endl;
3672         tabular.write(os);
3673 }
3674
3675
3676 string InsetTabular::contextMenu(BufferView const &, int, int) const
3677 {
3678         // FIXME: depending on the selection state,
3679         // we could offer a different menu.
3680         return cell(0)->contextMenuName() + ";" + contextMenuName();
3681 }
3682
3683
3684 string InsetTabular::contextMenuName() const
3685 {
3686         return "context-tabular";
3687 }
3688
3689
3690 void InsetTabular::read(Lexer & lex)
3691 {
3692         //bool const old_format = (lex.getString() == "\\LyXTable");
3693
3694         tabular.read(lex);
3695
3696         //if (old_format)
3697         //      return;
3698
3699         lex.next();
3700         string token = lex.getString();
3701         while (lex && token != "\\end_inset") {
3702                 lex.next();
3703                 token = lex.getString();
3704         }
3705         if (!lex)
3706                 lex.printError("Missing \\end_inset at this point. ");
3707 }
3708
3709
3710 int InsetTabular::rowFromY(Cursor & cur, int y) const
3711 {
3712         // top y coordinate of tabular
3713         int h = yo(cur.bv()) - tabular.rowAscent(0) + tabular.offsetVAlignment();
3714         row_type r = 0;
3715         for (; r < tabular.nrows() && y > h; ++r)
3716                 h += tabular.rowAscent(r) + tabular.rowDescent(r)
3717                         + tabular.interRowSpace(r);
3718
3719         return r - 1;
3720 }
3721
3722
3723 int InsetTabular::columnFromX(Cursor & cur, int x) const
3724 {
3725         // left x coordinate of tabular
3726         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
3727         col_type c = 0;
3728         for (; c < tabular.ncols() && x > w; ++c)
3729                 w += tabular.cellWidth(c);
3730         return c - 1;
3731 }
3732
3733
3734 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
3735 {
3736         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
3737         //      mi.base.textwidth << "\n";
3738         LBUFERR(mi.base.bv);
3739
3740         for (row_type r = 0; r < tabular.nrows(); ++r) {
3741                 int maxasc = 0;
3742                 int maxdes = 0;
3743                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3744                         if (tabular.isPartOfMultiColumn(r, c)
3745                                 || tabular.isPartOfMultiRow(r, c))
3746                                 // multicolumn or multirow cell, but not first one
3747                                 continue;
3748                         idx_type const cell = tabular.cellIndex(r, c);
3749                         Dimension dim0;
3750                         MetricsInfo m = mi;
3751                         Length const p_width = tabular.getPWidth(cell);
3752                         if (!p_width.zero())
3753                                 m.base.textwidth = mi.base.inPixels(p_width);
3754                         tabular.cellInset(cell)->metrics(m, dim0);
3755                         if (!p_width.zero())
3756                                 dim0.wid = m.base.textwidth;
3757                         tabular.cellInfo(cell).width = dim0.wid + 2 * WIDTH_OF_LINE
3758                                 + tabular.interColumnSpace(cell);
3759
3760                         // FIXME(?): do we need a second metrics call?
3761                         TextMetrics const & tm =
3762                                 mi.base.bv->textMetrics(tabular.cellInset(cell)->getText(0));
3763
3764                         // determine horizontal offset because of decimal align (if necessary)
3765                         int decimal_width = 0;
3766                         if (tabular.getAlignment(cell) == LYX_ALIGN_DECIMAL) {
3767                                 InsetTableCell tail = InsetTableCell(*tabular.cellInset(cell));
3768                                 tail.setBuffer(tabular.buffer());
3769                                 // we need to set macrocontext position everywhere
3770                                 // otherwise we crash with nested insets (e.g. footnotes)
3771                                 // after decimal point
3772                                 DocIterator dit = tabular.cellInset(cell)->getText(0)->macrocontextPosition();
3773                                 dit.pop_back();
3774                                 dit.push_back(CursorSlice(tail));
3775                                 tail.setMacrocontextPositionRecursive(dit);
3776
3777                                 // remove text leading decimal point
3778                                 docstring const align_d = tabular.column_info[c].decimal_point;
3779                                 dit = separatorPos(&tail, align_d);
3780
3781                                 pit_type const psize = tail.paragraphs().front().size();
3782                                 if (dit) {
3783                                         tail.paragraphs().front().eraseChars(0,
3784                                                 dit.pos() < psize ? dit.pos() + 1 : psize, false);
3785                                         Dimension dim1;
3786                                         tail.metrics(m, dim1);
3787                                         decimal_width = dim1.width();
3788                                 }
3789                         }
3790                         tabular.cell_info[r][c].decimal_hoffset = tm.width() - decimal_width;
3791                         tabular.cell_info[r][c].decimal_width = decimal_width;
3792
3793                         // with LYX_VALIGN_BOTTOM the descent is relative to the last par
3794                         // = descent of text in last par + TEXT_TO_INSET_OFFSET:
3795                         int const lastpardes = tm.last().second->descent()
3796                                 + TEXT_TO_INSET_OFFSET;
3797                         int offset = 0;
3798                         switch (tabular.getVAlignment(cell)) {
3799                                 case Tabular::LYX_VALIGN_TOP:
3800                                         break;
3801                                 case Tabular::LYX_VALIGN_MIDDLE:
3802                                         offset = -(dim0.des - lastpardes)/2;
3803                                         break;
3804                                 case Tabular::LYX_VALIGN_BOTTOM:
3805                                         offset = -(dim0.des - lastpardes);
3806                                         break;
3807                         }
3808                         tabular.cell_info[r][c].voffset = offset;
3809                         maxasc = max(maxasc, dim0.asc - offset);
3810                         maxdes = max(maxdes, dim0.des + offset);
3811                 }
3812                 int const top_space = tabular.row_info[r].top_space_default ?
3813                     default_line_space :
3814                     mi.base.inPixels(tabular.row_info[r].top_space);
3815                 tabular.setRowAscent(r, maxasc + ADD_TO_HEIGHT + top_space);
3816                 int const bottom_space = tabular.row_info[r].bottom_space_default ?
3817                     default_line_space :
3818                     mi.base.inPixels(tabular.row_info[r].bottom_space);
3819                 tabular.setRowDescent(r, maxdes + ADD_TO_HEIGHT + bottom_space);
3820         }
3821
3822         tabular.updateColumnWidths();
3823         dim.asc = tabular.rowAscent(0) - tabular.offsetVAlignment();
3824         dim.des = tabular.height() - dim.asc;
3825         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3826 }
3827
3828
3829 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col)
3830         const
3831 {
3832         if (&cur.inset() == this && cur.selection()) {
3833                 if (cur.selIsMultiCell()) {
3834                         row_type rs, re;
3835                         col_type cs, ce;
3836                         getSelection(cur, rs, re, cs, ce);
3837
3838                         idx_type const cell = tabular.cellIndex(row, col);
3839                         col_type const cspan = tabular.columnSpan(cell);
3840                         row_type const rspan = tabular.rowSpan(cell);
3841                         if (col + cspan - 1 >= cs && col <= ce
3842                                 && row + rspan - 1 >= rs && row <= re)
3843                                 return true;
3844                 } else
3845                         if (col == tabular.cellColumn(cur.idx())
3846                                 && row == tabular.cellRow(cur.idx())) {
3847                         CursorSlice const & beg = cur.selBegin();
3848                         CursorSlice const & end = cur.selEnd();
3849
3850                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3851                                   && end.pos() == end.lastpos() && beg.pos() == 0
3852                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3853                                 return true;
3854                 }
3855         }
3856         return false;
3857 }
3858
3859
3860 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3861 {
3862         x += ADD_TO_TABULAR_WIDTH;
3863
3864         BufferView * bv = pi.base.bv;
3865         Cursor & cur = pi.base.bv->cursor();
3866
3867         // FIXME: As the full background is painted in drawBackground(),
3868         // we have no choice but to do a full repaint for the Text cells.
3869         pi.full_repaint = true;
3870
3871         bool const original_selection_state = pi.selected;
3872
3873         idx_type idx = 0;
3874
3875         int yy = y + tabular.offsetVAlignment();
3876         for (row_type r = 0; r < tabular.nrows(); ++r) {
3877                 int nx = x;
3878                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3879                         if (tabular.isPartOfMultiColumn(r, c))
3880                                 continue;
3881
3882                         idx = tabular.cellIndex(r, c);
3883
3884                         if (tabular.isPartOfMultiRow(r, c)) {
3885                                 nx += tabular.cellWidth(idx);
3886                                 continue;
3887                         }
3888
3889                         pi.selected |= isCellSelected(cur, r, c);
3890                         int const cx = nx + tabular.textHOffset(idx);
3891                         int const cy = yy + tabular.textVOffset(idx);
3892                         // Cache the Inset position.
3893                         bv->coordCache().insets().add(cell(idx).get(), cx, cy);
3894                         cell(idx)->draw(pi, cx, cy);
3895                         drawCellLines(pi, nx, yy, r, idx);
3896                         nx += tabular.cellWidth(idx);
3897                         pi.selected = original_selection_state;
3898                 }
3899
3900                 if (r + 1 < tabular.nrows())
3901                         yy += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
3902                                 + tabular.interRowSpace(r + 1);
3903         }
3904 }
3905
3906
3907 void InsetTabular::drawBackground(PainterInfo & pi, int x, int y) const
3908 {
3909         x += ADD_TO_TABULAR_WIDTH;
3910         y += tabular.offsetVAlignment() - tabular.rowAscent(0);
3911         pi.pain.fillRectangle(x, y, tabular.width(), tabular.height(),
3912                 pi.backgroundColor(this));
3913 }
3914
3915
3916 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3917 {
3918         Cursor & cur = pi.base.bv->cursor();
3919
3920         x += ADD_TO_TABULAR_WIDTH;
3921
3922         if (!cur.selection())
3923                 return;
3924         if (&cur.inset() != this)
3925                 return;
3926
3927         //resetPos(cur);
3928
3929         bool const full_cell_selected = isCellSelected(cur,
3930                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3931
3932         if (cur.selIsMultiCell() || full_cell_selected) {
3933                 for (row_type r = 0; r < tabular.nrows(); ++r) {
3934                         int xx = x;
3935                         for (col_type c = 0; c < tabular.ncols(); ++c) {
3936                                 if (tabular.isPartOfMultiColumn(r, c))
3937                                         continue;
3938
3939                                 idx_type const cell = tabular.cellIndex(r, c);
3940
3941                                 if (tabular.isPartOfMultiRow(r, c)) {
3942                                         xx += tabular.cellWidth(cell);
3943                                         continue;
3944                                 }
3945                                 int const w = tabular.cellWidth(cell);
3946                                 int const h = tabular.cellHeight(cell);
3947                                 int const yy = y - tabular.rowAscent(r) + tabular.offsetVAlignment();
3948                                 if (isCellSelected(cur, r, c))
3949                                         pi.pain.fillRectangle(xx, yy, w, h, Color_selection);
3950                                 xx += w;
3951                         }
3952                         if (r + 1 < tabular.nrows())
3953                                 y += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
3954                                      + tabular.interRowSpace(r + 1);
3955                 }
3956
3957         }
3958         // FIXME: This code has no effect because InsetTableCell does not handle
3959         // drawSelection other than the trivial implementation in Inset.
3960         //else {
3961         //      x += cellXPos(cur.idx());
3962         //      x += tabular.textHOffset(cur.idx());
3963         //      cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3964         //}
3965 }
3966
3967
3968 void InsetTabular::drawCellLines(PainterInfo & pi, int x, int y,
3969                                  row_type row, idx_type cell) const
3970 {
3971         y -= tabular.rowAscent(row);
3972         int const w = tabular.cellWidth(cell);
3973         int const h = tabular.cellHeight(cell);
3974         Color const linecolor = pi.textColor(Color_tabularline);
3975         Color const gridcolor = pi.textColor(Color_tabularonoffline);
3976
3977         // Top
3978         bool drawline = tabular.topLine(cell)
3979                 || (row > 0 && tabular.bottomLine(tabular.cellAbove(cell)));
3980         pi.pain.line(x, y, x + w, y,
3981                 drawline ? linecolor : gridcolor,
3982                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3983
3984         // Bottom
3985         drawline = tabular.bottomLine(cell);
3986         pi.pain.line(x, y + h, x + w, y + h,
3987                 drawline ? linecolor : gridcolor,
3988                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3989
3990         // Left
3991         col_type const col = tabular.cellColumn(cell);
3992         drawline = tabular.leftLine(cell)
3993                 || (col > 0 && tabular.rightLine(tabular.cellIndex(row, col - 1)));
3994         pi.pain.line(x, y, x, y + h,
3995                 drawline ? linecolor : gridcolor,
3996                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3997
3998         // Right
3999         x -= tabular.interColumnSpace(cell);
4000         col_type next_cell_col = col + 1;
4001         while (next_cell_col < tabular.ncols()
4002                 && tabular.isMultiColumn(tabular.cellIndex(row, next_cell_col)))
4003                 next_cell_col++;
4004         drawline = tabular.rightLine(cell)
4005                    || (next_cell_col < tabular.ncols()
4006                        && tabular.leftLine(tabular.cellIndex(row, next_cell_col)));
4007         pi.pain.line(x + w, y, x + w, y + h,
4008                 drawline ? linecolor : gridcolor,
4009                 drawline ? Painter::line_solid : Painter::line_onoffdash);
4010 }
4011
4012
4013 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
4014 {
4015         //lyxerr << "InsetTabular::edit: " << this << endl;
4016         cur.finishUndo();
4017         cur.push(*this);
4018         if (front) {
4019                 if (isRightToLeft(cur))
4020                         cur.idx() = tabular.getLastCellInRow(0);
4021                 else
4022                         cur.idx() = 0;
4023                 cur.pit() = 0;
4024                 cur.pos() = 0;
4025         } else {
4026                 if (isRightToLeft(cur))
4027                         cur.idx() = tabular.getFirstCellInRow(tabular.nrows() - 1);
4028                 else
4029                         cur.idx() = tabular.numberofcells - 1;
4030                 cur.pit() = 0;
4031                 cur.pos() = cur.lastpos(); // FIXME crude guess
4032         }
4033         cur.setCurrentFont();
4034         // FIXME: this accesses the position cache before it is initialized
4035         //cur.bv().fitCursor();
4036 }
4037
4038
4039 void InsetTabular::updateBuffer(ParIterator const & it, UpdateType utype)
4040 {
4041         // In a longtable, tell captions what the current float is
4042         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
4043         string const saveflt = cnts.current_float();
4044         if (tabular.is_long_tabular) {
4045                 cnts.current_float("table");
4046                 // in longtables, we only step the counter once
4047                 cnts.step(from_ascii("table"), utype);
4048                 cnts.isLongtable(true);
4049         }
4050
4051         ParIterator it2 = it;
4052         it2.forwardPos();
4053         size_t const end = it2.nargs();
4054         for ( ; it2.idx() < end; it2.top().forwardIdx())
4055                 buffer().updateBuffer(it2, utype);
4056
4057         //reset afterwards
4058         if (tabular.is_long_tabular) {
4059                 cnts.current_float(saveflt);
4060                 cnts.isLongtable(false);
4061         }
4062 }
4063
4064
4065 void InsetTabular::addToToc(DocIterator const & cpit, bool output_active,
4066                                                         UpdateType utype, TocBackend & backend) const
4067 {
4068         DocIterator dit = cpit;
4069         dit.forwardPos();
4070         size_t const end = dit.nargs();
4071         for ( ; dit.idx() < end; dit.top().forwardIdx())
4072                 cell(dit.idx())->addToToc(dit, output_active, utype, backend);
4073 }
4074
4075
4076 bool InsetTabular::hitSelectRow(BufferView const & bv, int x) const
4077 {
4078         int const x0 = xo(bv) + ADD_TO_TABULAR_WIDTH;
4079         return x < x0 || x > x0 + tabular.width();
4080 }
4081
4082
4083 bool InsetTabular::hitSelectColumn(BufferView const & bv, int y) const
4084 {
4085         int const y0 = yo(bv) - tabular.rowAscent(0) + tabular.offsetVAlignment();
4086         // FIXME: using ADD_TO_TABULAR_WIDTH is not really correct since
4087         // there is no margin added vertically to tabular insets.
4088         // However, it works for now.
4089         return y < y0 + ADD_TO_TABULAR_WIDTH || y > y0 + tabular.height() - ADD_TO_TABULAR_WIDTH;
4090 }
4091
4092
4093 bool InsetTabular::clickable(BufferView const & bv, int x, int y) const
4094 {
4095         return hitSelectRow(bv, x) || hitSelectColumn(bv, y);
4096 }
4097
4098
4099 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
4100 {
4101         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
4102                              << "\n  cur:" << cur);
4103         CursorSlice sl = cur.top();
4104         Cursor & bvcur = cur.bv().cursor();
4105
4106         FuncCode const act = cmd.action();
4107
4108         switch (act) {
4109
4110         case LFUN_MOUSE_PRESS: {
4111                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
4112                 // select row
4113                 if (hitSelectRow(cur.bv(), cmd.x())) {
4114                         row_type r = rowFromY(cur, cmd.y());
4115                         cur.idx() = tabular.getFirstCellInRow(r);
4116                         cur.pit() = 0;
4117                         cur.pos() = 0;
4118                         cur.resetAnchor();
4119                         cur.idx() = tabular.getLastCellInRow(r);
4120                         cur.pit() = cur.lastpit();
4121                         cur.pos() = cur.lastpos();
4122                         cur.selection(true);
4123                         bvcur = cur;
4124                         rowselect_ = true;
4125                         break;
4126                 }
4127                 // select column
4128                 if (hitSelectColumn(cur.bv(), cmd.y())) {
4129                         col_type c = columnFromX(cur, cmd.x());
4130                         cur.idx() = tabular.cellIndex(0, c);
4131                         cur.pit() = 0;
4132                         cur.pos() = 0;
4133                         cur.resetAnchor();
4134                         cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
4135                         cur.pit() = cur.lastpit();
4136                         cur.pos() = cur.lastpos();
4137                         cur.selection(true);
4138                         bvcur = cur;
4139                         colselect_ = true;
4140                         break;
4141                 }
4142                 // do not reset cursor/selection if we have selected
4143                 // some cells (bug 2715).
4144                 if (cmd.button() == mouse_button::button3
4145                     && &bvcur.selBegin().inset() == this
4146                     && bvcur.selIsMultiCell())
4147                         ;
4148                 else
4149                         // Let InsetTableCell do it
4150                         cell(cur.idx())->dispatch(cur, cmd);
4151                 break;
4152         }
4153         case LFUN_MOUSE_MOTION:
4154                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
4155                 if (cmd.button() == mouse_button::button1) {
4156                         // only accept motions to places not deeper nested than the real anchor
4157                         if (!bvcur.realAnchor().hasPart(cur)) {
4158                                 cur.undispatched();
4159                                 break;
4160                         }
4161                         // select (additional) row
4162                         if (rowselect_) {
4163                                 row_type r = rowFromY(cur, cmd.y());
4164                                 cur.idx() = tabular.getLastCellInRow(r);
4165                                 // we need to reset the cursor's pit and pos now, as the old ones
4166                                 // may no longer be valid.
4167                                 cur.pit() = 0;
4168                                 cur.pos() = 0;
4169                                 bvcur.setCursor(cur);
4170                                 bvcur.selection(true);
4171                                 break;
4172                         }
4173                         // select (additional) column
4174                         if (colselect_) {
4175                                 col_type c = columnFromX(cur, cmd.x());
4176                                 cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
4177                                 // we need to reset the cursor's pit and pos now, as the old ones
4178                                 // may no longer be valid.
4179                                 cur.pit() = 0;
4180                                 cur.pos() = 0;
4181                                 bvcur.setCursor(cur);
4182                                 bvcur.selection(true);
4183                                 break;
4184                         }
4185                         // only update if selection changes
4186                         if (bvcur.idx() == cur.idx() &&
4187                                 !(bvcur.realAnchor().idx() == cur.idx() && bvcur.pos() != cur.pos()))
4188                                 cur.noScreenUpdate();
4189                         setCursorFromCoordinates(cur, cmd.x(), cmd.y());
4190                         bvcur.setCursor(cur);
4191                         bvcur.selection(true);
4192                         // if this is a multicell selection, we just set the cursor to
4193                         // the beginning of the cell's text.
4194                         if (bvcur.selIsMultiCell()) {
4195                                 bvcur.pit() = bvcur.lastpit();
4196                                 bvcur.pos() = bvcur.lastpos();
4197                         }
4198                 }
4199                 break;
4200
4201         case LFUN_MOUSE_RELEASE:
4202                 rowselect_ = false;
4203                 colselect_ = false;
4204                 break;
4205
4206         case LFUN_CELL_BACKWARD:
4207                 movePrevCell(cur);
4208                 cur.selection(false);
4209                 break;
4210
4211         case LFUN_CELL_FORWARD:
4212                 moveNextCell(cur);
4213                 cur.selection(false);
4214                 break;
4215
4216         case LFUN_CHAR_FORWARD_SELECT:
4217         case LFUN_CHAR_FORWARD:
4218         case LFUN_CHAR_BACKWARD_SELECT:
4219         case LFUN_CHAR_BACKWARD:
4220         case LFUN_CHAR_RIGHT_SELECT:
4221         case LFUN_CHAR_RIGHT:
4222         case LFUN_CHAR_LEFT_SELECT:
4223         case LFUN_CHAR_LEFT:
4224         case LFUN_WORD_FORWARD:
4225         case LFUN_WORD_FORWARD_SELECT:
4226         case LFUN_WORD_BACKWARD:
4227         case LFUN_WORD_BACKWARD_SELECT:
4228         case LFUN_WORD_RIGHT:
4229         case LFUN_WORD_RIGHT_SELECT:
4230         case LFUN_WORD_LEFT:
4231         case LFUN_WORD_LEFT_SELECT: {
4232                 // determine whether we move to next or previous cell, where to enter
4233                 // the new cell from, and which command to "finish" (i.e., exit the
4234                 // inset) with:
4235                 bool next_cell;
4236                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
4237                 FuncCode finish_lfun;
4238
4239                 if (act == LFUN_CHAR_FORWARD
4240                                 || act == LFUN_CHAR_FORWARD_SELECT
4241                                 || act == LFUN_WORD_FORWARD
4242                                 || act == LFUN_WORD_FORWARD_SELECT) {
4243                         next_cell = true;
4244                         finish_lfun = LFUN_FINISHED_FORWARD;
4245                 }
4246                 else if (act == LFUN_CHAR_BACKWARD
4247                                 || act == LFUN_CHAR_BACKWARD_SELECT
4248                                 || act == LFUN_WORD_BACKWARD
4249                                 || act == LFUN_WORD_BACKWARD_SELECT) {
4250                         next_cell = false;
4251                         finish_lfun = LFUN_FINISHED_BACKWARD;
4252                 }
4253                 // LEFT or RIGHT commands --- the interpretation will depend on the
4254                 // table's direction.
4255                 else {
4256                         bool const right = act == LFUN_CHAR_RIGHT
4257                                 || act == LFUN_CHAR_RIGHT_SELECT
4258                                 || act == LFUN_WORD_RIGHT
4259                                 || act == LFUN_WORD_RIGHT_SELECT;
4260                         next_cell = isRightToLeft(cur) != right;
4261
4262                         if (lyxrc.visual_cursor)
4263                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
4264
4265                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
4266                 }
4267
4268                 bool const select =     act == LFUN_CHAR_FORWARD_SELECT
4269                     || act == LFUN_CHAR_BACKWARD_SELECT
4270                     || act == LFUN_CHAR_RIGHT_SELECT
4271                     || act == LFUN_CHAR_LEFT_SELECT
4272                         || act == LFUN_WORD_FORWARD_SELECT
4273                         || act == LFUN_WORD_RIGHT_SELECT
4274                         || act == LFUN_WORD_BACKWARD_SELECT
4275                         || act == LFUN_WORD_LEFT_SELECT;
4276
4277                 // If we have a multicell selection or we're
4278                 // not doing some LFUN_*_SELECT thing anyway...
4279                 if (!cur.selIsMultiCell() || !select) {
4280                         col_type const c = tabular.cellColumn(cur.idx());
4281                         row_type const r = tabular.cellRow(cur.idx());
4282                         // Are we trying to select the whole cell and is the whole cell
4283                         // not yet selected?
4284                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
4285                                 ((next_cell && cur.pit() == cur.lastpit()
4286                                 && cur.pos() == cur.lastpos())
4287                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
4288
4289                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
4290
4291                         // ...try to dispatch to the cell's inset.
4292                         cell(cur.idx())->dispatch(cur, cmd);
4293
4294                         // When we already have a selection we want to select the whole cell
4295                         // before going to the next cell.
4296                         if (select_whole && !empty_cell){
4297                                 getText(cur.idx())->selectAll(cur);
4298                                 cur.dispatched();
4299                                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4300                                 break;
4301                         }
4302
4303                         // FIXME: When we support the selection of an empty cell, remove
4304                         // the !empty_cell from this condition. For now we jump to the next
4305                         // cell if the current cell is empty.
4306                         if (cur.result().dispatched() && !empty_cell)
4307                                 break;
4308                 }
4309
4310                 // move to next/prev cell, as appropriate
4311                 // note that we will always do this if we're selecting and we have
4312                 // a multicell selection
4313                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
4314                         << " cell from: " << int(entry_from));
4315                 if (next_cell)
4316                         moveNextCell(cur, entry_from);
4317                 else
4318                         movePrevCell(cur, entry_from);
4319                 // if we're exiting the table, call the appropriate FINISHED lfun
4320                 if (sl == cur.top()) {
4321                         cmd = FuncRequest(finish_lfun);
4322                         cur.undispatched();
4323                 } else
4324                         cur.dispatched();
4325
4326                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4327                 break;
4328
4329         }
4330
4331         case LFUN_DOWN_SELECT:
4332         case LFUN_DOWN:
4333                 if (!(cur.selection() && cur.selIsMultiCell()))
4334                         cell(cur.idx())->dispatch(cur, cmd);
4335
4336                 cur.dispatched(); // override the cell's decision
4337                 if (sl == cur.top()) {
4338                         // if our Text didn't do anything to the cursor
4339                         // then we try to put the cursor into the cell below
4340                         // setting also the right targetX.
4341                         cur.selHandle(act == LFUN_DOWN_SELECT);
4342                         if (tabular.cellRow(cur.idx()) != tabular.nrows() - 1) {
4343                                 int const xtarget = cur.targetX();
4344                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4345                                 // an inconsistent state until pos() has been set. Be careful
4346                                 // what you do with it!
4347                                 cur.idx() = tabular.cellBelow(cur.idx());
4348                                 cur.pit() = 0;
4349                                 TextMetrics const & tm =
4350                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
4351                                 cur.pos() = tm.x2pos(cur.pit(), 0, xtarget);
4352                                 cur.setCurrentFont();
4353                         }
4354                 }
4355                 if (sl == cur.top()) {
4356                         // we trick it to go to forward after leaving the
4357                         // tabular.
4358                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
4359                         cur.undispatched();
4360                 }
4361                 if (cur.selIsMultiCell()) {
4362                         cur.pit() = cur.lastpit();
4363                         cur.pos() = cur.lastpos();
4364                         cur.setCurrentFont();
4365                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4366                         return;
4367                 }
4368                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4369                 break;
4370
4371         case LFUN_UP_SELECT:
4372         case LFUN_UP:
4373                 if (!(cur.selection() && cur.selIsMultiCell()))
4374                         cell(cur.idx())->dispatch(cur, cmd);
4375                 cur.dispatched(); // override the cell's decision
4376                 if (sl == cur.top()) {
4377                         // if our Text didn't do anything to the cursor
4378                         // then we try to put the cursor into the cell above
4379                         // setting also the right targetX.
4380                         cur.selHandle(act == LFUN_UP_SELECT);
4381                         if (tabular.cellRow(cur.idx()) != 0) {
4382                                 int const xtarget = cur.targetX();
4383                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4384                                 // an inconsistent state until pos() has been set. Be careful
4385                                 // what you do with it!
4386                                 cur.idx() = tabular.cellAbove(cur.idx());
4387                                 cur.pit() = cur.lastpit();
4388                                 Text const * text = cell(cur.idx())->getText(0);
4389                                 TextMetrics const & tm = cur.bv().textMetrics(text);
4390                                 ParagraphMetrics const & pm =
4391                                         tm.parMetrics(cur.lastpit());
4392                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, xtarget);
4393                                 cur.setCurrentFont();
4394                         }
4395                 }
4396                 if (sl == cur.top()) {
4397                         cmd = FuncRequest(LFUN_UP);
4398                         cur.undispatched();
4399                 }
4400                 if (cur.selIsMultiCell()) {
4401                         cur.pit() = 0;
4402                         cur.pos() = cur.lastpos();
4403                         cur.setCurrentFont();
4404                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4405                         return;
4406                 }
4407                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4408                 break;
4409
4410         case LFUN_LAYOUT_TABULAR:
4411                 cur.bv().showDialog("tabular");
4412                 break;
4413
4414         case LFUN_INSET_MODIFY:
4415                 // we come from the dialog
4416                 if (cmd.getArg(0) == "tabular")
4417                         tabularFeatures(cur, cmd.getLongArg(1));
4418                 else
4419                         cur.undispatched();
4420                 break;
4421
4422         case LFUN_TABULAR_FEATURE:
4423                 tabularFeatures(cur, to_utf8(cmd.argument()));
4424                 break;
4425
4426         // insert file functions
4427         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
4428         case LFUN_FILE_INSERT_PLAINTEXT:
4429                 // FIXME UNICODE
4430                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
4431                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
4432                                 FileName(to_utf8(cmd.argument())));
4433                         if (tmpstr.empty())
4434                                 break;
4435                         cur.recordUndoInset();
4436                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
4437                                 // content has been replaced,
4438                                 // so cursor might be invalid
4439                                 cur.pos() = cur.lastpos();
4440                                 cur.pit() = cur.lastpit();
4441                                 bvcur.setCursor(cur);
4442                         } else
4443                                 cur.undispatched();
4444                 }
4445                 break;
4446
4447         case LFUN_CUT:
4448                 if (cur.selIsMultiCell()) {
4449                         if (copySelection(cur)) {
4450                                 cur.recordUndoInset();
4451                                 cutSelection(cur);
4452                         }
4453                 } else
4454                         cell(cur.idx())->dispatch(cur, cmd);
4455                 break;
4456
4457         case LFUN_SELF_INSERT:
4458                 if (cur.selIsMultiCell()) {
4459                         cur.recordUndoInset();
4460                         cutSelection(cur);
4461                         BufferView * bv = &cur.bv();
4462                         docstring::const_iterator cit = cmd.argument().begin();
4463                         docstring::const_iterator const end = cmd.argument().end();
4464                         for (; cit != end; ++cit)
4465                                 bv->translateAndInsert(*cit, getText(cur.idx()), cur);
4466
4467                         cur.resetAnchor();
4468                         bv->bookmarkEditPosition();
4469                 } else
4470                         cell(cur.idx())->dispatch(cur, cmd);
4471                 break;
4472
4473         case LFUN_CHAR_DELETE_BACKWARD:
4474         case LFUN_CHAR_DELETE_FORWARD:
4475                 if (cur.selIsMultiCell()) {
4476                         cur.recordUndoInset();
4477                         cutSelection(cur);
4478                 } else
4479                         cell(cur.idx())->dispatch(cur, cmd);
4480                 break;
4481
4482         case LFUN_COPY:
4483                 if (!cur.selection())
4484                         break;
4485                 if (cur.selIsMultiCell()) {
4486                         cur.finishUndo();
4487                         copySelection(cur);
4488                 } else
4489                         cell(cur.idx())->dispatch(cur, cmd);
4490                 break;
4491
4492         case LFUN_CLIPBOARD_PASTE:
4493         case LFUN_PRIMARY_SELECTION_PASTE: {
4494                 docstring const clip = (act == LFUN_CLIPBOARD_PASTE) ?
4495                         theClipboard().getAsText(Clipboard::PlainTextType) :
4496                         theSelection().get();
4497                 if (clip.empty())
4498                         break;
4499                 // pass to InsertPlaintextString, but
4500                 // only if we have multi-cell content
4501                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
4502                         cur.recordUndoInset();
4503                         if (insertPlaintextString(cur.bv(), clip, false)) {
4504                                 // content has been replaced,
4505                                 // so cursor might be invalid
4506                                 cur.pos() = cur.lastpos();
4507                                 cur.pit() = cur.lastpit();
4508                                 bvcur.setCursor(cur);
4509                                 break;
4510                         }
4511                 }
4512                 // Let the cell handle normal text
4513                 cell(cur.idx())->dispatch(cur, cmd);
4514                 break;
4515         }
4516
4517         case LFUN_PASTE:
4518                 if (!tabularStackDirty()) {
4519                         if (!cur.selIsMultiCell())
4520                                 cell(cur.idx())->dispatch(cur, cmd);
4521                         break;
4522                 }
4523                 if (theClipboard().isInternal()) {
4524                         cur.recordUndoInset();
4525                         pasteClipboard(cur);
4526                 }
4527                 break;
4528
4529         case LFUN_FONT_EMPH:
4530         case LFUN_FONT_BOLD:
4531         case LFUN_FONT_BOLDSYMBOL:
4532         case LFUN_FONT_ROMAN:
4533         case LFUN_FONT_NOUN:
4534         case LFUN_FONT_ITAL:
4535         case LFUN_FONT_FRAK:
4536         case LFUN_FONT_TYPEWRITER:
4537         case LFUN_FONT_SANS:
4538         case LFUN_TEXTSTYLE_APPLY:
4539         case LFUN_TEXTSTYLE_UPDATE:
4540         case LFUN_FONT_SIZE:
4541         case LFUN_FONT_UNDERLINE:
4542         case LFUN_FONT_STRIKEOUT:
4543         case LFUN_FONT_CROSSOUT:
4544         case LFUN_FONT_UNDERUNDERLINE:
4545         case LFUN_FONT_UNDERWAVE:
4546         case LFUN_LANGUAGE:
4547         case LFUN_PARAGRAPH_PARAMS_APPLY:
4548         case LFUN_PARAGRAPH_PARAMS:
4549         case LFUN_WORD_CAPITALIZE:
4550         case LFUN_WORD_UPCASE:
4551         case LFUN_WORD_LOWCASE:
4552         case LFUN_CHARS_TRANSPOSE:
4553                 if (cur.selIsMultiCell()) {
4554                         row_type rs, re;
4555                         col_type cs, ce;
4556                         getSelection(cur, rs, re, cs, ce);
4557                         Cursor tmpcur = cur;
4558                         for (row_type r = rs; r <= re; ++r) {
4559                                 for (col_type c = cs; c <= ce; ++c) {
4560                                         // cursor follows cell:
4561                                         tmpcur.idx() = tabular.cellIndex(r, c);
4562                                         // select this cell only:
4563                                         tmpcur.pit() = 0;
4564                                         tmpcur.pos() = 0;
4565                                         tmpcur.resetAnchor();
4566                                         tmpcur.pit() = tmpcur.lastpit();
4567                                         tmpcur.pos() = tmpcur.top().lastpos();
4568                                         tmpcur.setCursor(tmpcur);
4569                                         tmpcur.setSelection();
4570                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
4571                                 }
4572                         }
4573                         break;
4574                 } else {
4575                         cell(cur.idx())->dispatch(cur, cmd);
4576                         break;
4577                 }
4578
4579         case LFUN_INSET_SETTINGS:
4580                 // relay this lfun to Inset, not to the cell.
4581                 Inset::doDispatch(cur, cmd);
4582                 break;
4583
4584         default:
4585                 // we try to handle this event in the insets dispatch function.
4586                 cell(cur.idx())->dispatch(cur, cmd);
4587                 break;
4588         }
4589 }
4590
4591
4592 bool InsetTabular::getFeatureStatus(Cursor & cur, string const & s,
4593                       string const & argument, FuncStatus & status) const
4594 {
4595
4596                 int action = Tabular::LAST_ACTION;
4597                 int i = 0;
4598                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4599                         if (tabularFeature[i].feature == s) {
4600                                 action = tabularFeature[i].action;
4601                                 break;
4602                         }
4603                 }
4604                 if (action == Tabular::LAST_ACTION) {
4605                         status.clear();
4606                         status.setUnknown(true);
4607                         return true;
4608                 }
4609
4610                 row_type sel_row_start = 0;
4611                 row_type sel_row_end = 0;
4612                 col_type sel_col_start = 0;
4613                 col_type sel_col_end = 0;
4614                 Tabular::ltType dummyltt;
4615                 bool flag = true;
4616
4617                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4618
4619                 switch (action) {
4620                 case Tabular::SET_PWIDTH:
4621                 case Tabular::SET_MPWIDTH:
4622                 case Tabular::SET_SPECIAL_COLUMN:
4623                 case Tabular::SET_SPECIAL_MULTICOLUMN:
4624                 case Tabular::APPEND_ROW:
4625                 case Tabular::APPEND_COLUMN:
4626                 case Tabular::DELETE_ROW:
4627                 case Tabular::DELETE_COLUMN:
4628                 case Tabular::COPY_ROW:
4629                 case Tabular::COPY_COLUMN:
4630                 case Tabular::SET_TOP_SPACE:
4631                 case Tabular::SET_BOTTOM_SPACE:
4632                 case Tabular::SET_INTERLINE_SPACE:
4633                         status.clear();
4634                         return true;
4635
4636                 case Tabular::SET_TABULAR_WIDTH:
4637                         status.setEnabled(!tabular.rotate &&  !tabular.is_long_tabular
4638                                 && tabular.tabular_valignment == Tabular::LYX_VALIGN_MIDDLE);
4639                         break;
4640
4641                 case Tabular::MOVE_COLUMN_RIGHT:
4642                 case Tabular::MOVE_COLUMN_LEFT:
4643                 case Tabular::MOVE_ROW_DOWN:
4644                 case Tabular::MOVE_ROW_UP: {
4645                         if (cur.selection()) {
4646                                 status.message(_("Selections not supported."));
4647                                 status.setEnabled(false);
4648                                 break;
4649                         }
4650
4651                         if ((action == Tabular::MOVE_COLUMN_RIGHT &&
4652                                 tabular.ncols() == tabular.cellColumn(cur.idx()) + 1) ||
4653                             (action == Tabular::MOVE_COLUMN_LEFT &&
4654                                 tabular.cellColumn(cur.idx()) == 0) ||
4655                             (action == Tabular::MOVE_ROW_DOWN &&
4656                                 tabular.nrows() == tabular.cellRow(cur.idx()) + 1) ||
4657                             (action == Tabular::MOVE_ROW_UP &&
4658                                 tabular.cellRow(cur.idx()) == 0)) {
4659                                         status.setEnabled(false);
4660                                         break;
4661                         }
4662
4663                         if (action == Tabular::MOVE_COLUMN_RIGHT ||
4664                             action == Tabular::MOVE_COLUMN_LEFT) {
4665                                 if (tabular.hasMultiColumn(tabular.cellColumn(cur.idx())) ||
4666                                     tabular.hasMultiColumn(tabular.cellColumn(cur.idx()) +
4667                                         (action == Tabular::MOVE_COLUMN_RIGHT ? 1 : -1))) {
4668                                         status.message(_("Multi-column in current or"
4669                                                          " destination column."));
4670                                         status.setEnabled(false);
4671                                         break;
4672                                 }
4673                         }
4674
4675                         if (action == Tabular::MOVE_ROW_DOWN ||
4676                             action == Tabular::MOVE_ROW_UP) {
4677                                 if (tabular.hasMultiRow(tabular.cellRow(cur.idx())) ||
4678                                     tabular.hasMultiRow(tabular.cellRow(cur.idx()) +
4679                                         (action == Tabular::MOVE_ROW_DOWN ? 1 : -1))) {
4680                                         status.message(_("Multi-row in current or"
4681                                                          " destination row."));
4682                                         status.setEnabled(false);
4683                                         break;
4684                                 }
4685                         }
4686
4687                         status.setEnabled(true);
4688                         break;
4689                 }
4690
4691                 case Tabular::SET_DECIMAL_POINT:
4692                         status.setEnabled(
4693                                 tabular.getAlignment(cur.idx()) == LYX_ALIGN_DECIMAL);
4694                         break;
4695
4696                 case Tabular::SET_MULTICOLUMN:
4697                 case Tabular::UNSET_MULTICOLUMN:
4698                 case Tabular::MULTICOLUMN:
4699                         // If a row is set as longtable caption, it must not be allowed
4700                         // to unset that this row is a multicolumn.
4701                         status.setEnabled(sel_row_start == sel_row_end
4702                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4703                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
4704                         break;
4705
4706                 case Tabular::SET_MULTIROW:
4707                 case Tabular::UNSET_MULTIROW:
4708                 case Tabular::MULTIROW:
4709                         // If a row is set as longtable caption, it must not be allowed
4710                         // to unset that this row is a multirow.
4711                         status.setEnabled(sel_col_start == sel_col_end
4712                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4713                         status.setOnOff(tabular.isMultiRow(cur.idx()));
4714                         break;
4715
4716                 case Tabular::SET_ALL_LINES:
4717                 case Tabular::UNSET_ALL_LINES:
4718                 case Tabular::SET_BORDER_LINES:
4719                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4720                         break;
4721
4722                 case Tabular::SET_LINE_TOP:
4723                 case Tabular::SET_LINE_BOTTOM:
4724                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4725                         break;
4726
4727                 case Tabular::SET_LINE_LEFT:
4728                 case Tabular::SET_LINE_RIGHT:
4729                         status.setEnabled(!tabular.use_booktabs
4730                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4731                         break;
4732
4733                 case Tabular::TOGGLE_LINE_TOP:
4734                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4735                         status.setOnOff(tabular.topLine(cur.idx()));
4736                         break;
4737
4738                 case Tabular::TOGGLE_LINE_BOTTOM:
4739                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4740                         status.setOnOff(tabular.bottomLine(cur.idx()));
4741                         break;
4742
4743                 case Tabular::TOGGLE_LINE_LEFT:
4744                         status.setEnabled(!tabular.use_booktabs
4745                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4746                         status.setOnOff(tabular.leftLine(cur.idx()));
4747                         break;
4748
4749                 case Tabular::TOGGLE_LINE_RIGHT:
4750                         status.setEnabled(!tabular.use_booktabs
4751                                           && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4752                         status.setOnOff(tabular.rightLine(cur.idx()));
4753                         break;
4754
4755                 // multirow cells only inherit the alignment of the column if the column has
4756                 // no width, otherwise they are left-aligned
4757                 // therefore allow always left but right and center only if there is no width
4758                 case Tabular::M_ALIGN_LEFT:
4759                         flag = false;
4760                         // fall through
4761                 case Tabular::ALIGN_LEFT:
4762                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
4763                         break;
4764
4765                 case Tabular::M_ALIGN_RIGHT:
4766                         flag = false;
4767                         // fall through
4768                 case Tabular::ALIGN_RIGHT:
4769                         status.setEnabled(!(tabular.isMultiRow(cur.idx())
4770                                 && !tabular.getPWidth(cur.idx()).zero()));
4771                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
4772                         break;
4773
4774                 case Tabular::M_ALIGN_CENTER:
4775                         flag = false;
4776                         // fall through
4777                 case Tabular::ALIGN_CENTER:
4778                         status.setEnabled(!(tabular.isMultiRow(cur.idx())
4779                                 && !tabular.getPWidth(cur.idx()).zero()));
4780                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
4781                         break;
4782
4783                 case Tabular::ALIGN_BLOCK:
4784                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4785                                 && !tabular.isMultiRow(cur.idx()));
4786                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
4787                         break;
4788
4789                 case Tabular::ALIGN_DECIMAL:
4790                         status.setEnabled(!tabular.isMultiRow(cur.idx())
4791                                 && !tabular.isMultiColumn(cur.idx()));
4792                         status.setOnOff(tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_DECIMAL);
4793                         break;
4794
4795                 case Tabular::M_VALIGN_TOP:
4796                         flag = false;
4797                         // fall through
4798                 case Tabular::VALIGN_TOP:
4799                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4800                                 && !tabular.isMultiRow(cur.idx()));
4801                         status.setOnOff(
4802                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
4803                         break;
4804
4805                 case Tabular::M_VALIGN_BOTTOM:
4806                         flag = false;
4807                         // fall through
4808                 case Tabular::VALIGN_BOTTOM:
4809                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4810                                 && !tabular.isMultiRow(cur.idx()));
4811                         status.setOnOff(
4812                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
4813                         break;
4814
4815                 case Tabular::M_VALIGN_MIDDLE:
4816                         flag = false;
4817                         // fall through
4818                 case Tabular::VALIGN_MIDDLE:
4819                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4820                                 && !tabular.isMultiRow(cur.idx()));
4821                         status.setOnOff(
4822                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
4823                         break;
4824
4825                 case Tabular::SET_LONGTABULAR:
4826                 case Tabular::TOGGLE_LONGTABULAR:
4827                         // setting as longtable is not allowed when table is inside a float
4828                         if (cur.innerInsetOfType(FLOAT_CODE) != 0
4829                                 || cur.innerInsetOfType(WRAP_CODE) != 0)
4830                                 status.setEnabled(false);
4831                         else
4832                                 status.setEnabled(true);
4833                         status.setOnOff(tabular.is_long_tabular);
4834                         break;
4835
4836                 case Tabular::UNSET_LONGTABULAR:
4837                         status.setOnOff(!tabular.is_long_tabular);
4838                         break;
4839
4840                 case Tabular::TOGGLE_ROTATE_TABULAR:
4841                 case Tabular::SET_ROTATE_TABULAR:
4842                         status.setOnOff(tabular.rotate != 0);
4843                         break;
4844
4845                 case Tabular::TABULAR_VALIGN_TOP:
4846                         status.setEnabled(tabular.tabular_width.zero());
4847                         status.setOnOff(tabular.tabular_valignment
4848                                 == Tabular::LYX_VALIGN_TOP);
4849                         break;
4850                 case Tabular::TABULAR_VALIGN_MIDDLE:
4851                         status.setEnabled(tabular.tabular_width.zero());
4852                         status.setOnOff(tabular.tabular_valignment
4853                                 == Tabular::LYX_VALIGN_MIDDLE);
4854                         break;
4855                 case Tabular::TABULAR_VALIGN_BOTTOM:
4856                         status.setEnabled(tabular.tabular_width.zero());
4857                         status.setOnOff(tabular.tabular_valignment
4858                                 == Tabular::LYX_VALIGN_BOTTOM);
4859                         break;
4860
4861                 case Tabular::LONGTABULAR_ALIGN_LEFT:
4862                         status.setOnOff(tabular.longtabular_alignment
4863                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
4864                         break;
4865                 case Tabular::LONGTABULAR_ALIGN_CENTER:
4866                         status.setOnOff(tabular.longtabular_alignment
4867                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
4868                         break;
4869                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
4870                         status.setOnOff(tabular.longtabular_alignment
4871                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
4872                         break;
4873
4874                 case Tabular::UNSET_ROTATE_TABULAR:
4875                         status.setOnOff(tabular.rotate == 0);
4876                         break;
4877
4878                 case Tabular::TOGGLE_ROTATE_CELL:
4879                 case Tabular::SET_ROTATE_CELL:
4880                         status.setOnOff(!oneCellHasRotationState(false,
4881                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4882                         break;
4883
4884                 case Tabular::UNSET_ROTATE_CELL:
4885                         status.setOnOff(!oneCellHasRotationState(true,
4886                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4887                         break;
4888
4889                 case Tabular::SET_USEBOX:
4890                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4891                         break;
4892
4893                 // every row can only be one thing:
4894                 // either a footer or header
4895                 case Tabular::SET_LTFIRSTHEAD:
4896                         status.setEnabled(sel_row_start == sel_row_end);
4897                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4898                         break;
4899
4900                 case Tabular::UNSET_LTFIRSTHEAD:
4901                         status.setEnabled(sel_row_start == sel_row_end);
4902                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4903                         break;
4904
4905                 case Tabular::SET_LTHEAD:
4906                         status.setEnabled(sel_row_start == sel_row_end);
4907                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4908                         break;
4909
4910                 case Tabular::UNSET_LTHEAD:
4911                         status.setEnabled(sel_row_start == sel_row_end);
4912                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4913                         break;
4914
4915                 case Tabular::SET_LTFOOT:
4916                         status.setEnabled(sel_row_start == sel_row_end);
4917                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4918                         break;
4919
4920                 case Tabular::UNSET_LTFOOT:
4921                         status.setEnabled(sel_row_start == sel_row_end);
4922                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4923                         break;
4924
4925                 case Tabular::SET_LTLASTFOOT:
4926                         status.setEnabled(sel_row_start == sel_row_end);
4927                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4928                         break;
4929
4930                 case Tabular::UNSET_LTLASTFOOT:
4931                         status.setEnabled(sel_row_start == sel_row_end);
4932                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4933                         break;
4934
4935                 case Tabular::SET_LTNEWPAGE:
4936                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4937                         break;
4938                 case Tabular::UNSET_LTNEWPAGE:
4939                         status.setOnOff(!tabular.getLTNewPage(sel_row_start));
4940                         break;
4941
4942                 // only one row in head/firsthead/foot/lasthead can be the caption
4943                 // and a multirow cannot be set as caption
4944                 case Tabular::SET_LTCAPTION:
4945                         status.setEnabled(sel_row_start == sel_row_end
4946                                 && (!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4947                                  || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
4948                                 && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
4949                                  || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
4950                                 && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4951                                  || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
4952                                 && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4953                                  || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT))
4954                                 && !tabular.isMultiRow(sel_row_start));
4955                         status.setOnOff(tabular.ltCaption(sel_row_start));
4956                         break;
4957
4958                 case Tabular::UNSET_LTCAPTION:
4959                         status.setEnabled(sel_row_start == sel_row_end && tabular.ltCaption(sel_row_start));
4960                         break;
4961
4962                 case Tabular::TOGGLE_LTCAPTION:
4963                         status.setEnabled(sel_row_start == sel_row_end && (tabular.ltCaption(sel_row_start)
4964                                 || ((!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4965                                   || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
4966                                  && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
4967                                   || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
4968                                  && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4969                                   || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
4970                                  && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4971                                   || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT)))));
4972                         status.setOnOff(tabular.ltCaption(sel_row_start));
4973                         break;
4974
4975                 case Tabular::TOGGLE_BOOKTABS:
4976                 case Tabular::SET_BOOKTABS:
4977                         status.setOnOff(tabular.use_booktabs);
4978                         break;
4979
4980                 case Tabular::UNSET_BOOKTABS:
4981                         status.setOnOff(!tabular.use_booktabs);
4982                         break;
4983
4984                 default:
4985                         status.clear();
4986                         status.setEnabled(false);
4987                         break;
4988                 }
4989                 return true;
4990 }
4991
4992
4993 // function sets an object as defined in FuncStatus.h:
4994 // states OK, Unknown, Disabled, On, Off.
4995 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
4996                              FuncStatus & status) const
4997 {
4998         switch (cmd.action()) {
4999         case LFUN_INSET_MODIFY:
5000                 if (cmd.getArg(0) != "tabular")
5001                         break;
5002                 if (cmd.getArg(1) == "for-dialog") {
5003                         // The dialog is asking the status of a command
5004                         if (&cur.inset() != this)
5005                                 break;
5006                         string action = cmd.getArg(2);
5007                         string arg = cmd.getLongArg(3);
5008                         return getFeatureStatus(cur, action, arg, status);
5009                 } else {
5010                         // We always enable the lfun if it is coming from the dialog
5011                         // because the dialog makes sure all the settings are valid,
5012                         // even though the first argument might not be valid now.
5013                         status.setEnabled(true);
5014                         return true;
5015                 }
5016
5017         case LFUN_TABULAR_FEATURE: {
5018                 if (&cur.inset() != this)
5019                         break;
5020                 string action = cmd.getArg(0);
5021                 string arg = cmd.getLongArg(1);
5022                 return getFeatureStatus(cur, action, arg, status);
5023         }
5024
5025         case LFUN_CAPTION_INSERT: {
5026                 // caption is only allowed in caption cell of longtable
5027                 if (!tabular.ltCaption(tabular.cellRow(cur.idx()))) {
5028                         status.setEnabled(false);
5029                         return true;
5030                 }
5031                 // only standard caption is allowed
5032                 string arg = cmd.getArg(0);
5033                 if (!arg.empty() && arg != "Standard") {
5034                         status.setEnabled(false);
5035                         return true;
5036                 }
5037                 // check if there is already a caption
5038                 bool have_caption = false;
5039                 InsetTableCell itc = InsetTableCell(*tabular.cellInset(cur.idx()));
5040                 ParagraphList::const_iterator pit = itc.paragraphs().begin();
5041                 ParagraphList::const_iterator pend = itc.paragraphs().end();
5042                 for (; pit != pend; ++pit) {
5043                         InsetList::const_iterator it  = pit->insetList().begin();
5044                         InsetList::const_iterator end = pit->insetList().end();
5045                         for (; it != end; ++it) {
5046                                 if (it->inset->lyxCode() == CAPTION_CODE) {
5047                                         have_caption = true;
5048                                         break;
5049                                 }
5050                         }
5051                 }
5052                 status.setEnabled(!have_caption);
5053                 return true;
5054         }
5055
5056         // These are only enabled inside tabular
5057         case LFUN_CELL_BACKWARD:
5058         case LFUN_CELL_FORWARD:
5059                 status.setEnabled(true);
5060                 return true;
5061
5062         // disable these with multiple cells selected
5063         case LFUN_INSET_INSERT:
5064         case LFUN_TABULAR_INSERT:
5065         case LFUN_FLEX_INSERT:
5066         case LFUN_FLOAT_INSERT:
5067         case LFUN_FLOAT_WIDE_INSERT:
5068         case LFUN_FOOTNOTE_INSERT:
5069         case LFUN_MARGINALNOTE_INSERT:
5070         case LFUN_MATH_INSERT:
5071         case LFUN_MATH_MODE:
5072         case LFUN_MATH_MUTATE:
5073         case LFUN_MATH_DISPLAY:
5074         case LFUN_NOTE_INSERT:
5075         case LFUN_ARGUMENT_INSERT:
5076         case LFUN_BOX_INSERT:
5077         case LFUN_BRANCH_INSERT:
5078         case LFUN_PHANTOM_INSERT:
5079         case LFUN_WRAP_INSERT:
5080         case LFUN_PREVIEW_INSERT:
5081         case LFUN_ERT_INSERT: {
5082                 if (cur.selIsMultiCell()) {
5083                         status.setEnabled(false);
5084                         return true;
5085                 } else
5086                         return cell(cur.idx())->getStatus(cur, cmd, status);
5087         }
5088
5089         // disable in non-fixed-width cells
5090         case LFUN_PARAGRAPH_BREAK:
5091                 // multirow does not allow paragraph breaks
5092                 if (tabular.isMultiRow(cur.idx())) {
5093                         status.setEnabled(false);
5094                         return true;
5095                 }
5096                 // fall through
5097         case LFUN_NEWLINE_INSERT: {
5098                 if (tabular.getPWidth(cur.idx()).zero()) {
5099                         status.setEnabled(false);
5100                         return true;
5101                 } else
5102                         return cell(cur.idx())->getStatus(cur, cmd, status);
5103         }
5104
5105         case LFUN_NEWPAGE_INSERT:
5106                 status.setEnabled(false);
5107                 return true;
5108
5109         case LFUN_PASTE:
5110                 if (tabularStackDirty() && theClipboard().isInternal()) {
5111                         if (cur.selIsMultiCell()) {
5112                                 row_type rs, re;
5113                                 col_type cs, ce;
5114                                 getSelection(cur, rs, re, cs, ce);
5115                                 if (paste_tabular && paste_tabular->ncols() == ce - cs + 1
5116                                           && paste_tabular->nrows() == re - rs + 1)
5117                                         status.setEnabled(true);
5118                                 else {
5119                                         status.setEnabled(false);
5120                                         status.message(_("Selection size should match clipboard content."));
5121                                 }
5122                         } else
5123                                 status.setEnabled(true);
5124                         return true;
5125                 }
5126                 return cell(cur.idx())->getStatus(cur, cmd, status);
5127
5128         case LFUN_INSET_SETTINGS:
5129                 // relay this lfun to Inset, not to the cell.
5130                 return Inset::getStatus(cur, cmd, status);
5131
5132         default:
5133                 // we try to handle this event in the insets dispatch function.
5134                 return cell(cur.idx())->getStatus(cur, cmd, status);
5135         }
5136         return false;
5137 }
5138
5139
5140 Inset::DisplayType InsetTabular::display() const
5141 {
5142                 if (tabular.is_long_tabular) {
5143                         switch (tabular.longtabular_alignment) {
5144                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
5145                                 return AlignLeft;
5146                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
5147                                 return AlignCenter;
5148                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
5149                                 return AlignRight;
5150                         default:
5151                                 return AlignCenter;
5152                         }
5153                 } else
5154                         return Inline;
5155 }
5156
5157
5158 void InsetTabular::latex(otexstream & os, OutputParams const & runparams) const
5159 {
5160         tabular.latex(os, runparams);
5161 }
5162
5163
5164 int InsetTabular::plaintext(odocstringstream & os,
5165         OutputParams const & runparams, size_t max_length) const
5166 {
5167         os << '\n'; // output table on a new line
5168         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
5169         tabular.plaintext(os, runparams, dp, false, 0, max_length);
5170         return PLAINTEXT_NEWLINE;
5171 }
5172
5173
5174 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
5175 {
5176         int ret = 0;
5177         Inset * master = 0;
5178
5179         // FIXME: Why not pass a proper DocIterator here?
5180 #if 0
5181         // if the table is inside a float it doesn't need the informaltable
5182         // wrapper. Search for it.
5183         for (master = owner(); master; master = master->owner())
5184                 if (master->lyxCode() == FLOAT_CODE)
5185                         break;
5186 #endif
5187
5188         if (!master) {
5189                 os << "<informaltable>";
5190                 ++ret;
5191         }
5192         ret += tabular.docbook(os, runparams);
5193         if (!master) {
5194                 os << "</informaltable>";
5195                 ++ret;
5196         }
5197         return ret;
5198 }
5199
5200
5201 docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
5202 {
5203         return tabular.xhtml(xs, rp);
5204 }
5205
5206
5207 void InsetTabular::validate(LaTeXFeatures & features) const
5208 {
5209         tabular.validate(features);
5210         features.useInsetLayout(getLayout());
5211 }
5212
5213
5214 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
5215 {
5216         return tabular.cellInset(idx);
5217 }
5218
5219
5220 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
5221 {
5222         return tabular.cellInset(idx);
5223 }
5224
5225
5226 void InsetTabular::cursorPos(BufferView const & bv,
5227                 CursorSlice const & sl, bool boundary, int & x, int & y) const
5228 {
5229         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
5230
5231         // y offset     correction
5232         y += cellYPos(sl.idx());
5233         y += tabular.textVOffset(sl.idx());
5234         y += tabular.offsetVAlignment();
5235
5236         // x offset correction
5237         x += cellXPos(sl.idx());
5238         x += tabular.textHOffset(sl.idx());
5239         x += ADD_TO_TABULAR_WIDTH;
5240 }
5241
5242
5243 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
5244 {
5245         int xx = 0;
5246         int yy = 0;
5247         Inset const & inset = *tabular.cellInset(cell);
5248         Point o = bv.coordCache().getInsets().xy(&inset);
5249         int const xbeg = o.x_ - tabular.textHOffset(cell);
5250         int const xend = xbeg + tabular.cellWidth(cell);
5251         row_type const row = tabular.cellRow(cell);
5252         int const ybeg = o.y_ - tabular.rowAscent(row)
5253                 - tabular.interRowSpace(row) - tabular.textVOffset(cell);
5254         int const yend = ybeg + tabular.cellHeight(cell);
5255
5256         if (x < xbeg)
5257                 xx = xbeg - x;
5258         else if (x > xend)
5259                 xx = x - xend;
5260
5261         if (y < ybeg)
5262                 yy = ybeg - y;
5263         else if (y > yend)
5264                 yy = y - yend;
5265
5266         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
5267         //       << " ybeg=" << ybeg << " yend=" << yend
5268         //       << " xx=" << xx << " yy=" << yy
5269         //       << " dist=" << xx + yy << endl;
5270         return xx + yy;
5271 }
5272
5273
5274 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
5275 {
5276         //lyxerr << "InsetTabular::editXY: " << this << endl;
5277         cur.push(*this);
5278         cur.idx() = getNearestCell(cur.bv(), x, y);
5279         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
5280 }
5281
5282
5283 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
5284 {
5285         cur.idx() = getNearestCell(cur.bv(), x, y);
5286         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
5287 }
5288
5289
5290 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
5291 {
5292         idx_type idx_min = 0;
5293         int dist_min = numeric_limits<int>::max();
5294         for (idx_type i = 0, n = nargs(); i != n; ++i) {
5295                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
5296                         int const d = dist(bv, i, x, y);
5297                         if (d < dist_min) {
5298                                 dist_min = d;
5299                                 idx_min = i;
5300                         }
5301                 }
5302         }
5303         return idx_min;
5304 }
5305
5306
5307 int InsetTabular::cellYPos(idx_type const cell) const
5308 {
5309         row_type row = tabular.cellRow(cell);
5310         int ly = 0;
5311         for (row_type r = 0; r < row; ++r)
5312                 ly += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
5313                         + tabular.interRowSpace(r + 1);
5314         return ly;
5315 }
5316
5317
5318 int InsetTabular::cellXPos(idx_type const cell) const
5319 {
5320         col_type col = tabular.cellColumn(cell);
5321         int lx = 0;
5322         for (col_type c = 0; c < col; ++c)
5323                 lx += tabular.column_info[c].width;
5324         return lx;
5325 }
5326
5327
5328 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
5329 {
5330         row_type const row = tabular.cellRow(cur.idx());
5331         col_type const col = tabular.cellColumn(cur.idx());
5332
5333         if (isRightToLeft(cur)) {
5334                 if (tabular.cellColumn(cur.idx()) == 0) {
5335                         if (row == tabular.nrows() - 1)
5336                                 return;
5337                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
5338                 } else {
5339                         if (cur.idx() == 0)
5340                                 return;
5341                         if (col == 0)
5342                                 cur.idx() = tabular.getLastCellInRow(row - 1);
5343                         else
5344                                 cur.idx() = tabular.cellIndex(row, col - 1);
5345                 }
5346         } else {
5347                 if (tabular.isLastCell(cur.idx()))
5348                         return;
5349                 if (cur.idx() == tabular.getLastCellInRow(row))
5350                         cur.idx() = tabular.cellIndex(row + 1, 0);
5351                 else {
5352                         col_type const colnextcell = col + tabular.columnSpan(cur.idx());
5353                         cur.idx() = tabular.cellIndex(row, colnextcell);
5354                 }
5355         }
5356
5357         cur.boundary(false);
5358
5359         if (cur.selIsMultiCell()) {
5360                 cur.pit() = cur.lastpit();
5361                 cur.pos() = cur.lastpos();
5362                 return;
5363         }
5364
5365         cur.pit() = 0;
5366         cur.pos() = 0;
5367
5368         // in visual mode, place cursor at extreme left or right
5369
5370         switch(entry_from) {
5371
5372         case ENTRY_DIRECTION_RIGHT:
5373                 cur.posVisToRowExtremity(false /* !left */);
5374                 break;
5375         case ENTRY_DIRECTION_LEFT:
5376                 cur.posVisToRowExtremity(true /* left */);
5377                 break;
5378         case ENTRY_DIRECTION_IGNORE:
5379                 // nothing to do in this case
5380                 break;
5381
5382         }
5383         cur.setCurrentFont();
5384 }
5385
5386
5387 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
5388 {
5389         row_type const row = tabular.cellRow(cur.idx());
5390         col_type const col = tabular.cellColumn(cur.idx());
5391
5392         if (isRightToLeft(cur)) {
5393                 if (cur.idx() == tabular.getLastCellInRow(row)) {
5394                         if (row == 0)
5395                                 return;
5396                         cur.idx() = tabular.getFirstCellInRow(row);
5397                         cur.idx() = tabular.cellAbove(cur.idx());
5398                 } else {
5399                         if (tabular.isLastCell(cur.idx()))
5400                                 return;
5401                         if (cur.idx() == tabular.getLastCellInRow(row))
5402                                 cur.idx() = tabular.cellIndex(row + 1, 0);
5403                         else
5404                                 cur.idx() = tabular.cellIndex(row, col + 1);
5405                 }
5406         } else {
5407                 if (cur.idx() == 0) // first cell
5408                         return;
5409                 if (col == 0)
5410                         cur.idx() = tabular.getLastCellInRow(row - 1);
5411                 else
5412                         cur.idx() = tabular.cellIndex(row, col - 1);
5413         }
5414
5415         if (cur.selIsMultiCell()) {
5416                 cur.pit() = cur.lastpit();
5417                 cur.pos() = cur.lastpos();
5418                 return;
5419         }
5420
5421         cur.pit() = cur.lastpit();
5422         cur.pos() = cur.lastpos();
5423
5424         // in visual mode, place cursor at extreme left or right
5425
5426         switch(entry_from) {
5427
5428         case ENTRY_DIRECTION_RIGHT:
5429                 cur.posVisToRowExtremity(false /* !left */);
5430                 break;
5431         case ENTRY_DIRECTION_LEFT:
5432                 cur.posVisToRowExtremity(true /* left */);
5433                 break;
5434         case ENTRY_DIRECTION_IGNORE:
5435                 // nothing to do in this case
5436                 break;
5437
5438         }
5439         cur.setCurrentFont();
5440 }
5441
5442
5443 void InsetTabular::tabularFeatures(Cursor & cur, string const & argument)
5444 {
5445         cur.recordUndoInset(this);
5446
5447         istringstream is(argument);
5448         // limit the size of strings we read to avoid memory problems
5449         is >> setw(65636);
5450         string s;
5451         // Safe guard.
5452         size_t safe_guard = 0;
5453         for (;;) {
5454                 if (is.eof())
5455                         return;
5456                 safe_guard++;
5457                 if (safe_guard > 1000) {
5458                         LYXERR0("parameter max count reached!");
5459                         return;
5460                 }
5461                 is >> s;
5462                 Tabular::Feature action = Tabular::LAST_ACTION;
5463
5464                 size_t i = 0;
5465                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
5466                         if (s != tabularFeature[i].feature)
5467                                 continue;
5468                         action = tabularFeature[i].action;
5469                         break;
5470                 }
5471                 if (action == Tabular::LAST_ACTION) {
5472                         LYXERR0("Feature not found " << s);
5473                         continue;
5474                 }
5475                 string val;
5476                 if (tabularFeature[i].need_value)
5477                         is >> val;
5478                 LYXERR(Debug::DEBUG, "Feature: " << s << "\t\tvalue: " << val);
5479                 tabularFeatures(cur, action, val);
5480         }
5481 }
5482
5483
5484 static void checkLongtableSpecial(Tabular::ltType & ltt,
5485                           string const & special, bool & flag)
5486 {
5487         if (special == "dl_above") {
5488                 ltt.topDL = flag;
5489                 ltt.set = false;
5490         } else if (special == "dl_below") {
5491                 ltt.bottomDL = flag;
5492                 ltt.set = false;
5493         } else if (special == "empty") {
5494                 ltt.empty = flag;
5495                 ltt.set = false;
5496         } else if (flag) {
5497                 ltt.empty = false;
5498                 ltt.set = true;
5499         }
5500 }
5501
5502
5503 bool InsetTabular::oneCellHasRotationState(bool rotated,
5504                 row_type row_start, row_type row_end,
5505                 col_type col_start, col_type col_end) const
5506 {
5507         for (row_type r = row_start; r <= row_end; ++r)
5508                 for (col_type c = col_start; c <= col_end; ++c)
5509                         if (rotated) {
5510                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) != 0)
5511                                         return true;
5512                         } else {
5513                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) == 0)
5514                                         return true;
5515                         }
5516         return false;
5517 }
5518
5519
5520 void InsetTabular::tabularFeatures(Cursor & cur,
5521         Tabular::Feature feature, string const & value)
5522 {
5523         col_type sel_col_start;
5524         col_type sel_col_end;
5525         row_type sel_row_start;
5526         row_type sel_row_end;
5527         bool setLines = false;
5528         LyXAlignment setAlign = LYX_ALIGN_LEFT;
5529         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
5530
5531         switch (feature) {
5532
5533         case Tabular::M_ALIGN_LEFT:
5534         case Tabular::ALIGN_LEFT:
5535                 setAlign = LYX_ALIGN_LEFT;
5536                 break;
5537
5538         case Tabular::M_ALIGN_RIGHT:
5539         case Tabular::ALIGN_RIGHT:
5540                 setAlign = LYX_ALIGN_RIGHT;
5541                 break;
5542
5543         case Tabular::M_ALIGN_CENTER:
5544         case Tabular::ALIGN_CENTER:
5545                 setAlign = LYX_ALIGN_CENTER;
5546                 break;
5547
5548         case Tabular::ALIGN_BLOCK:
5549                 setAlign = LYX_ALIGN_BLOCK;
5550                 break;
5551
5552         case Tabular::ALIGN_DECIMAL:
5553                 setAlign = LYX_ALIGN_DECIMAL;
5554                 break;
5555
5556         case Tabular::M_VALIGN_TOP:
5557         case Tabular::VALIGN_TOP:
5558                 setVAlign = Tabular::LYX_VALIGN_TOP;
5559                 break;
5560
5561         case Tabular::M_VALIGN_BOTTOM:
5562         case Tabular::VALIGN_BOTTOM:
5563                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
5564                 break;
5565
5566         case Tabular::M_VALIGN_MIDDLE:
5567         case Tabular::VALIGN_MIDDLE:
5568                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
5569                 break;
5570
5571         default:
5572                 break;
5573         }
5574
5575         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5576         row_type const row = tabular.cellRow(cur.idx());
5577         col_type const column = tabular.cellColumn(cur.idx());
5578         bool flag = true;
5579         Tabular::ltType ltt;
5580
5581         switch (feature) {
5582
5583         case Tabular::SET_TABULAR_WIDTH:
5584                 tabular.setTabularWidth(Length(value));
5585                 break;
5586
5587         case Tabular::SET_PWIDTH: {
5588                 Length const len(value);
5589                 tabular.setColumnPWidth(cur, cur.idx(), len);
5590                 if (len.zero()
5591                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
5592                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
5593                 break;
5594         }
5595
5596         case Tabular::SET_MPWIDTH:
5597                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
5598                 break;
5599
5600         case Tabular::SET_MROFFSET:
5601                 tabular.setMROffset(cur, cur.idx(), Length(value));
5602                 break;
5603
5604         case Tabular::SET_SPECIAL_COLUMN:
5605         case Tabular::SET_SPECIAL_MULTICOLUMN:
5606                 if (value == "none")
5607                         tabular.setAlignSpecial(cur.idx(), docstring(), feature);
5608                 else
5609                         tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
5610                 break;
5611
5612         case Tabular::APPEND_ROW:
5613                 // append the row into the tabular
5614                 tabular.appendRow(row);
5615                 break;
5616
5617         case Tabular::APPEND_COLUMN:
5618                 // append the column into the tabular
5619                 tabular.appendColumn(column);
5620                 cur.idx() = tabular.cellIndex(row, column);
5621                 break;
5622
5623         case Tabular::DELETE_ROW:
5624                 if (sel_row_end == tabular.nrows() - 1 && sel_row_start != 0) {
5625                         for (col_type c = 0; c < tabular.ncols(); c++)
5626                                 tabular.setBottomLine(tabular.cellIndex(sel_row_start - 1, c),
5627                                         tabular.bottomLine(tabular.cellIndex(sel_row_end, c)));
5628                 }
5629
5630                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5631                         tabular.deleteRow(sel_row_start);
5632                 if (sel_row_start >= tabular.nrows())
5633                         --sel_row_start;
5634                 cur.idx() = tabular.cellIndex(sel_row_start, column);
5635                 cur.pit() = 0;
5636                 cur.pos() = 0;
5637                 cur.selection(false);
5638                 break;
5639
5640         case Tabular::DELETE_COLUMN:
5641                 if (sel_col_end == tabular.ncols() - 1 && sel_col_start != 0) {
5642                         for (row_type r = 0; r < tabular.nrows(); r++)
5643                                 tabular.setRightLine(tabular.cellIndex(r, sel_col_start - 1),
5644                                         tabular.rightLine(tabular.cellIndex(r, sel_col_end)));
5645                 }
5646
5647                 if (sel_col_start == 0 && sel_col_end != tabular.ncols() - 1) {
5648                         for (row_type r = 0; r < tabular.nrows(); r++)
5649                                 tabular.setLeftLine(tabular.cellIndex(r, sel_col_end + 1),
5650                                         tabular.leftLine(tabular.cellIndex(r, 0)));
5651                 }
5652
5653                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5654                         tabular.deleteColumn(sel_col_start);
5655                 if (sel_col_start >= tabular.ncols())
5656                         --sel_col_start;
5657                 cur.idx() = tabular.cellIndex(row, sel_col_start);
5658                 cur.pit() = 0;
5659                 cur.pos() = 0;
5660                 cur.selection(false);
5661                 break;
5662
5663         case Tabular::COPY_ROW:
5664                 tabular.copyRow(row);
5665                 break;
5666
5667         case Tabular::COPY_COLUMN:
5668                 tabular.copyColumn(column);
5669                 cur.idx() = tabular.cellIndex(row, column);
5670                 break;
5671
5672         case Tabular::MOVE_COLUMN_RIGHT:
5673                 tabular.moveColumn(column, Tabular::RIGHT);
5674                 cur.idx() = tabular.cellIndex(row, column + 1);
5675                 break;
5676
5677         case Tabular::MOVE_COLUMN_LEFT:
5678                 tabular.moveColumn(column, Tabular::LEFT);
5679                 cur.idx() = tabular.cellIndex(row, column - 1);
5680                 break;
5681
5682         case Tabular::MOVE_ROW_DOWN:
5683                 tabular.moveRow(row, Tabular::DOWN);
5684                 cur.idx() = tabular.cellIndex(row + 1, column);
5685                 break;
5686
5687         case Tabular::MOVE_ROW_UP:
5688                 tabular.moveRow(row, Tabular::UP);
5689                 cur.idx() = tabular.cellIndex(row - 1, column);
5690                 break;
5691
5692         case Tabular::SET_LINE_TOP:
5693         case Tabular::TOGGLE_LINE_TOP: {
5694                 bool lineSet = (feature == Tabular::SET_LINE_TOP)
5695                                ? (value == "true") : !tabular.topLine(cur.idx());
5696                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5697                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5698                                 tabular.setTopLine(tabular.cellIndex(r, c), lineSet);
5699                 break;
5700         }
5701
5702         case Tabular::SET_LINE_BOTTOM:
5703         case Tabular::TOGGLE_LINE_BOTTOM: {
5704                 bool lineSet = (feature == Tabular::SET_LINE_BOTTOM)
5705                                ? (value == "true") : !tabular.bottomLine(cur.idx());
5706                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5707                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5708                                 tabular.setBottomLine(tabular.cellIndex(r, c), lineSet);
5709                 break;
5710         }
5711
5712         case Tabular::SET_LINE_LEFT:
5713         case Tabular::TOGGLE_LINE_LEFT: {
5714                 bool lineSet = (feature == Tabular::SET_LINE_LEFT)
5715                                ? (value == "true") : !tabular.leftLine(cur.idx());
5716                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5717                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5718                                 tabular.setLeftLine(tabular.cellIndex(r, c), lineSet);
5719                 break;
5720         }
5721
5722         case Tabular::SET_LINE_RIGHT:
5723         case Tabular::TOGGLE_LINE_RIGHT: {
5724                 bool lineSet = (feature == Tabular::SET_LINE_RIGHT)
5725                                ? (value == "true") : !tabular.rightLine(cur.idx());
5726                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5727                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5728                                 tabular.setRightLine(tabular.cellIndex(r, c), lineSet);
5729                 break;
5730         }
5731
5732         case Tabular::M_ALIGN_LEFT:
5733         case Tabular::M_ALIGN_RIGHT:
5734         case Tabular::M_ALIGN_CENTER:
5735         case Tabular::ALIGN_LEFT:
5736         case Tabular::ALIGN_RIGHT:
5737         case Tabular::ALIGN_CENTER:
5738         case Tabular::ALIGN_BLOCK:
5739         case Tabular::ALIGN_DECIMAL:
5740                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5741                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5742                                 tabular.setAlignment(tabular.cellIndex(r, c), setAlign,
5743                                 !tabular.getPWidth(c).zero());
5744                 break;
5745
5746         case Tabular::M_VALIGN_TOP:
5747         case Tabular::M_VALIGN_BOTTOM:
5748         case Tabular::M_VALIGN_MIDDLE:
5749                 flag = false;
5750                 // fall through
5751         case Tabular::VALIGN_TOP:
5752         case Tabular::VALIGN_BOTTOM:
5753         case Tabular::VALIGN_MIDDLE:
5754                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5755                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5756                                 tabular.setVAlignment(tabular.cellIndex(r, c), setVAlign, flag);
5757                 break;
5758
5759         case Tabular::SET_MULTICOLUMN: {
5760                 if (!cur.selection()) {
5761                         // just multicol for one single cell
5762                         // check whether we are completely in a multicol
5763                         if (!tabular.isMultiColumn(cur.idx()))
5764                                 tabular.setMultiColumn(cur.idx(), 1,
5765                                         tabular.rightLine(cur.idx()));
5766                         break;
5767                 }
5768                 // we have a selection so this means we just add all these
5769                 // cells to form a multicolumn cell
5770                 idx_type const s_start = cur.selBegin().idx();
5771                 row_type const col_start = tabular.cellColumn(s_start);
5772                 row_type const col_end = tabular.cellColumn(cur.selEnd().idx());
5773                 cur.idx() = tabular.setMultiColumn(s_start, col_end - col_start + 1,
5774                                                    tabular.rightLine(cur.selEnd().idx()));
5775                 cur.pit() = 0;
5776                 cur.pos() = 0;
5777                 cur.selection(false);
5778                 break;
5779         }
5780
5781         case Tabular::UNSET_MULTICOLUMN: {
5782                 if (!cur.selection()) {
5783                         if (tabular.isMultiColumn(cur.idx()))
5784                                 tabular.unsetMultiColumn(cur.idx());
5785                 }
5786                 break;
5787         }
5788
5789         case Tabular::MULTICOLUMN: {
5790                 if (!cur.selection()) {
5791                         if (tabular.isMultiColumn(cur.idx()))
5792                                 tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5793                         else
5794                                 tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5795                         break;
5796                 }
5797                 bool merge = false;
5798                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5799                         row_type const r = sel_row_start;
5800                         if (!tabular.isMultiColumn(tabular.cellIndex(r, c))
5801                             || (r > sel_row_start && !tabular.isPartOfMultiColumn(r, c)))
5802                                 merge = true;
5803                 }
5804                 // If the selection contains at least one singlecol cell
5805                 // or multiple multicol cells,
5806                 // we assume the user will merge is to a single multicol
5807                 if (merge)
5808                         tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5809                 else
5810                         tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5811                 break;
5812         }
5813
5814         case Tabular::SET_MULTIROW: {
5815                 if (!cur.selection()) {
5816                         // just multirow for one single cell
5817                         // check whether we are completely in a multirow
5818                         if (!tabular.isMultiRow(cur.idx()))
5819                                 tabular.setMultiRow(cur.idx(), 1,
5820                                                     tabular.bottomLine(cur.idx()),
5821                                                     tabular.getAlignment(cur.idx()));
5822                         break;
5823                 }
5824                 // we have a selection so this means we just add all this
5825                 // cells to form a multirow cell
5826                 idx_type const s_start = cur.selBegin().idx();
5827                 row_type const row_start = tabular.cellRow(s_start);
5828                 row_type const row_end = tabular.cellRow(cur.selEnd().idx());
5829                 cur.idx() = tabular.setMultiRow(s_start, row_end - row_start + 1,
5830                                                 tabular.bottomLine(cur.selEnd().idx()),
5831                                                 tabular.getAlignment(cur.selEnd().idx()));
5832                 cur.pit() = 0;
5833                 cur.pos() = 0;
5834                 cur.selection(false);
5835                 break;
5836         }
5837
5838         case Tabular::UNSET_MULTIROW: {
5839                 if (!cur.selection()) {
5840                         if (tabular.isMultiRow(cur.idx()))
5841                                 tabular.unsetMultiRow(cur.idx());
5842                 }
5843                 break;
5844         }
5845
5846         case Tabular::MULTIROW: {
5847                 if (!cur.selection()) {
5848                         if (tabular.isMultiRow(cur.idx()))
5849                                 tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5850                         else
5851                                 tabularFeatures(cur, Tabular::SET_MULTIROW);
5852                         break;
5853                 }
5854                 bool merge = false;
5855                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5856                         col_type const c = sel_col_start;
5857                         if (!tabular.isMultiRow(tabular.cellIndex(r, c))
5858                             || (r > sel_row_start && !tabular.isPartOfMultiRow(r, c)))
5859                                 merge = true;
5860                 }
5861                 // If the selection contains at least one singlerow cell
5862                 // or multiple multirow cells,
5863                 // we assume the user will merge is to a single multirow
5864                 if (merge)
5865                         tabularFeatures(cur, Tabular::SET_MULTIROW);
5866                 else
5867                         tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5868                 break;
5869         }
5870
5871         case Tabular::SET_ALL_LINES:
5872                 setLines = true;
5873                 // fall through
5874         case Tabular::UNSET_ALL_LINES:
5875                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5876                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5877                                 idx_type const cell = tabular.cellIndex(r, c);
5878                                 tabular.setTopLine(cell, setLines);
5879                                 tabular.setBottomLine(cell, setLines);
5880                                 tabular.setRightLine(cell, setLines);
5881                                 tabular.setLeftLine(cell, setLines);
5882                         }
5883                 break;
5884
5885         case Tabular::SET_BORDER_LINES:
5886                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5887                         tabular.setLeftLine(tabular.cellIndex(r, sel_col_start), true);
5888                         tabular.setRightLine(tabular.cellIndex(r, sel_col_end), true);
5889                 }
5890                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5891                         tabular.setTopLine(tabular.cellIndex(sel_row_start, c), true);
5892                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, c), true);
5893                 }
5894                 break;
5895
5896         case Tabular::TOGGLE_LONGTABULAR:
5897                 if (tabular.is_long_tabular)
5898                         tabularFeatures(cur, Tabular::UNSET_LONGTABULAR);
5899                 else
5900                         tabular.is_long_tabular = true;
5901                 break;
5902
5903         case Tabular::SET_LONGTABULAR:
5904                 tabular.is_long_tabular = true;
5905                 break;
5906
5907         case Tabular::UNSET_LONGTABULAR:
5908                 for (row_type r = 0; r < tabular.nrows(); ++r) {
5909                         if (tabular.ltCaption(r)) {
5910                                 cur.idx() = tabular.cellIndex(r, 0);
5911                                 cur.pit() = 0;
5912                                 cur.pos() = 0;
5913                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
5914                         }
5915                 }
5916                 tabular.is_long_tabular = false;
5917                 break;
5918
5919         case Tabular::SET_ROTATE_TABULAR:
5920                 tabular.rotate = convert<int>(value);
5921                 break;
5922
5923         case Tabular::UNSET_ROTATE_TABULAR:
5924                 tabular.rotate = 0;
5925                 break;
5926
5927         case Tabular::TOGGLE_ROTATE_TABULAR:
5928                 // when pressing the rotate button we default to 90° rotation
5929                 tabular.rotate != 0 ? tabular.rotate = 0 : tabular.rotate = 90;
5930                 break;
5931
5932         case Tabular::TABULAR_VALIGN_TOP:
5933                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
5934                 break;
5935
5936         case Tabular::TABULAR_VALIGN_MIDDLE:
5937                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
5938                 break;
5939
5940         case Tabular::TABULAR_VALIGN_BOTTOM:
5941                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
5942                 break;
5943
5944         case Tabular::LONGTABULAR_ALIGN_LEFT:
5945                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
5946                 break;
5947
5948         case Tabular::LONGTABULAR_ALIGN_CENTER:
5949                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
5950                 break;
5951
5952         case Tabular::LONGTABULAR_ALIGN_RIGHT:
5953                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
5954                 break;
5955
5956
5957
5958         case Tabular::SET_ROTATE_CELL:
5959                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5960                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5961                                 tabular.setRotateCell(tabular.cellIndex(r, c), convert<int>(value));
5962                 break;
5963
5964         case Tabular::UNSET_ROTATE_CELL:
5965                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5966                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5967                                 tabular.setRotateCell(tabular.cellIndex(r, c), 0);
5968                 break;
5969
5970         case Tabular::TOGGLE_ROTATE_CELL:
5971                 {
5972                 bool oneNotRotated = oneCellHasRotationState(false,
5973                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5974
5975                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5976                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5977                                 // when pressing the rotate cell button we default to 90° rotation
5978                                 if (oneNotRotated)
5979                                         tabular.setRotateCell(tabular.cellIndex(r, c), 90);
5980                                 else
5981                                         tabular.setRotateCell(tabular.cellIndex(r, c), 0);
5982                         }
5983                 }
5984                 break;
5985
5986         case Tabular::SET_USEBOX: {
5987                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
5988                 if (val == tabular.getUsebox(cur.idx()))
5989                         val = Tabular::BOX_NONE;
5990                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5991                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5992                                 tabular.setUsebox(tabular.cellIndex(r, c), val);
5993                 break;
5994         }
5995
5996         case Tabular::UNSET_LTFIRSTHEAD:
5997                 flag = false;
5998                 // fall through
5999         case Tabular::SET_LTFIRSTHEAD:
6000                 tabular.getRowOfLTFirstHead(row, ltt);
6001                 checkLongtableSpecial(ltt, value, flag);
6002                 tabular.setLTHead(row, flag, ltt, true);
6003                 break;
6004
6005         case Tabular::UNSET_LTHEAD:
6006                 flag = false;
6007                 // fall through
6008         case Tabular::SET_LTHEAD:
6009                 tabular.getRowOfLTHead(row, ltt);
6010                 checkLongtableSpecial(ltt, value, flag);
6011                 tabular.setLTHead(row, flag, ltt, false);
6012                 break;
6013
6014         case Tabular::UNSET_LTFOOT:
6015                 flag = false;
6016                 // fall through
6017         case Tabular::SET_LTFOOT:
6018                 tabular.getRowOfLTFoot(row, ltt);
6019                 checkLongtableSpecial(ltt, value, flag);
6020                 tabular.setLTFoot(row, flag, ltt, false);
6021                 break;
6022
6023         case Tabular::UNSET_LTLASTFOOT:
6024                 flag = false;
6025                 // fall through
6026         case Tabular::SET_LTLASTFOOT:
6027                 tabular.getRowOfLTLastFoot(row, ltt);
6028                 checkLongtableSpecial(ltt, value, flag);
6029                 tabular.setLTFoot(row, flag, ltt, true);
6030                 break;
6031
6032         case Tabular::UNSET_LTNEWPAGE:
6033                 flag = false;
6034                 // fall through
6035         case Tabular::SET_LTNEWPAGE:
6036                 tabular.setLTNewPage(row, flag);
6037                 break;
6038
6039         case Tabular::SET_LTCAPTION: {
6040                 if (tabular.ltCaption(row))
6041                         break;
6042                 cur.idx() = tabular.setLTCaption(row, true);
6043                 cur.pit() = 0;
6044                 cur.pos() = 0;
6045                 cur.selection(false);
6046                 // If a row is set as caption, then also insert
6047                 // a caption. Otherwise the LaTeX output is broken.
6048                 // Select cell if it is non-empty
6049                 if (cur.lastpos() > 0 || cur.lastpit() > 0)
6050                         lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
6051                 lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
6052                 break;
6053         }
6054
6055         case Tabular::UNSET_LTCAPTION: {
6056                 if (!tabular.ltCaption(row))
6057                         break;
6058                 cur.idx() = tabular.setLTCaption(row, false);
6059                 cur.pit() = 0;
6060                 cur.pos() = 0;
6061                 cur.selection(false);
6062                 FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
6063                 if (lyx::getStatus(fr).enabled())
6064                         lyx::dispatch(fr);
6065                 break;
6066         }
6067
6068         case Tabular::TOGGLE_LTCAPTION: {
6069                 if (tabular.ltCaption(row))
6070                         tabularFeatures(cur, Tabular::UNSET_LTCAPTION);
6071                 else
6072                         tabularFeatures(cur, Tabular::SET_LTCAPTION);
6073                 break;
6074         }
6075
6076         case Tabular::TOGGLE_BOOKTABS:
6077                 tabular.use_booktabs = !tabular.use_booktabs;
6078                 break;
6079
6080         case Tabular::SET_BOOKTABS:
6081                 tabular.use_booktabs = true;
6082                 break;
6083
6084         case Tabular::UNSET_BOOKTABS:
6085                 tabular.use_booktabs = false;
6086                 break;
6087
6088         case Tabular::SET_TOP_SPACE: {
6089                 Length len;
6090                 if (value == "default")
6091                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6092                                 tabular.row_info[r].top_space_default = true;
6093                 else if (value == "none")
6094                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6095                                 tabular.row_info[r].top_space_default = false;
6096                                 tabular.row_info[r].top_space = len;
6097                         }
6098                 else if (isValidLength(value, &len))
6099                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6100                                 tabular.row_info[r].top_space_default = false;
6101                                 tabular.row_info[r].top_space = len;
6102                         }
6103                 break;
6104         }
6105
6106         case Tabular::SET_BOTTOM_SPACE: {
6107                 Length len;
6108                 if (value == "default")
6109                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6110                                 tabular.row_info[r].bottom_space_default = true;
6111                 else if (value == "none")
6112                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6113                                 tabular.row_info[r].bottom_space_default = false;
6114                                 tabular.row_info[r].bottom_space = len;
6115                         }
6116                 else if (isValidLength(value, &len))
6117                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6118                                 tabular.row_info[r].bottom_space_default = false;
6119                                 tabular.row_info[r].bottom_space = len;
6120                         }
6121                 break;
6122         }
6123
6124         case Tabular::SET_INTERLINE_SPACE: {
6125                 Length len;
6126                 if (value == "default")
6127                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
6128                                 tabular.row_info[r].interline_space_default = true;
6129                 else if (value == "none")
6130                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6131                                 tabular.row_info[r].interline_space_default = false;
6132                                 tabular.row_info[r].interline_space = len;
6133                         }
6134                 else if (isValidLength(value, &len))
6135                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
6136                                 tabular.row_info[r].interline_space_default = false;
6137                                 tabular.row_info[r].interline_space = len;
6138                         }
6139                 break;
6140         }
6141
6142         case Tabular::SET_DECIMAL_POINT:
6143                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
6144                         tabular.column_info[c].decimal_point = from_utf8(value);
6145                 break;
6146
6147         // dummy stuff just to avoid warnings
6148         case Tabular::LAST_ACTION:
6149                 break;
6150         }
6151 }
6152
6153
6154 bool InsetTabular::copySelection(Cursor & cur)
6155 {
6156         if (!cur.selection())
6157                 return false;
6158
6159         row_type rs, re;
6160         col_type cs, ce;
6161         getSelection(cur, rs, re, cs, ce);
6162
6163         paste_tabular.reset(new Tabular(tabular));
6164
6165         for (row_type r = 0; r < rs; ++r)
6166                 paste_tabular->deleteRow(0);
6167
6168         row_type const rows = re - rs + 1;
6169         while (paste_tabular->nrows() > rows)
6170                 paste_tabular->deleteRow(rows);
6171
6172         for (col_type c = 0; c < cs; ++c)
6173                 paste_tabular->deleteColumn(0);
6174
6175         col_type const columns = ce - cs + 1;
6176         while (paste_tabular->ncols() > columns)
6177                 paste_tabular->deleteColumn(columns);
6178
6179         paste_tabular->setBuffer(tabular.buffer());
6180
6181         odocstringstream os;
6182         OutputParams const runparams(0);
6183         paste_tabular->plaintext(os, runparams, 0, true, '\t', INT_MAX);
6184         // Needed for the "Edit->Paste recent" menu and the system clipboard.
6185         cap::copySelection(cur, os.str());
6186
6187         // mark tabular stack dirty
6188         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
6189         // when we (hopefully) have a one-for-all paste mechanism.
6190         // This must be called after cap::copySelection.
6191         dirtyTabularStack(true);
6192
6193         return true;
6194 }
6195
6196
6197 bool InsetTabular::pasteClipboard(Cursor & cur)
6198 {
6199         if (!paste_tabular)
6200                 return false;
6201         col_type actcol = tabular.cellColumn(cur.idx());
6202         row_type actrow = tabular.cellRow(cur.idx());
6203
6204         if (cur.selIsMultiCell()) {
6205                 row_type re;
6206                 col_type ce;
6207                 getSelection(cur, actrow, re, actcol, ce);
6208         }
6209
6210         for (row_type r1 = 0, r2 = actrow;
6211              r1 < paste_tabular->nrows() && r2 < tabular.nrows();
6212              ++r1, ++r2) {
6213                 for (col_type c1 = 0, c2 = actcol;
6214                     c1 < paste_tabular->ncols() && c2 < tabular.ncols();
6215                     ++c1, ++c2) {
6216                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
6217                               tabular.isPartOfMultiColumn(r2, c2))
6218                                 continue;
6219                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
6220                                 --c2;
6221                                 continue;
6222                         }
6223                         if (tabular.isPartOfMultiColumn(r2, c2)) {
6224                                 --c1;
6225                                 continue;
6226                         }
6227                         shared_ptr<InsetTableCell> inset(
6228                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
6229                         tabular.setCellInset(r2, c2, inset);
6230                         // FIXME?: why do we need to do this explicitly? (EL)
6231                         tabular.cellInset(r2, c2)->setBuffer(tabular.buffer());
6232
6233                         // FIXME: change tracking (MG)
6234                         inset->setChange(Change(buffer().params().track_changes ?
6235                                                 Change::INSERTED : Change::UNCHANGED));
6236                         cur.pos() = 0;
6237                         cur.pit() = 0;
6238                 }
6239         }
6240         return true;
6241 }
6242
6243
6244 void InsetTabular::cutSelection(Cursor & cur)
6245 {
6246         if (!cur.selection())
6247                 return;
6248
6249         row_type rs, re;
6250         col_type cs, ce;
6251         getSelection(cur, rs, re, cs, ce);
6252         for (row_type r = rs; r <= re; ++r) {
6253                 for (col_type c = cs; c <= ce; ++c) {
6254                         shared_ptr<InsetTableCell> t
6255                                 = cell(tabular.cellIndex(r, c));
6256                         if (buffer().params().track_changes)
6257                                 // FIXME: Change tracking (MG)
6258                                 t->setChange(Change(Change::DELETED));
6259                         else
6260                                 t->clear();
6261                 }
6262         }
6263
6264         // cursor position might be invalid now
6265         if (cur.pit() > cur.lastpit())
6266                 cur.pit() = cur.lastpit();
6267         if (cur.pos() > cur.lastpos())
6268                 cur.pos() = cur.lastpos();
6269         cur.clearSelection();
6270 }
6271
6272
6273 bool InsetTabular::isRightToLeft(Cursor & cur) const
6274 {
6275         // LASSERT: It might be better to abandon this Buffer.
6276         LASSERT(cur.depth() > 1, return false);
6277         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
6278         pos_type const parentpos = cur[cur.depth() - 2].pos();
6279         return parentpar.getFontSettings(buffer().params(),
6280                                          parentpos).language()->rightToLeft();
6281 }
6282
6283
6284 docstring InsetTabular::asString(idx_type stidx, idx_type enidx,
6285                                  bool intoInsets)
6286 {
6287         LASSERT(stidx <= enidx, return docstring());
6288         docstring retval;
6289         col_type const col1 = tabular.cellColumn(stidx);
6290         col_type const col2 = tabular.cellColumn(enidx);
6291         row_type const row1 = tabular.cellRow(stidx);
6292         row_type const row2 = tabular.cellRow(enidx);
6293         bool first = true;
6294         for (col_type col = col1; col <= col2; col++)
6295                 for (row_type row = row1; row <= row2; row++) {
6296                         if (!first)
6297                                 retval += "\n";
6298                         else
6299                                 first = false;
6300                         retval += tabular.cellInset(row, col)->asString(intoInsets);
6301                 }
6302         return retval;
6303 }
6304
6305
6306 void InsetTabular::getSelection(Cursor & cur,
6307         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
6308 {
6309         CursorSlice const & beg = cur.selBegin();
6310         CursorSlice const & end = cur.selEnd();
6311         cs = tabular.cellColumn(beg.idx());
6312         ce = tabular.cellColumn(end.idx());
6313         if (cs > ce)
6314                 swap(cs, ce);
6315
6316         rs = tabular.cellRow(beg.idx());
6317         re = tabular.cellRow(end.idx());
6318         if (rs > re)
6319                 swap(rs, re);
6320 }
6321
6322
6323 Text * InsetTabular::getText(int idx) const
6324 {
6325         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
6326 }
6327
6328
6329 void InsetTabular::setChange(Change const & change)
6330 {
6331         for (idx_type idx = 0; idx < nargs(); ++idx)
6332                 cell(idx)->setChange(change);
6333 }
6334
6335
6336 void InsetTabular::acceptChanges()
6337 {
6338         for (idx_type idx = 0; idx < nargs(); ++idx)
6339                 cell(idx)->acceptChanges();
6340 }
6341
6342
6343 void InsetTabular::rejectChanges()
6344 {
6345         for (idx_type idx = 0; idx < nargs(); ++idx)
6346                 cell(idx)->rejectChanges();
6347 }
6348
6349
6350 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
6351 {
6352         return tabular.getPWidth(cell).zero();
6353 }
6354
6355
6356 bool InsetTabular::forcePlainLayout(idx_type cell) const
6357 {
6358         return !tabular.getPWidth(cell).zero();
6359 }
6360
6361
6362 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
6363                                      bool usePaste)
6364 {
6365         if (buf.length() <= 0)
6366                 return true;
6367
6368         col_type cols = 1;
6369         row_type rows = 1;
6370         col_type maxCols = 1;
6371         size_t const len = buf.length();
6372         size_t p = 0;
6373
6374         while (p < len &&
6375                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
6376                 switch (buf[p]) {
6377                 case '\t':
6378                         ++cols;
6379                         break;
6380                 case '\n':
6381                         if (p + 1 < len)
6382                                 ++rows;
6383                         maxCols = max(cols, maxCols);
6384                         cols = 1;
6385                         break;
6386                 }
6387                 ++p;
6388         }
6389         maxCols = max(cols, maxCols);
6390         Tabular * loctab;
6391         idx_type cell = 0;
6392         col_type ocol = 0;
6393         row_type row = 0;
6394         if (usePaste) {
6395                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
6396                 loctab = paste_tabular.get();
6397                 dirtyTabularStack(true);
6398         } else {
6399                 loctab = &tabular;
6400                 cell = bv.cursor().idx();
6401                 ocol = tabular.cellColumn(cell);
6402                 row = tabular.cellRow(cell);
6403         }
6404
6405         size_t op = 0;
6406         idx_type const cells = loctab->numberofcells;
6407         p = 0;
6408         cols = ocol;
6409         rows = loctab->nrows();
6410         col_type const columns = loctab->ncols();
6411
6412         while (cell < cells && p < len && row < rows &&
6413                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
6414         {
6415                 if (p >= len)
6416                         break;
6417                 switch (buf[p]) {
6418                 case '\t':
6419                         // we can only set this if we are not too far right
6420                         if (cols < columns) {
6421                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6422                                 Font const font = bv.textMetrics(&inset->text()).
6423                                         displayFont(0, 0);
6424                                 inset->setText(buf.substr(op, p - op), font,
6425                                                buffer().params().track_changes);
6426                                 ++cols;
6427                                 ++cell;
6428                         }
6429                         break;
6430                 case '\n':
6431                         // we can only set this if we are not too far right
6432                         if (cols < columns) {
6433                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
6434                                 Font const font = bv.textMetrics(&inset->text()).
6435                                         displayFont(0, 0);
6436                                 inset->setText(buf.substr(op, p - op), font,
6437                                                buffer().params().track_changes);
6438                         }
6439                         cols = ocol;
6440                         ++row;
6441                         if (row < rows)
6442                                 cell = loctab->cellIndex(row, cols);
6443                         break;
6444                 }
6445                 ++p;
6446                 op = p;
6447         }
6448         // check for the last cell if there is no trailing '\n'
6449         if (cell < cells && op < len) {
6450                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6451                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
6452                 inset->setText(buf.substr(op, len - op), font,
6453                         buffer().params().track_changes);
6454         }
6455         return true;
6456 }
6457
6458
6459 void InsetTabular::addPreview(DocIterator const & inset_pos,
6460         PreviewLoader & loader) const
6461 {
6462         DocIterator cell_pos = inset_pos;
6463
6464         cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
6465         for (row_type r = 0; r < tabular.nrows(); ++r) {
6466                 for (col_type c = 0; c < tabular.ncols(); ++c) {
6467                         cell_pos.top().idx() = tabular.cellIndex(r, c);
6468                         tabular.cellInset(r, c)->addPreview(cell_pos, loader);
6469                 }
6470         }
6471 }
6472
6473
6474 bool InsetTabular::completionSupported(Cursor const & cur) const
6475 {
6476         Cursor const & bvCur = cur.bv().cursor();
6477         if (&bvCur.inset() != this)
6478                 return false;
6479         return cur.text()->completionSupported(cur);
6480 }
6481
6482
6483 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
6484 {
6485         return completionSupported(cur);
6486 }
6487
6488
6489 bool InsetTabular::automaticInlineCompletion() const
6490 {
6491         return lyxrc.completion_inline_text;
6492 }
6493
6494
6495 bool InsetTabular::automaticPopupCompletion() const
6496 {
6497         return lyxrc.completion_popup_text;
6498 }
6499
6500
6501 bool InsetTabular::showCompletionCursor() const
6502 {
6503         return lyxrc.completion_cursor_text;
6504 }
6505
6506
6507 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
6508 {
6509         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
6510 }
6511
6512
6513 docstring InsetTabular::completionPrefix(Cursor const & cur) const
6514 {
6515         if (!completionSupported(cur))
6516                 return docstring();
6517         return cur.text()->completionPrefix(cur);
6518 }
6519
6520
6521 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
6522 {
6523         if (!completionSupported(cur))
6524                 return false;
6525
6526         return cur.text()->insertCompletion(cur, s, finished);
6527 }
6528
6529
6530 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y,
6531                                     Dimension & dim) const
6532 {
6533         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
6534         tm.completionPosAndDim(cur, x, y, dim);
6535 }
6536
6537
6538 void InsetTabular::string2params(string const & in, InsetTabular & inset)
6539 {
6540         istringstream data(in);
6541         Lexer lex;
6542         lex.setStream(data);
6543
6544         if (in.empty())
6545                 return;
6546
6547         string token;
6548         lex >> token;
6549         if (!lex || token != "tabular") {
6550                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
6551                 return;
6552         }
6553
6554         // This is part of the inset proper that is usually swallowed
6555         // by Buffer::readInset
6556         lex >> token;
6557         if (!lex || token != "Tabular") {
6558                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
6559                 return;
6560         }
6561
6562         inset.read(lex);
6563 }
6564
6565
6566 string InsetTabular::params2string(InsetTabular const & inset)
6567 {
6568         ostringstream data;
6569         data << "tabular" << ' ';
6570         inset.write(data);
6571         data << "\\end_inset\n";
6572         return data.str();
6573 }
6574
6575
6576 void InsetTabular::setLayoutForHiddenCells(DocumentClass const & dc)
6577 {
6578         for (Tabular::col_type c = 0; c < tabular.ncols(); ++c) {
6579                 for (Tabular::row_type r = 0; r < tabular.nrows(); ++r) {
6580                         if (!tabular.isPartOfMultiColumn(r,c) &&
6581                             !tabular.isPartOfMultiRow(r,c))
6582                                 continue;
6583
6584                         ParagraphList & parlist = tabular.cellInset(r,c)->paragraphs();
6585                         ParagraphList::iterator it = parlist.begin();
6586                         ParagraphList::iterator const en = parlist.end();
6587                         for (; it != en; ++it)
6588                                         it->setLayout(dc.plainLayout());
6589                 }
6590         }
6591 }
6592
6593
6594 } // namespace lyx