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