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