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