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