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