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