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