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