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