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