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