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