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