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