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