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