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