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