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