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