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