]> git.lyx.org Git - features.git/blob - src/insets/InsetTabular.cpp
Add a member to TocItem that tells us whether the item in question
[features.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 void InsetTabular::write(ostream & os) const
3484 {
3485         os << "Tabular" << endl;
3486         tabular.write(os);
3487 }
3488
3489
3490 string InsetTabular::contextMenu(BufferView const &, int, int) const
3491 {
3492         // FIXME: depending on the selection state,
3493         // we could offer a different menu.
3494         return cell(0)->contextMenuName() + ";" + contextMenuName();
3495 }
3496
3497
3498 string InsetTabular::contextMenuName() const
3499 {
3500         return "context-tabular";
3501 }
3502
3503
3504 void InsetTabular::read(Lexer & lex)
3505 {
3506         //bool const old_format = (lex.getString() == "\\LyXTable");
3507
3508         tabular.read(lex);
3509
3510         //if (old_format)
3511         //      return;
3512
3513         lex.next();
3514         string token = lex.getString();
3515         while (lex && token != "\\end_inset") {
3516                 lex.next();
3517                 token = lex.getString();
3518         }
3519         if (!lex)
3520                 lex.printError("Missing \\end_inset at this point. ");
3521 }
3522
3523
3524 int InsetTabular::rowFromY(Cursor & cur, int y) const
3525 {
3526         // top y coordinate of tabular
3527         int h = yo(cur.bv()) - tabular.rowAscent(0) + offset_valign_;
3528         row_type r = 0;
3529         for (; r < tabular.nrows() && y > h; ++r)
3530                 h += tabular.rowAscent(r) + tabular.rowDescent(r)
3531                         + tabular.interRowSpace(r);
3532
3533         return r - 1;
3534 }
3535
3536
3537 int InsetTabular::columnFromX(Cursor & cur, int x) const
3538 {
3539         // left x coordinate of tabular
3540         int w = xo(cur.bv()) + ADD_TO_TABULAR_WIDTH;
3541         col_type c = 0;
3542         for (; c < tabular.ncols() && x > w; ++c)
3543                 w += tabular.cellWidth(c);
3544         return c - 1;
3545 }
3546
3547
3548 void InsetTabular::metrics(MetricsInfo & mi, Dimension & dim) const
3549 {
3550         //lyxerr << "InsetTabular::metrics: " << mi.base.bv << " width: " <<
3551         //      mi.base.textwidth << "\n";
3552         if (!mi.base.bv) {
3553                 LYXERR0("need bv");
3554                 LASSERT(false, /**/);
3555         }
3556
3557         for (row_type r = 0; r < tabular.nrows(); ++r) {
3558                 int maxasc = 0;
3559                 int maxdes = 0;
3560                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3561                         if (tabular.isPartOfMultiColumn(r, c)
3562                                 || tabular.isPartOfMultiRow(r, c))
3563                                 // multicolumn or multirow cell, but not first one
3564                                 continue;
3565                         idx_type const cell = tabular.cellIndex(r, c);
3566                         Dimension dim;
3567                         MetricsInfo m = mi;
3568                         Length const p_width = tabular.getPWidth(cell);
3569                         if (!p_width.zero())
3570                                 m.base.textwidth = p_width.inPixels(mi.base.textwidth);
3571                         tabular.cellInset(cell)->metrics(m, dim);
3572                         if (!p_width.zero())
3573                                 dim.wid = m.base.textwidth;
3574                         tabular.cellInfo(cell).width = dim.wid + 2 * WIDTH_OF_LINE 
3575                                 + tabular.interColumnSpace(cell);
3576
3577                         // FIXME(?): do we need a second metrics call?
3578                         TextMetrics const & tm = 
3579                                 mi.base.bv->textMetrics(tabular.cellInset(cell)->getText(0));
3580
3581                         // determine horizontal offset because of decimal align (if necessary)
3582                         int decimal_width = 0;
3583                         if (tabular.getAlignment(cell) == LYX_ALIGN_DECIMAL) {
3584                                 InsetTableCell tail = InsetTableCell(*tabular.cellInset(cell).get());
3585                                 tail.setBuffer(tabular.buffer());
3586                                 // we need to set macrocontext position everywhere
3587                                 // otherwise we crash with nested insets (e.g. footnotes)
3588                                 // after decimal point
3589                                 DocIterator dit = tabular.cellInset(cell)->getText(0)->macrocontextPosition();
3590                                 dit.pop_back();
3591                                 dit.push_back(CursorSlice(tail));
3592                                 tail.setMacrocontextPositionRecursive(dit);
3593
3594                                 // remove text leading decimal point
3595                                 docstring const align_d = tabular.column_info[c].decimal_point;
3596                                 dit = separatorPos(&tail, align_d);
3597
3598                                 pit_type const psize = tail.paragraphs().front().size();
3599                                 if (dit) {
3600                                         tail.paragraphs().front().eraseChars(0,
3601                                                 dit.pos() < psize ? dit.pos() + 1 : psize, false);
3602                                         Dimension dim1;
3603                                         tail.metrics(m, dim1);
3604                                         decimal_width = dim1.width();
3605                                 }
3606                         }
3607                         tabular.cell_info[r][c].decimal_hoffset = tm.width() - decimal_width;
3608                         tabular.cell_info[r][c].decimal_width = decimal_width;
3609
3610                         // with LYX_VALIGN_BOTTOM the descent is relative to the last par
3611                         // = descent of text in last par + TEXT_TO_INSET_OFFSET:
3612                         int const lastpardes = tm.last().second->descent()
3613                                 + TEXT_TO_INSET_OFFSET;
3614                         int offset = 0;
3615                         switch (tabular.getVAlignment(cell)) { 
3616                                 case Tabular::LYX_VALIGN_TOP:
3617                                         break; 
3618                                 case Tabular::LYX_VALIGN_MIDDLE:
3619                                         offset = -(dim.des - lastpardes)/2; 
3620                                         break; 
3621                                 case Tabular::LYX_VALIGN_BOTTOM:
3622                                         offset = -(dim.des - lastpardes); 
3623                                         break;
3624                         }
3625                         tabular.cell_info[r][c].voffset = offset;
3626                         maxasc = max(maxasc, dim.asc - offset);
3627                         maxdes = max(maxdes, dim.des + offset);
3628                 }
3629                 int const top_space = tabular.row_info[r].top_space_default ?
3630                         default_line_space :
3631                         tabular.row_info[r].top_space.inPixels(mi.base.textwidth);
3632                 tabular.setRowAscent(r, maxasc + ADD_TO_HEIGHT + top_space);
3633                 int const bottom_space = tabular.row_info[r].bottom_space_default ?
3634                         default_line_space :
3635                         tabular.row_info[r].bottom_space.inPixels(mi.base.textwidth);
3636                 tabular.setRowDescent(r, maxdes + ADD_TO_HEIGHT + bottom_space);
3637         }
3638
3639         // for top-alignment the first horizontal table line must be exactly at
3640         // the position of the base line of the surrounding text line
3641         // for bottom alignment, the same is for the last table line
3642         switch (tabular.tabular_valignment) {
3643         case Tabular::LYX_VALIGN_BOTTOM:
3644                 offset_valign_ = tabular.rowAscent(0) - tabular.height();
3645                 break;
3646         case Tabular::LYX_VALIGN_MIDDLE:
3647                 offset_valign_ = (- tabular.height()) / 2 + tabular.rowAscent(0);
3648                 break;
3649         case Tabular::LYX_VALIGN_TOP:
3650                 offset_valign_ = tabular.rowAscent(0);
3651                 break;
3652         }
3653
3654         tabular.updateColumnWidths();
3655         dim.asc = tabular.rowAscent(0) - offset_valign_;        
3656         dim.des = tabular.height() - dim.asc;
3657         dim.wid = tabular.width() + 2 * ADD_TO_TABULAR_WIDTH;
3658 }
3659
3660
3661 bool InsetTabular::isCellSelected(Cursor & cur, row_type row, col_type col) 
3662         const
3663 {
3664         if (&cur.inset() == this && cur.selection()) {
3665                 if (cur.selIsMultiCell()) {
3666                         row_type rs, re;
3667                         col_type cs, ce;
3668                         getSelection(cur, rs, re, cs, ce);
3669                         
3670                         idx_type const cell = tabular.cellIndex(row, col);
3671                         col_type const cspan = tabular.columnSpan(cell);
3672                         row_type const rspan = tabular.rowSpan(cell);
3673                         if (col + cspan - 1 >= cs && col <= ce 
3674                                 && row + rspan - 1 >= rs && row <= re)
3675                                 return true;
3676                 } else 
3677                         if (col == tabular.cellColumn(cur.idx()) 
3678                                 && row == tabular.cellRow(cur.idx())) {
3679                         CursorSlice const & beg = cur.selBegin();
3680                         CursorSlice const & end = cur.selEnd();
3681
3682                         if ((end.lastpos() > 0 || end.lastpit() > 0)
3683                                   && end.pos() == end.lastpos() && beg.pos() == 0
3684                                   && end.pit() == end.lastpit() && beg.pit() == 0)
3685                                 return true;
3686                 }
3687         }
3688         return false;
3689 }
3690
3691
3692 void InsetTabular::draw(PainterInfo & pi, int x, int y) const
3693 {
3694         x += scx_ + ADD_TO_TABULAR_WIDTH;
3695
3696         BufferView * bv = pi.base.bv;
3697         Cursor & cur = pi.base.bv->cursor();
3698         resetPos(cur);
3699
3700         // FIXME: As the full background is painted in drawBackground(),
3701         // we have no choice but to do a full repaint for the Text cells.
3702         pi.full_repaint = true;
3703
3704         bool const original_selection_state = pi.selected;
3705
3706         idx_type idx = 0;
3707         first_visible_cell = Tabular::npos;
3708
3709         int yy = y + offset_valign_;
3710         for (row_type r = 0; r < tabular.nrows(); ++r) {
3711                 int nx = x;
3712                 for (col_type c = 0; c < tabular.ncols(); ++c) {
3713                         if (tabular.isPartOfMultiColumn(r, c))
3714                                 continue;
3715                         
3716                         idx = tabular.cellIndex(r, c);
3717                         
3718                         if (tabular.isPartOfMultiRow(r, c)) {
3719                                 nx += tabular.cellWidth(idx);
3720                                 continue;
3721                         }
3722
3723                         if (first_visible_cell == Tabular::npos)
3724                                 first_visible_cell = idx;
3725
3726                         pi.selected |= isCellSelected(cur, r, c);
3727                         int const cx = nx + tabular.textHOffset(idx);
3728                         int const cy = yy + tabular.textVOffset(idx);
3729                         // Cache the Inset position.
3730                         bv->coordCache().insets().add(cell(idx).get(), cx, cy);
3731                         cell(idx)->draw(pi, cx, cy);
3732                         drawCellLines(pi, nx, yy, r, idx);
3733                         nx += tabular.cellWidth(idx);
3734                         pi.selected = original_selection_state;
3735                 }
3736
3737                 if (r + 1 < tabular.nrows())
3738                         yy += tabular.rowDescent(r) + tabular.rowAscent(r + 1) 
3739                                 + tabular.interRowSpace(r + 1);
3740         }
3741 }
3742
3743
3744 void InsetTabular::drawBackground(PainterInfo & pi, int x, int y) const
3745 {
3746         x += scx_ + ADD_TO_TABULAR_WIDTH;
3747         y += offset_valign_ - tabular.rowAscent(0);
3748         pi.pain.fillRectangle(x, y, tabular.width(), tabular.height(),
3749                 pi.backgroundColor(this));
3750 }
3751
3752
3753 void InsetTabular::drawSelection(PainterInfo & pi, int x, int y) const
3754 {
3755         Cursor & cur = pi.base.bv->cursor();
3756         resetPos(cur);
3757
3758         x += scx_ + ADD_TO_TABULAR_WIDTH;
3759
3760         if (!cur.selection())
3761                 return;
3762         if (&cur.inset() != this)
3763                 return;
3764
3765         //resetPos(cur);
3766
3767         bool const full_cell_selected = isCellSelected(cur,
3768                 tabular.cellRow(cur.idx()), tabular.cellColumn(cur.idx()));
3769
3770         if (cur.selIsMultiCell() || full_cell_selected) {
3771                 for (row_type r = 0; r < tabular.nrows(); ++r) {
3772                         int xx = x;
3773                         for (col_type c = 0; c < tabular.ncols(); ++c) {
3774                                 if (tabular.isPartOfMultiColumn(r, c))
3775                                         continue;
3776
3777                                 idx_type const cell = tabular.cellIndex(r, c);
3778
3779                                 if (tabular.isPartOfMultiRow(r, c)) {
3780                                         xx += tabular.cellWidth(cell);
3781                                         continue;
3782                                 }
3783                                 int const w = tabular.cellWidth(cell);
3784                                 int const h = tabular.cellHeight(cell);
3785                                 int const yy = y - tabular.rowAscent(r) + offset_valign_;
3786                                 if (isCellSelected(cur, r, c))
3787                                         pi.pain.fillRectangle(xx, yy, w, h, Color_selection);
3788                                 xx += w;
3789                         }
3790                         if (r + 1 < tabular.nrows())
3791                                 y += tabular.rowDescent(r) + tabular.rowAscent(r + 1)
3792                                      + tabular.interRowSpace(r + 1);
3793                 }
3794
3795         } 
3796         // FIXME: This code has no effect because InsetTableCell does not handle
3797         // drawSelection other than the trivial implementation in Inset.
3798         //else {
3799         //      x += cellXPos(cur.idx());
3800         //      x += tabular.textHOffset(cur.idx());
3801         //      cell(cur.idx())->drawSelection(pi, x, 0 /* ignored */);
3802         //}
3803 }
3804
3805
3806 void InsetTabular::drawCellLines(PainterInfo & pi, int x, int y,
3807                                  row_type row, idx_type cell) const
3808 {
3809         y -= tabular.rowAscent(row);
3810         int const w = tabular.cellWidth(cell);
3811         int const h = tabular.cellHeight(cell);
3812         Color const linecolor = pi.textColor(Color_tabularline);
3813         Color const gridcolor = pi.textColor(Color_tabularonoffline);
3814
3815         // Top
3816         bool drawline = tabular.topLine(cell)
3817                 || (row > 0 && tabular.bottomLine(tabular.cellAbove(cell)));
3818         pi.pain.line(x, y, x + w, y,
3819                 drawline ? linecolor : gridcolor,
3820                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3821
3822         // Bottom
3823         drawline = tabular.bottomLine(cell);
3824         pi.pain.line(x, y + h, x + w, y + h,
3825                 drawline ? linecolor : gridcolor,
3826                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3827
3828         // Left
3829         col_type const col = tabular.cellColumn(cell);
3830         drawline = tabular.leftLine(cell)
3831                 || (col > 0 && tabular.rightLine(tabular.cellIndex(row, col - 1)));
3832         pi.pain.line(x, y, x, y + h,
3833                 drawline ? linecolor : gridcolor,
3834                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3835
3836         // Right
3837         x -= tabular.interColumnSpace(cell);
3838         drawline = tabular.rightLine(cell)
3839                    || (col + 1 < tabular.ncols()
3840                        && tabular.leftLine(tabular.cellIndex(row, col + 1)));
3841         pi.pain.line(x + w, y, x + w, y + h,
3842                 drawline ? linecolor : gridcolor,
3843                 drawline ? Painter::line_solid : Painter::line_onoffdash);
3844 }
3845
3846
3847 void InsetTabular::edit(Cursor & cur, bool front, EntryDirection)
3848 {
3849         //lyxerr << "InsetTabular::edit: " << this << endl;
3850         cur.finishUndo();
3851         cur.setSelection(false);
3852         cur.push(*this);
3853         if (front) {
3854                 if (isRightToLeft(cur))
3855                         cur.idx() = tabular.getLastCellInRow(0);
3856                 else
3857                         cur.idx() = 0;
3858                 cur.pit() = 0;
3859                 cur.pos() = 0;
3860         } else {
3861                 if (isRightToLeft(cur))
3862                         cur.idx() = tabular.getFirstCellInRow(tabular.nrows() - 1);
3863                 else
3864                         cur.idx() = tabular.numberofcells - 1;
3865                 cur.pit() = 0;
3866                 cur.pos() = cur.lastpos(); // FIXME crude guess
3867         }
3868         cur.setCurrentFont();
3869         // FIXME: this accesses the position cache before it is initialized
3870         //resetPos(cur);
3871         //cur.bv().fitCursor();
3872 }
3873
3874
3875 void InsetTabular::updateBuffer(ParIterator const & it, UpdateType utype)
3876 {
3877         // In a longtable, tell captions what the current float is
3878         Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
3879         string const saveflt = cnts.current_float();
3880         if (tabular.is_long_tabular)
3881                 cnts.current_float("table");
3882
3883         ParIterator it2 = it;
3884         it2.forwardPos();
3885         size_t const end = it2.nargs();
3886         for ( ; it2.idx() < end; it2.top().forwardIdx())
3887                 buffer().updateBuffer(it2, utype);
3888
3889         //reset afterwards
3890         if (tabular.is_long_tabular)
3891                 cnts.current_float(saveflt);
3892 }
3893
3894
3895 void InsetTabular::addToToc(DocIterator const & cpit, bool output_active) const
3896 {
3897         DocIterator dit = cpit;
3898         dit.forwardPos();
3899         size_t const end = dit.nargs();
3900         for ( ; dit.idx() < end; dit.top().forwardIdx())
3901                 cell(dit.idx())->addToToc(dit, output_active);
3902 }
3903
3904
3905 void InsetTabular::doDispatch(Cursor & cur, FuncRequest & cmd)
3906 {
3907         LYXERR(Debug::DEBUG, "# InsetTabular::doDispatch: cmd: " << cmd
3908                              << "\n  cur:" << cur);
3909         CursorSlice sl = cur.top();
3910         Cursor & bvcur = cur.bv().cursor();
3911
3912         FuncCode const act = cmd.action();
3913         
3914         switch (act) {
3915
3916         case LFUN_MOUSE_PRESS: {
3917                 //lyxerr << "# InsetTabular::MousePress\n" << cur.bv().cursor() << endl;
3918                 // select row
3919                 if (cmd.x() < xo(cur.bv()) + ADD_TO_TABULAR_WIDTH
3920                         || cmd.x() > xo(cur.bv()) + tabular.width()) {
3921                         row_type r = rowFromY(cur, cmd.y());
3922                         cur.idx() = tabular.getFirstCellInRow(r);
3923                         cur.pos() = 0;
3924                         cur.resetAnchor();
3925                         cur.idx() = tabular.getLastCellInRow(r);
3926                         cur.pos() = cur.lastpos();
3927                         cur.setSelection(true);
3928                         bvcur = cur; 
3929                         rowselect_ = true;
3930                         break;
3931                 }
3932                 // select column
3933                 int const y0 = yo(cur.bv()) - tabular.rowAscent(0) + offset_valign_;
3934                 if (cmd.y() < y0 + ADD_TO_TABULAR_WIDTH 
3935                         || cmd.y() > y0 + tabular.height()) {
3936                         col_type c = columnFromX(cur, cmd.x());
3937                         cur.idx() = tabular.cellIndex(0, c);
3938                         cur.pos() = 0;
3939                         cur.resetAnchor();
3940                         cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
3941                         cur.pos() = cur.lastpos();
3942                         cur.setSelection(true);
3943                         bvcur = cur; 
3944                         colselect_ = true;
3945                         break;
3946                 }
3947                 // do not reset cursor/selection if we have selected
3948                 // some cells (bug 2715).
3949                 if (cmd.button() == mouse_button::button3
3950                     && &bvcur.selBegin().inset() == this 
3951                     && bvcur.selIsMultiCell()) 
3952                         ;
3953                 else
3954                         // Let InsetTableCell do it
3955                         cell(cur.idx())->dispatch(cur, cmd);
3956                 break;
3957         }
3958         case LFUN_MOUSE_MOTION:
3959                 //lyxerr << "# InsetTabular::MouseMotion\n" << bvcur << endl;
3960                 if (cmd.button() == mouse_button::button1) {
3961                         // only accept motions to places not deeper nested than the real anchor
3962                         if (!bvcur.realAnchor().hasPart(cur)) {
3963                                 cur.undispatched();
3964                                 break;
3965                         }
3966                         // select (additional) row
3967                         if (rowselect_) {
3968                                 row_type r = rowFromY(cur, cmd.y());
3969                                 cur.idx() = tabular.getLastCellInRow(r);
3970                                 // we need to reset the cursor's pit and pos now, as the old ones
3971                                 // may no longer be valid.
3972                                 cur.pit() = 0;
3973                                 cur.pos() = 0;
3974                                 bvcur.setCursor(cur);
3975                                 bvcur.setSelection(true);
3976                                 break;
3977                         }
3978                         // select (additional) column
3979                         if (colselect_) {
3980                                 col_type c = columnFromX(cur, cmd.x());
3981                                 cur.idx() = tabular.cellIndex(tabular.nrows() - 1, c);
3982                                 // we need to reset the cursor's pit and pos now, as the old ones
3983                                 // may no longer be valid.
3984                                 cur.pit() = 0;
3985                                 cur.pos() = 0;
3986                                 bvcur.setCursor(cur);
3987                                 bvcur.setSelection(true);
3988                                 break;
3989                         }
3990                         // only update if selection changes
3991                         if (bvcur.idx() == cur.idx() &&
3992                                 !(bvcur.realAnchor().idx() == cur.idx() && bvcur.pos() != cur.pos()))
3993                                 cur.noScreenUpdate();
3994                         setCursorFromCoordinates(cur, cmd.x(), cmd.y());
3995                         bvcur.setCursor(cur);
3996                         bvcur.setSelection(true);
3997                         // if this is a multicell selection, we just set the cursor to
3998                         // the beginning of the cell's text.
3999                         if (bvcur.selIsMultiCell()) {
4000                                 bvcur.pit() = bvcur.lastpit();
4001                                 bvcur.pos() = bvcur.lastpos();
4002                         }
4003                 }
4004                 break;
4005
4006         case LFUN_MOUSE_RELEASE:
4007                 rowselect_ = false;
4008                 colselect_ = false;
4009                 break;
4010
4011         case LFUN_CELL_BACKWARD:
4012                 movePrevCell(cur);
4013                 cur.setSelection(false);
4014                 break;
4015
4016         case LFUN_CELL_FORWARD:
4017                 moveNextCell(cur);
4018                 cur.setSelection(false);
4019                 break;
4020
4021         case LFUN_CHAR_FORWARD_SELECT:
4022         case LFUN_CHAR_FORWARD:
4023         case LFUN_CHAR_BACKWARD_SELECT:
4024         case LFUN_CHAR_BACKWARD:
4025         case LFUN_CHAR_RIGHT_SELECT:
4026         case LFUN_CHAR_RIGHT:
4027         case LFUN_CHAR_LEFT_SELECT:
4028         case LFUN_CHAR_LEFT: 
4029         case LFUN_WORD_FORWARD:
4030         case LFUN_WORD_FORWARD_SELECT:
4031         case LFUN_WORD_BACKWARD:
4032         case LFUN_WORD_BACKWARD_SELECT:
4033         case LFUN_WORD_RIGHT:
4034         case LFUN_WORD_RIGHT_SELECT:
4035         case LFUN_WORD_LEFT:
4036         case LFUN_WORD_LEFT_SELECT: {
4037                 // determine whether we move to next or previous cell, where to enter 
4038                 // the new cell from, and which command to "finish" (i.e., exit the
4039                 // inset) with:
4040                 bool next_cell;
4041                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE;
4042                 FuncCode finish_lfun;
4043
4044                 if (act == LFUN_CHAR_FORWARD 
4045                                 || act == LFUN_CHAR_FORWARD_SELECT
4046                                 || act == LFUN_WORD_FORWARD
4047                                 || act == LFUN_WORD_FORWARD_SELECT) {
4048                         next_cell = true;
4049                         finish_lfun = LFUN_FINISHED_FORWARD;
4050                 }
4051                 else if (act == LFUN_CHAR_BACKWARD
4052                                 || act == LFUN_CHAR_BACKWARD_SELECT
4053                                 || act == LFUN_WORD_BACKWARD
4054                                 || act == LFUN_WORD_BACKWARD_SELECT) {
4055                         next_cell = false;
4056                         finish_lfun = LFUN_FINISHED_BACKWARD;
4057                 }
4058                 // LEFT or RIGHT commands --- the interpretation will depend on the 
4059                 // table's direction.
4060                 else {
4061                         bool const right = act == LFUN_CHAR_RIGHT
4062                                 || act == LFUN_CHAR_RIGHT_SELECT
4063                                 || act == LFUN_WORD_RIGHT
4064                                 || act == LFUN_WORD_RIGHT_SELECT;
4065                         next_cell = isRightToLeft(cur) != right;
4066                         
4067                         if (lyxrc.visual_cursor)
4068                                 entry_from = right ? ENTRY_DIRECTION_LEFT:ENTRY_DIRECTION_RIGHT;
4069
4070                         finish_lfun = right ? LFUN_FINISHED_RIGHT : LFUN_FINISHED_LEFT;
4071                 }
4072
4073                 bool const select =     act == LFUN_CHAR_FORWARD_SELECT 
4074                     || act == LFUN_CHAR_BACKWARD_SELECT
4075                     || act == LFUN_CHAR_RIGHT_SELECT
4076                     || act == LFUN_CHAR_LEFT_SELECT
4077                         || act == LFUN_WORD_FORWARD_SELECT
4078                         || act == LFUN_WORD_RIGHT_SELECT
4079                         || act == LFUN_WORD_BACKWARD_SELECT
4080                         || act == LFUN_WORD_LEFT_SELECT;
4081
4082                 // If we have a multicell selection or we're 
4083                 // not doing some LFUN_*_SELECT thing anyway...
4084                 if (!cur.selIsMultiCell() || !select) {
4085                         col_type const c = tabular.cellColumn(cur.idx());
4086                         row_type const r = tabular.cellRow(cur.idx());
4087                         // Are we trying to select the whole cell and is the whole cell 
4088                         // not yet selected?
4089                         bool const select_whole = select && !isCellSelected(cur, r, c) &&
4090                                 ((next_cell && cur.pit() == cur.lastpit() 
4091                                 && cur.pos() == cur.lastpos())
4092                                 || (!next_cell && cur.pit() == 0 && cur.pos() == 0));
4093
4094                         bool const empty_cell = cur.lastpos() == 0 && cur.lastpit() == 0;
4095
4096                         // ...try to dispatch to the cell's inset.
4097                         cell(cur.idx())->dispatch(cur, cmd);
4098
4099                         // When we already have a selection we want to select the whole cell
4100                         // before going to the next cell.
4101                         if (select_whole && !empty_cell){
4102                                 getText(cur.idx())->selectAll(cur);
4103                                 cur.dispatched();
4104                                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4105                                 break;
4106                         }
4107
4108                         // FIXME: When we support the selection of an empty cell, remove 
4109                         // the !empty_cell from this condition. For now we jump to the next
4110                         // cell if the current cell is empty.
4111                         if (cur.result().dispatched() && !empty_cell)
4112                                 break;
4113                 }
4114
4115                 // move to next/prev cell, as appropriate
4116                 // note that we will always do this if we're selecting and we have
4117                 // a multicell selection
4118                 LYXERR(Debug::RTL, "entering " << (next_cell ? "next" : "previous")
4119                         << " cell from: " << int(entry_from));
4120                 if (next_cell)
4121                         moveNextCell(cur, entry_from);
4122                 else
4123                         movePrevCell(cur, entry_from);
4124                 // if we're exiting the table, call the appropriate FINISHED lfun
4125                 if (sl == cur.top())
4126                         cmd = FuncRequest(finish_lfun);
4127                 else
4128                         cur.dispatched();
4129
4130                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4131                 break;
4132
4133         }
4134
4135         case LFUN_DOWN_SELECT:
4136         case LFUN_DOWN:
4137                 if (!(cur.selection() && cur.selIsMultiCell()))
4138                         cell(cur.idx())->dispatch(cur, cmd);
4139                 
4140                 cur.dispatched(); // override the cell's decision
4141                 if (sl == cur.top()) {
4142                         // if our Text didn't do anything to the cursor
4143                         // then we try to put the cursor into the cell below
4144                         // setting also the right targetX.
4145                         cur.selHandle(act == LFUN_DOWN_SELECT);
4146                         if (tabular.cellRow(cur.idx()) != tabular.nrows() - 1) {
4147                                 int const xtarget = cur.targetX();
4148                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4149                                 // an inconsistent state until pos() has been set. Be careful
4150                                 // what you do with it!
4151                                 cur.idx() = tabular.cellBelow(cur.idx());
4152                                 cur.pit() = 0;
4153                                 TextMetrics const & tm =
4154                                         cur.bv().textMetrics(cell(cur.idx())->getText(0));
4155                                 cur.pos() = tm.x2pos(cur.pit(), 0, xtarget);
4156                                 cur.setCurrentFont();
4157                         }
4158                 }
4159                 if (sl == cur.top()) {
4160                         // we trick it to go to forward after leaving the
4161                         // tabular.
4162                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
4163                         cur.undispatched();
4164                 }
4165                 if (cur.selIsMultiCell()) {
4166                         cur.pit() = cur.lastpit();
4167                         cur.pos() = cur.lastpos();
4168                         cur.setCurrentFont();
4169                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4170                         return;
4171                 }
4172                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4173                 break;
4174
4175         case LFUN_UP_SELECT:
4176         case LFUN_UP:
4177                 if (!(cur.selection() && cur.selIsMultiCell()))
4178                         cell(cur.idx())->dispatch(cur, cmd);
4179                 cur.dispatched(); // override the cell's decision
4180                 if (sl == cur.top()) {
4181                         // if our Text didn't do anything to the cursor
4182                         // then we try to put the cursor into the cell above
4183                         // setting also the right targetX.
4184                         cur.selHandle(act == LFUN_UP_SELECT);
4185                         if (tabular.cellRow(cur.idx()) != 0) {
4186                                 int const xtarget = cur.targetX();
4187                                 // WARNING: Once cur.idx() has been reset, the cursor is in
4188                                 // an inconsistent state until pos() has been set. Be careful
4189                                 // what you do with it!
4190                                 cur.idx() = tabular.cellAbove(cur.idx());
4191                                 cur.pit() = cur.lastpit();
4192                                 Text const * text = cell(cur.idx())->getText(0);
4193                                 TextMetrics const & tm = cur.bv().textMetrics(text);
4194                                 ParagraphMetrics const & pm =
4195                                         tm.parMetrics(cur.lastpit());
4196                                 cur.pos() = tm.x2pos(cur.pit(), pm.rows().size()-1, xtarget);
4197                                 cur.setCurrentFont();
4198                         }
4199                 }
4200                 if (sl == cur.top()) {
4201                         cmd = FuncRequest(LFUN_UP);
4202                         cur.undispatched();
4203                 }
4204                 if (cur.selIsMultiCell()) {
4205                         cur.pit() = 0;
4206                         cur.pos() = cur.lastpos();
4207                         cur.setCurrentFont();
4208                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4209                         return;
4210                 }
4211                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4212                 break;
4213
4214 //      case LFUN_SCREEN_DOWN: {
4215 //              //if (hasSelection())
4216 //              //      cur.selection() = false;
4217 //              col_type const col = tabular.cellColumn(cur.idx());
4218 //              int const t =   cur.bv().top_y() + cur.bv().height();
4219 //              if (t < yo() + tabular.getHeightOfTabular()) {
4220 //                      cur.bv().scrollDocView(t, true);
4221 //                      cur.idx() = tabular.cellBelow(first_visible_cell) + col;
4222 //              } else {
4223 //                      cur.idx() = tabular.getFirstCellInRow(tabular.rows() - 1) + col;
4224 //              }
4225 //              cur.par() = 0;
4226 //              cur.pos() = 0;
4227 //              break;
4228 //      }
4229 //
4230 //      case LFUN_SCREEN_UP: {
4231 //              //if (hasSelection())
4232 //              //      cur.selection() = false;
4233 //              col_type const col = tabular.cellColumn(cur.idx());
4234 //              int const t =   cur.bv().top_y() + cur.bv().height();
4235 //              if (yo() < 0) {
4236 //                      cur.bv().scrollDocView(t, true);
4237 //                      if (yo() > 0)
4238 //                              cur.idx() = col;
4239 //                      else
4240 //                              cur.idx() = tabular.cellBelow(first_visible_cell) + col;
4241 //              } else {
4242 //                      cur.idx() = col;
4243 //              }
4244 //              cur.par() = cur.lastpar();
4245 //              cur.pos() = cur.lastpos();
4246 //              break;
4247 //      }
4248
4249         case LFUN_LAYOUT_TABULAR:
4250                 cur.bv().showDialog("tabular");
4251                 break;
4252
4253         case LFUN_INSET_MODIFY: {
4254                 string arg;
4255                 if (cmd.getArg(1) == "from-dialog")
4256                         arg = cmd.getArg(0) + to_utf8(cmd.argument().substr(19));
4257                 else
4258                         arg = to_utf8(cmd.argument());
4259                 if (!tabularFeatures(cur, arg))
4260                         cur.undispatched();
4261                 break;
4262         }
4263
4264         // insert file functions
4265         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
4266         case LFUN_FILE_INSERT_PLAINTEXT:
4267                 // FIXME UNICODE
4268                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
4269                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
4270                                 FileName(to_utf8(cmd.argument())));
4271                         if (tmpstr.empty())
4272                                 break;
4273                         cur.recordUndoInset(INSERT_UNDO);
4274                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
4275                                 // content has been replaced,
4276                                 // so cursor might be invalid
4277                                 cur.pos() = cur.lastpos();
4278                                 cur.pit() = cur.lastpit();
4279                                 bvcur.setCursor(cur);
4280                         } else
4281                                 cur.undispatched();
4282                 }
4283                 break;
4284
4285         case LFUN_CUT:
4286                 if (cur.selIsMultiCell()) {
4287                         if (copySelection(cur)) {
4288                                 cur.recordUndoInset(DELETE_UNDO);
4289                                 cutSelection(cur);
4290                         }
4291                 } else
4292                         cell(cur.idx())->dispatch(cur, cmd);
4293                 break;
4294
4295         case LFUN_SELF_INSERT:
4296                 if (cur.selIsMultiCell()) {
4297                         cur.recordUndoInset(DELETE_UNDO);
4298                         cutSelection(cur);
4299                 }
4300                 cell(cur.idx())->dispatch(cur, cmd);
4301                 break;
4302
4303         case LFUN_CHAR_DELETE_BACKWARD:
4304         case LFUN_CHAR_DELETE_FORWARD:
4305                 if (cur.selIsMultiCell()) {
4306                         cur.recordUndoInset(DELETE_UNDO);
4307                         cutSelection(cur);
4308                 } else
4309                         cell(cur.idx())->dispatch(cur, cmd);
4310                 break;
4311
4312         case LFUN_COPY:
4313                 if (!cur.selection())
4314                         break;
4315                 if (cur.selIsMultiCell()) {
4316                         cur.finishUndo();
4317                         copySelection(cur);
4318                 } else
4319                         cell(cur.idx())->dispatch(cur, cmd);
4320                 break;
4321
4322         case LFUN_CLIPBOARD_PASTE:
4323         case LFUN_PRIMARY_SELECTION_PASTE: {
4324                 docstring const clip = (act == LFUN_CLIPBOARD_PASTE) ?
4325                         theClipboard().getAsText() :
4326                         theSelection().get();
4327                 if (clip.empty())
4328                         break;
4329                 // pass to InsertPlaintextString, but
4330                 // only if we have multi-cell content
4331                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
4332                         cur.recordUndoInset(INSERT_UNDO);
4333                         if (insertPlaintextString(cur.bv(), clip, false)) {
4334                                 // content has been replaced,
4335                                 // so cursor might be invalid
4336                                 cur.pos() = cur.lastpos();
4337                                 cur.pit() = cur.lastpit();
4338                                 bvcur.setCursor(cur);
4339                                 break;
4340                         }
4341                 }
4342                 // Let the cell handle normal text
4343                 cell(cur.idx())->dispatch(cur, cmd);
4344                 break;
4345         }
4346
4347         case LFUN_PASTE:
4348                 if (!tabularStackDirty()) {
4349                         if (!cur.selIsMultiCell())
4350                                 cell(cur.idx())->dispatch(cur, cmd);
4351                         break;
4352                 }
4353                 if (theClipboard().isInternal()) {
4354                         cur.recordUndoInset(INSERT_UNDO);
4355                         pasteClipboard(cur);
4356                 }
4357                 break;
4358
4359         case LFUN_FONT_EMPH:
4360         case LFUN_FONT_BOLD:
4361         case LFUN_FONT_BOLDSYMBOL:
4362         case LFUN_FONT_ROMAN:
4363         case LFUN_FONT_NOUN:
4364         case LFUN_FONT_ITAL:
4365         case LFUN_FONT_FRAK:
4366         case LFUN_FONT_TYPEWRITER:
4367         case LFUN_FONT_SANS:
4368         case LFUN_TEXTSTYLE_APPLY:
4369         case LFUN_TEXTSTYLE_UPDATE:
4370         case LFUN_FONT_SIZE:
4371         case LFUN_FONT_UNDERLINE:
4372         case LFUN_FONT_STRIKEOUT:
4373         case LFUN_FONT_UULINE:
4374         case LFUN_FONT_UWAVE:
4375         case LFUN_LANGUAGE:
4376         case LFUN_WORD_CAPITALIZE:
4377         case LFUN_WORD_UPCASE:
4378         case LFUN_WORD_LOWCASE:
4379         case LFUN_CHARS_TRANSPOSE:
4380                 if (cur.selIsMultiCell()) {
4381                         row_type rs, re;
4382                         col_type cs, ce;
4383                         getSelection(cur, rs, re, cs, ce);
4384                         Cursor tmpcur = cur;
4385                         for (row_type r = rs; r <= re; ++r) {
4386                                 for (col_type c = cs; c <= ce; ++c) {
4387                                         // cursor follows cell:
4388                                         tmpcur.idx() = tabular.cellIndex(r, c);
4389                                         // select this cell only:
4390                                         tmpcur.pit() = 0;
4391                                         tmpcur.pos() = 0;
4392                                         tmpcur.resetAnchor();
4393                                         tmpcur.pit() = tmpcur.lastpit();
4394                                         tmpcur.pos() = tmpcur.top().lastpos();
4395                                         tmpcur.setCursor(tmpcur);
4396                                         tmpcur.setSelection();
4397                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
4398                                 }
4399                         }
4400                         break;
4401                 } else {
4402                         cell(cur.idx())->dispatch(cur, cmd);
4403                         break;
4404                 }
4405
4406         case LFUN_INSET_SETTINGS:
4407                 // relay this lfun to Inset, not to the cell.
4408                 Inset::doDispatch(cur, cmd);
4409                 break;
4410
4411         default:
4412                 // we try to handle this event in the insets dispatch function.
4413                 cell(cur.idx())->dispatch(cur, cmd);
4414                 break;
4415         }
4416 }
4417
4418
4419 // function sets an object as defined in func_status.h:
4420 // states OK, Unknown, Disabled, On, Off.
4421 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
4422         FuncStatus & status) const
4423 {
4424         switch (cmd.action()) {
4425         case LFUN_INSET_MODIFY: {
4426                 if (&cur.inset() != this || cmd.getArg(0) != "tabular") 
4427                         break;
4428
4429                 // FIXME: We only check for the very first argument...
4430                 string const s = cmd.getArg(1);
4431                 // We always enable the lfun if it is coming from the dialog
4432                 // because the dialog makes sure all the settings are valid,
4433                 // even though the first argument might not be valid now.
4434                 if (s == "from-dialog") {
4435                         status.setEnabled(true);
4436                         return true;
4437                 }
4438
4439                 int action = Tabular::LAST_ACTION;
4440                 int i = 0;
4441                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4442                         if (tabularFeature[i].feature == s) {
4443                                 action = tabularFeature[i].action;
4444                                 break;
4445                         }
4446                 }
4447                 if (action == Tabular::LAST_ACTION) {
4448                         status.clear();
4449                         status.setUnknown(true);
4450                         return true;
4451                 }
4452
4453                 string const argument = cmd.getLongArg(2);
4454
4455                 row_type sel_row_start = 0;
4456                 row_type sel_row_end = 0;
4457                 col_type sel_col_start = 0;
4458                 col_type sel_col_end = 0;
4459                 Tabular::ltType dummyltt;
4460                 bool flag = true;
4461
4462                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4463
4464                 switch (action) {
4465                 case Tabular::SET_PWIDTH:
4466                 case Tabular::SET_MPWIDTH:
4467                 case Tabular::SET_SPECIAL_COLUMN:
4468                 case Tabular::SET_SPECIAL_MULTICOLUMN:
4469                 case Tabular::APPEND_ROW:
4470                 case Tabular::APPEND_COLUMN:
4471                 case Tabular::DELETE_ROW:
4472                 case Tabular::DELETE_COLUMN:
4473                 case Tabular::COPY_ROW:
4474                 case Tabular::COPY_COLUMN:
4475                 case Tabular::SET_TOP_SPACE:
4476                 case Tabular::SET_BOTTOM_SPACE:
4477                 case Tabular::SET_INTERLINE_SPACE:
4478                         status.clear();
4479                         return true;
4480
4481                 case Tabular::SET_TABULAR_WIDTH:
4482                         status.setEnabled(!tabular.rotate &&  !tabular.is_long_tabular
4483                                 && tabular.tabular_valignment == Tabular::LYX_VALIGN_MIDDLE);
4484                         break;
4485
4486                 case Tabular::MOVE_COLUMN_RIGHT:
4487                 case Tabular::MOVE_COLUMN_LEFT:
4488                 case Tabular::MOVE_ROW_DOWN:
4489                 case Tabular::MOVE_ROW_UP: {
4490                         if (cur.selection()) {
4491                                 status.message(_("Selections not supported."));
4492                                 status.setEnabled(false);
4493                                 break;
4494                         }
4495
4496                         if ((action == Tabular::MOVE_COLUMN_RIGHT &&
4497                                 tabular.ncols() == tabular.cellColumn(cur.idx()) + 1) ||
4498                             (action == Tabular::MOVE_COLUMN_LEFT &&
4499                                 tabular.cellColumn(cur.idx()) == 0) ||
4500                             (action == Tabular::MOVE_ROW_DOWN &&
4501                                 tabular.nrows() == tabular.cellRow(cur.idx()) + 1) ||
4502                             (action == Tabular::MOVE_ROW_UP &&
4503                                 tabular.cellRow(cur.idx()) == 0)) {
4504                                         status.setEnabled(false);
4505                                         break;
4506                         }
4507
4508                         if (action == Tabular::MOVE_COLUMN_RIGHT ||
4509                             action == Tabular::MOVE_COLUMN_LEFT) {
4510                                 if (tabular.hasMultiColumn(tabular.cellColumn(cur.idx())) ||
4511                                     tabular.hasMultiColumn(tabular.cellColumn(cur.idx()) +
4512                                         (action == Tabular::MOVE_COLUMN_RIGHT ? 1 : -1))) {
4513                                         status.message(_("Multi-column in current or"
4514                                                          " destination column."));
4515                                         status.setEnabled(false);
4516                                         break;
4517                                 }
4518                         }
4519
4520                         if (action == Tabular::MOVE_ROW_DOWN ||
4521                             action == Tabular::MOVE_ROW_UP) {
4522                                 if (tabular.hasMultiRow(tabular.cellRow(cur.idx())) ||
4523                                     tabular.hasMultiRow(tabular.cellRow(cur.idx()) +
4524                                         (action == Tabular::MOVE_ROW_DOWN ? 1 : -1))) {
4525                                         status.message(_("Multi-row in current or"
4526                                                          " destination row."));
4527                                         status.setEnabled(false);
4528                                         break;
4529                                 }
4530                         }
4531
4532                         status.setEnabled(true);
4533                         break;
4534                 }
4535
4536                 case Tabular::SET_DECIMAL_POINT:
4537                         status.setEnabled(
4538                                 tabular.getAlignment(cur.idx()) == LYX_ALIGN_DECIMAL);
4539                         break;
4540
4541                 case Tabular::SET_MULTICOLUMN:
4542                 case Tabular::UNSET_MULTICOLUMN:
4543                 case Tabular::MULTICOLUMN:
4544                         // If a row is set as longtable caption, it must not be allowed
4545                         // to unset that this row is a multicolumn.
4546                         status.setEnabled(sel_row_start == sel_row_end
4547                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4548                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
4549                         break;
4550
4551                 case Tabular::SET_MULTIROW:
4552                 case Tabular::UNSET_MULTIROW:
4553                 case Tabular::MULTIROW:
4554                         // If a row is set as longtable caption, it must not be allowed
4555                         // to unset that this row is a multirow.
4556                         status.setEnabled(sel_col_start == sel_col_end
4557                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4558                         status.setOnOff(tabular.isMultiRow(cur.idx()));
4559                         break;
4560
4561                 case Tabular::SET_ALL_LINES:
4562                 case Tabular::UNSET_ALL_LINES:
4563                 case Tabular::SET_BORDER_LINES:
4564                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4565                         break;
4566
4567                 case Tabular::SET_LINE_TOP:
4568                 case Tabular::SET_LINE_BOTTOM:
4569                 case Tabular::SET_LINE_LEFT:
4570                 case Tabular::SET_LINE_RIGHT:
4571                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4572                         break;
4573
4574                 case Tabular::TOGGLE_LINE_TOP:
4575                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4576                         status.setOnOff(tabular.topLine(cur.idx()));
4577                         break;
4578
4579                 case Tabular::TOGGLE_LINE_BOTTOM:
4580                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4581                         status.setOnOff(tabular.bottomLine(cur.idx()));
4582                         break;
4583
4584                 case Tabular::TOGGLE_LINE_LEFT:
4585                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4586                         status.setOnOff(tabular.leftLine(cur.idx()));
4587                         break;
4588
4589                 case Tabular::TOGGLE_LINE_RIGHT:
4590                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4591                         status.setOnOff(tabular.rightLine(cur.idx()));
4592                         break;
4593
4594                 // multirow cells only inherit the alignment of the column if the column has
4595                 // no width, otherwise they are left-aligned
4596                 // therefore allow always left but right and center only if there is no width
4597                 case Tabular::M_ALIGN_LEFT:
4598                         flag = false;
4599                 case Tabular::ALIGN_LEFT:
4600                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
4601                         break;
4602
4603                 case Tabular::M_ALIGN_RIGHT:
4604                         flag = false;
4605                 case Tabular::ALIGN_RIGHT:
4606                         status.setEnabled(!(tabular.isMultiRow(cur.idx()) 
4607                                 && !tabular.getPWidth(cur.idx()).zero()));
4608                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
4609                         break;
4610
4611                 case Tabular::M_ALIGN_CENTER:
4612                         flag = false;
4613                 case Tabular::ALIGN_CENTER:
4614                         status.setEnabled(!(tabular.isMultiRow(cur.idx()) 
4615                                 && !tabular.getPWidth(cur.idx()).zero()));
4616                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
4617                         break;
4618
4619                 case Tabular::ALIGN_BLOCK:
4620                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4621                                 && !tabular.isMultiRow(cur.idx()));
4622                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
4623                         break;
4624
4625                 case Tabular::ALIGN_DECIMAL:
4626                         status.setEnabled(!tabular.isMultiRow(cur.idx()) 
4627                                 && !tabular.isMultiColumn(cur.idx()));
4628                         status.setOnOff(tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_DECIMAL);
4629                         break;
4630
4631                 case Tabular::M_VALIGN_TOP:
4632                         flag = false;
4633                 case Tabular::VALIGN_TOP:
4634                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4635                                 && !tabular.isMultiRow(cur.idx()));
4636                         status.setOnOff(
4637                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
4638                         break;
4639
4640                 case Tabular::M_VALIGN_BOTTOM:
4641                         flag = false;
4642                 case Tabular::VALIGN_BOTTOM:
4643                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4644                                 && !tabular.isMultiRow(cur.idx()));
4645                         status.setOnOff(
4646                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
4647                         break;
4648
4649                 case Tabular::M_VALIGN_MIDDLE:
4650                         flag = false;
4651                 case Tabular::VALIGN_MIDDLE:
4652                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4653                                 && !tabular.isMultiRow(cur.idx()));
4654                         status.setOnOff(
4655                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
4656                         break;
4657
4658                 case Tabular::SET_LONGTABULAR:
4659                         // setting as longtable is not allowed when table is inside a float
4660                         if (cur.innerInsetOfType(FLOAT_CODE) != 0
4661                                 || cur.innerInsetOfType(WRAP_CODE) != 0)
4662                                 status.setEnabled(false);
4663                         else
4664                                 status.setEnabled(true);
4665                         status.setOnOff(tabular.is_long_tabular);
4666                         break;
4667
4668                 case Tabular::UNSET_LONGTABULAR:
4669                         status.setOnOff(!tabular.is_long_tabular);
4670                         break;
4671
4672                 case Tabular::TOGGLE_ROTATE_TABULAR:
4673                 case Tabular::SET_ROTATE_TABULAR:
4674                         status.setOnOff(tabular.rotate != 0);
4675                         break;
4676
4677                 case Tabular::TABULAR_VALIGN_TOP:
4678                         status.setEnabled(tabular.tabular_width.zero());
4679                         status.setOnOff(tabular.tabular_valignment 
4680                                 == Tabular::LYX_VALIGN_TOP);
4681                         break;
4682                 case Tabular::TABULAR_VALIGN_MIDDLE:
4683                         status.setEnabled(tabular.tabular_width.zero());
4684                         status.setOnOff(tabular.tabular_valignment 
4685                                 == Tabular::LYX_VALIGN_MIDDLE);
4686                         break;
4687                 case Tabular::TABULAR_VALIGN_BOTTOM:
4688                         status.setEnabled(tabular.tabular_width.zero());
4689                         status.setOnOff(tabular.tabular_valignment 
4690                                 == Tabular::LYX_VALIGN_BOTTOM);
4691                         break;
4692
4693                 case Tabular::LONGTABULAR_ALIGN_LEFT:
4694                         status.setOnOff(tabular.longtabular_alignment 
4695                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
4696                         break;
4697                 case Tabular::LONGTABULAR_ALIGN_CENTER:
4698                         status.setOnOff(tabular.longtabular_alignment 
4699                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
4700                         break;
4701                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
4702                         status.setOnOff(tabular.longtabular_alignment 
4703                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
4704                         break;
4705
4706                 case Tabular::UNSET_ROTATE_TABULAR:
4707                         status.setOnOff(tabular.rotate == 0);
4708                         break;
4709
4710                 case Tabular::TOGGLE_ROTATE_CELL:
4711                 case Tabular::SET_ROTATE_CELL:
4712                         status.setOnOff(!oneCellHasRotationState(false,
4713                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4714                         break;
4715
4716                 case Tabular::UNSET_ROTATE_CELL:
4717                         status.setOnOff(!oneCellHasRotationState(true,
4718                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4719                         break;
4720
4721                 case Tabular::SET_USEBOX:
4722                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4723                         break;
4724
4725                 // every row can only be one thing:
4726                 // either a footer or header
4727                 case Tabular::SET_LTFIRSTHEAD:
4728                         status.setEnabled(sel_row_start == sel_row_end);
4729                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4730                         break;
4731
4732                 case Tabular::UNSET_LTFIRSTHEAD:
4733                         status.setEnabled(sel_row_start == sel_row_end && !tabular.ltCaption(sel_row_start));
4734                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4735                         break;
4736
4737                 case Tabular::SET_LTHEAD:
4738                         status.setEnabled(sel_row_start == sel_row_end);
4739                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4740                         break;
4741
4742                 case Tabular::UNSET_LTHEAD:
4743                         status.setEnabled(sel_row_start == sel_row_end && !tabular.ltCaption(sel_row_start));
4744                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4745                         break;
4746
4747                 case Tabular::SET_LTFOOT:
4748                         status.setEnabled(sel_row_start == sel_row_end);
4749                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4750                         break;
4751
4752                 case Tabular::UNSET_LTFOOT:
4753                         status.setEnabled(sel_row_start == sel_row_end && !tabular.ltCaption(sel_row_start));
4754                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4755                         break;
4756
4757                 case Tabular::SET_LTLASTFOOT:
4758                         status.setEnabled(sel_row_start == sel_row_end);
4759                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4760                         break;
4761
4762                 case Tabular::UNSET_LTLASTFOOT:
4763                         status.setEnabled(sel_row_start == sel_row_end && !tabular.ltCaption(sel_row_start));
4764                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4765                         break;
4766
4767                 case Tabular::SET_LTNEWPAGE:
4768                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4769                         break;
4770                 case Tabular::UNSET_LTNEWPAGE:
4771                         status.setOnOff(!tabular.getLTNewPage(sel_row_start));
4772                         break;
4773
4774                 // only one row in head/firsthead/foot/lasthead can be the caption
4775                 // and a multirow cannot be set as caption
4776                 case Tabular::SET_LTCAPTION:
4777                         status.setEnabled(sel_row_start == sel_row_end
4778                                 && (!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4779                                  || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
4780                                 && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
4781                                  || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
4782                                 && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4783                                  || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
4784                                 && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4785                                  || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT))
4786                                 && !tabular.isMultiRow(sel_row_start));
4787                         status.setOnOff(tabular.ltCaption(sel_row_start));
4788                         break;
4789
4790                 case Tabular::UNSET_LTCAPTION:
4791                         status.setEnabled(sel_row_start == sel_row_end && tabular.ltCaption(sel_row_start));
4792                         break;
4793
4794                 case Tabular::TOGGLE_LTCAPTION:
4795                         status.setEnabled(sel_row_start == sel_row_end && (tabular.ltCaption(sel_row_start)
4796                                 || ((!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4797                                   || !tabular.haveLTCaption(Tabular::CAPTION_FIRSTHEAD))
4798                                  && (!tabular.getRowOfLTHead(sel_row_start, dummyltt)
4799                                   || !tabular.haveLTCaption(Tabular::CAPTION_HEAD))
4800                                  && (!tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4801                                   || !tabular.haveLTCaption(Tabular::CAPTION_FOOT))
4802                                  && (!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4803                                   || !tabular.haveLTCaption(Tabular::CAPTION_LASTFOOT)))));
4804                         status.setOnOff(tabular.ltCaption(sel_row_start));
4805                         break;
4806
4807                 case Tabular::SET_BOOKTABS:
4808                         status.setOnOff(tabular.use_booktabs);
4809                         break;
4810
4811                 case Tabular::UNSET_BOOKTABS:
4812                         status.setOnOff(!tabular.use_booktabs);
4813                         break;
4814
4815                 default:
4816                         status.clear();
4817                         status.setEnabled(false);
4818                         break;
4819                 }
4820                 return true;
4821         }
4822
4823         case LFUN_CAPTION_INSERT: {
4824                 // caption is only allowed in caption cell of longtable
4825                 if (!tabular.ltCaption(tabular.cellRow(cur.idx()))) {
4826                         status.setEnabled(false);
4827                         return true;
4828                 }
4829                 // only standard caption is allowed
4830                 string arg = cmd.getArg(0);
4831                 if (!arg.empty() && arg != "Standard") {
4832                         status.setEnabled(false);
4833                         return true;
4834                 }
4835                 // check if there is already a caption
4836                 bool have_caption = false;
4837                 InsetTableCell itc = InsetTableCell(*tabular.cellInset(cur.idx()).get());
4838                 ParagraphList::const_iterator pit = itc.paragraphs().begin();
4839                 ParagraphList::const_iterator pend = itc.paragraphs().end();
4840                 for (; pit != pend; ++pit) {
4841                         InsetList::const_iterator it  = pit->insetList().begin();
4842                         InsetList::const_iterator end = pit->insetList().end();
4843                         for (; it != end; ++it) {
4844                                 if (it->inset->lyxCode() == CAPTION_CODE) {
4845                                         have_caption = true;
4846                                         break;
4847                                 }
4848                         }
4849                 }
4850                 status.setEnabled(!have_caption);
4851                 return true;
4852         }
4853
4854         // These are only enabled inside tabular
4855         case LFUN_CELL_BACKWARD:
4856         case LFUN_CELL_FORWARD:
4857                 status.setEnabled(true);
4858                 return true;
4859
4860         // disable these with multiple cells selected
4861         case LFUN_INSET_INSERT:
4862         case LFUN_TABULAR_INSERT:
4863         case LFUN_FLEX_INSERT:
4864         case LFUN_FLOAT_INSERT:
4865         case LFUN_FLOAT_WIDE_INSERT:
4866         case LFUN_FOOTNOTE_INSERT:
4867         case LFUN_MARGINALNOTE_INSERT:
4868         case LFUN_MATH_INSERT:
4869         case LFUN_MATH_MODE:
4870         case LFUN_MATH_MUTATE:
4871         case LFUN_MATH_DISPLAY:
4872         case LFUN_NOTE_INSERT:
4873         case LFUN_ARGUMENT_INSERT:
4874         case LFUN_BOX_INSERT:
4875         case LFUN_BRANCH_INSERT:
4876         case LFUN_PHANTOM_INSERT:
4877         case LFUN_WRAP_INSERT:
4878         case LFUN_PREVIEW_INSERT:
4879         case LFUN_ERT_INSERT: {
4880                 if (cur.selIsMultiCell()) {
4881                         status.setEnabled(false);
4882                         return true;
4883                 } else
4884                         return cell(cur.idx())->getStatus(cur, cmd, status);
4885         }
4886
4887         // disable in non-fixed-width cells
4888         case LFUN_PARAGRAPH_BREAK:
4889                 // multirow does not allow paragraph breaks
4890                 if (tabular.isMultiRow(cur.idx())) {
4891                         status.setEnabled(false);
4892                         return true;
4893                 }
4894         case LFUN_NEWLINE_INSERT: {
4895                 if (tabular.getPWidth(cur.idx()).zero()) {
4896                         status.setEnabled(false);
4897                         return true;
4898                 } else
4899                         return cell(cur.idx())->getStatus(cur, cmd, status);
4900         }
4901
4902         case LFUN_NEWPAGE_INSERT:
4903                 status.setEnabled(false);
4904                 return true;
4905
4906         case LFUN_PASTE:
4907                 if (tabularStackDirty() && theClipboard().isInternal()) {
4908                         if (cur.selIsMultiCell()) {
4909                                 row_type rs, re;
4910                                 col_type cs, ce;
4911                                 getSelection(cur, rs, re, cs, ce);
4912                                 if (paste_tabular && paste_tabular->ncols() == ce - cs + 1
4913                                           && paste_tabular->nrows() == re - rs + 1)
4914                                         status.setEnabled(true);        
4915                                 else {
4916                                         status.setEnabled(false);
4917                                         status.message(_("Selection size should match clipboard content."));
4918                                 }
4919                         } else
4920                                 status.setEnabled(true);
4921                         return true;
4922                 }
4923                 return cell(cur.idx())->getStatus(cur, cmd, status);
4924
4925         case LFUN_INSET_SETTINGS:
4926                 // relay this lfun to Inset, not to the cell.
4927                 return Inset::getStatus(cur, cmd, status);
4928
4929         default:
4930                 // we try to handle this event in the insets dispatch function.
4931                 return cell(cur.idx())->getStatus(cur, cmd, status);
4932         }
4933         return false;
4934 }
4935
4936
4937 Inset::DisplayType InsetTabular::display() const
4938 {
4939                 if (tabular.is_long_tabular) {
4940                         switch (tabular.longtabular_alignment) {
4941                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
4942                                 return AlignLeft;
4943                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
4944                                 return AlignCenter;
4945                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
4946                                 return AlignRight;
4947                         default:
4948                                 return AlignCenter;
4949                         }
4950                 } else
4951                         return Inline;
4952 }
4953
4954
4955 void InsetTabular::latex(otexstream & os, OutputParams const & runparams) const
4956 {
4957         tabular.latex(os, runparams);
4958 }
4959
4960
4961 int InsetTabular::plaintext(odocstringstream & os,
4962         OutputParams const & runparams, size_t max_length) const
4963 {
4964         os << '\n'; // output table on a new line
4965         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
4966         tabular.plaintext(os, runparams, dp, false, 0, max_length);
4967         return PLAINTEXT_NEWLINE;
4968 }
4969
4970
4971 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
4972 {
4973         int ret = 0;
4974         Inset * master = 0;
4975
4976         // FIXME: Why not pass a proper DocIterator here?
4977 #if 0
4978         // if the table is inside a float it doesn't need the informaltable
4979         // wrapper. Search for it.
4980         for (master = owner(); master; master = master->owner())
4981                 if (master->lyxCode() == FLOAT_CODE)
4982                         break;
4983 #endif
4984
4985         if (!master) {
4986                 os << "<informaltable>";
4987                 ++ret;
4988         }
4989         ret += tabular.docbook(os, runparams);
4990         if (!master) {
4991                 os << "</informaltable>";
4992                 ++ret;
4993         }
4994         return ret;
4995 }
4996
4997
4998 docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
4999 {
5000         return tabular.xhtml(xs, rp);
5001 }
5002
5003
5004 void InsetTabular::validate(LaTeXFeatures & features) const
5005 {
5006         tabular.validate(features);
5007         // FIXME XHTML
5008         // It'd be better to be able to get this from an InsetLayout, but at present
5009         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
5010         if (features.runparams().flavor == OutputParams::HTML)
5011                 features.addCSSSnippet(
5012                         "table { border: 1px solid black; display: inline-block; }\n"
5013                         "td { border: 1px solid black; padding: 0.5ex; }");
5014 }
5015
5016
5017 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
5018 {
5019         return tabular.cellInset(idx);
5020 }
5021
5022
5023 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
5024 {
5025         return tabular.cellInset(idx);
5026 }
5027
5028
5029 void InsetTabular::cursorPos(BufferView const & bv,
5030                 CursorSlice const & sl, bool boundary, int & x, int & y) const
5031 {
5032         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
5033
5034         // y offset     correction
5035         y += cellYPos(sl.idx());
5036         y += tabular.textVOffset(sl.idx());
5037         y += offset_valign_;
5038
5039         // x offset correction
5040         x += cellXPos(sl.idx());
5041         x += tabular.textHOffset(sl.idx());
5042         x += ADD_TO_TABULAR_WIDTH;
5043         x += scx_;
5044 }
5045
5046
5047 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
5048 {
5049         int xx = 0;
5050         int yy = 0;
5051         Inset const & inset = *tabular.cellInset(cell);
5052         Point o = bv.coordCache().getInsets().xy(&inset);
5053         int const xbeg = o.x_ - tabular.textHOffset(cell);
5054         int const xend = xbeg + tabular.cellWidth(cell);
5055         row_type const row = tabular.cellRow(cell);
5056         int const ybeg = o.y_ - tabular.rowAscent(row)
5057                 - tabular.interRowSpace(row) - tabular.textVOffset(cell);
5058         int const yend = ybeg + tabular.cellHeight(cell);
5059
5060         if (x < xbeg)
5061                 xx = xbeg - x;
5062         else if (x > xend)
5063                 xx = x - xend;
5064
5065         if (y < ybeg)
5066                 yy = ybeg - y;
5067         else if (y > yend)
5068                 yy = y - yend;
5069
5070         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
5071         //       << " ybeg=" << ybeg << " yend=" << yend
5072         //       << " xx=" << xx << " yy=" << yy
5073         //       << " dist=" << xx + yy << endl;
5074         return xx + yy;
5075 }
5076
5077
5078 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
5079 {
5080         //lyxerr << "InsetTabular::editXY: " << this << endl;
5081         cur.setSelection(false);
5082         cur.push(*this);
5083         cur.idx() = getNearestCell(cur.bv(), x, y);
5084         resetPos(cur);
5085         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
5086 }
5087
5088
5089 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
5090 {
5091         cur.idx() = getNearestCell(cur.bv(), x, y);
5092         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
5093 }
5094
5095
5096 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
5097 {
5098         idx_type idx_min = 0;
5099         int dist_min = numeric_limits<int>::max();
5100         for (idx_type i = 0, n = nargs(); i != n; ++i) {
5101                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
5102                         int const d = dist(bv, i, x, y);
5103                         if (d < dist_min) {
5104                                 dist_min = d;
5105                                 idx_min = i;
5106                         }
5107                 }
5108         }
5109         return idx_min;
5110 }
5111
5112
5113 int InsetTabular::cellYPos(idx_type const cell) const
5114 {
5115         row_type row = tabular.cellRow(cell);
5116         int ly = 0;
5117         for (row_type r = 0; r < row; ++r)
5118                 ly += tabular.rowDescent(r) + tabular.rowAscent(r + 1) 
5119                         + tabular.interRowSpace(r + 1);
5120         return ly;
5121 }
5122
5123
5124 int InsetTabular::cellXPos(idx_type const cell) const
5125 {
5126         col_type col = tabular.cellColumn(cell);
5127         int lx = 0;
5128         for (col_type c = 0; c < col; ++c)
5129                 lx += tabular.column_info[c].width;
5130         return lx;
5131 }
5132
5133
5134 void InsetTabular::resetPos(Cursor & cur) const
5135 {
5136         BufferView & bv = cur.bv();
5137         int const maxwidth = bv.workWidth();
5138
5139         int const scx_old = scx_;
5140         int const i = cur.find(this);
5141         if (i == -1) {
5142                 scx_ = 0;
5143         } else {
5144                 int const X1 = 0;
5145                 int const X2 = maxwidth;
5146                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
5147                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
5148                 int const x2 = x1 + tabular.cellWidth(cur[i].idx());
5149
5150                 if (x1 < X1)
5151                         scx_ = X1 + 20 - x1;
5152                 else if (x2 > X2)
5153                         scx_ = X2 - 20 - x2;
5154                 else
5155                         scx_ = 0;
5156         }
5157
5158         // only update if offset changed
5159         if (scx_ != scx_old)
5160                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
5161 }
5162
5163
5164 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
5165 {
5166         row_type const row = tabular.cellRow(cur.idx());
5167         col_type const col = tabular.cellColumn(cur.idx());
5168
5169         if (isRightToLeft(cur)) {
5170                 if (tabular.cellColumn(cur.idx()) == 0) {
5171                         if (row == tabular.nrows() - 1)
5172                                 return;
5173                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
5174                 } else {
5175                         if (cur.idx() == 0)
5176                                 return;
5177                         if (col == 0)
5178                                 cur.idx() = tabular.getLastCellInRow(row - 1);
5179                         else
5180                                 cur.idx() = tabular.cellIndex(row, col - 1);
5181                 }
5182         } else {
5183                 if (tabular.isLastCell(cur.idx()))
5184                         return;
5185                 if (cur.idx() == tabular.getLastCellInRow(row))
5186                         cur.idx() = tabular.cellIndex(row + 1, 0);
5187                 else {
5188                         col_type const colnextcell = col + tabular.columnSpan(cur.idx());
5189                         cur.idx() = tabular.cellIndex(row, colnextcell);
5190                 }
5191         }
5192
5193         cur.boundary(false);
5194
5195         if (cur.selIsMultiCell()) {
5196                 cur.pit() = cur.lastpit();
5197                 cur.pos() = cur.lastpos();
5198                 resetPos(cur);
5199                 return;
5200         }
5201
5202         cur.pit() = 0;
5203         cur.pos() = 0;
5204
5205         // in visual mode, place cursor at extreme left or right
5206         
5207         switch(entry_from) {
5208
5209         case ENTRY_DIRECTION_RIGHT:
5210                 cur.posVisToRowExtremity(false /* !left */);
5211                 break;
5212         case ENTRY_DIRECTION_LEFT:
5213                 cur.posVisToRowExtremity(true /* left */);
5214                 break;
5215         case ENTRY_DIRECTION_IGNORE:
5216                 // nothing to do in this case
5217                 break;
5218
5219         }
5220         cur.setCurrentFont();
5221         resetPos(cur);
5222 }
5223
5224
5225 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
5226 {
5227         row_type const row = tabular.cellRow(cur.idx());
5228         col_type const col = tabular.cellColumn(cur.idx());
5229
5230         if (isRightToLeft(cur)) {
5231                 if (cur.idx() == tabular.getLastCellInRow(row)) {
5232                         if (row == 0)
5233                                 return;
5234                         cur.idx() = tabular.getFirstCellInRow(row);
5235                         cur.idx() = tabular.cellAbove(cur.idx());
5236                 } else {
5237                         if (tabular.isLastCell(cur.idx()))
5238                                 return;
5239                         if (cur.idx() == tabular.getLastCellInRow(row))
5240                                 cur.idx() = tabular.cellIndex(row + 1, 0);
5241                         else
5242                                 cur.idx() = tabular.cellIndex(row, col + 1);
5243                 }
5244         } else {
5245                 if (cur.idx() == 0) // first cell
5246                         return;
5247                 if (col == 0)
5248                         cur.idx() = tabular.getLastCellInRow(row - 1);
5249                 else
5250                         cur.idx() = tabular.cellIndex(row, col - 1);
5251         }
5252
5253         if (cur.selIsMultiCell()) {
5254                 cur.pit() = cur.lastpit();
5255                 cur.pos() = cur.lastpos();
5256                 resetPos(cur);
5257                 return;
5258         }
5259
5260         cur.pit() = cur.lastpit();
5261         cur.pos() = cur.lastpos();
5262
5263         // in visual mode, place cursor at extreme left or right
5264         
5265         switch(entry_from) {
5266
5267         case ENTRY_DIRECTION_RIGHT:
5268                 cur.posVisToRowExtremity(false /* !left */);
5269                 break;
5270         case ENTRY_DIRECTION_LEFT:
5271                 cur.posVisToRowExtremity(true /* left */);
5272                 break;
5273         case ENTRY_DIRECTION_IGNORE:
5274                 // nothing to do in this case
5275                 break;
5276
5277         }
5278         cur.setCurrentFont();
5279         resetPos(cur);
5280 }
5281
5282
5283 bool InsetTabular::tabularFeatures(Cursor & cur, string const & argument)
5284 {
5285         istringstream is(argument);
5286         string s;
5287         is >> s;
5288         if (insetCode(s) != TABULAR_CODE)
5289                 return false;
5290
5291         // Safe guard.
5292         size_t safe_guard = 0;
5293         for (;;) {
5294                 if (is.eof())
5295                         break;
5296                 safe_guard++;
5297                 if (safe_guard > 1000) {
5298                         LYXERR0("parameter max count reached!");
5299                         break;
5300                 }
5301                 is >> s;
5302                 Tabular::Feature action = Tabular::LAST_ACTION;
5303
5304                 size_t i = 0;
5305                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
5306                         if (s != tabularFeature[i].feature)
5307                                 continue;
5308                         action = tabularFeature[i].action;
5309                         break;
5310                 }
5311                 if (action == Tabular::LAST_ACTION) {
5312                         LYXERR0("Feature not found " << s);
5313                         continue;
5314                 }
5315                 string val;
5316                 if (tabularFeature[i].need_value)
5317                         is >> val;
5318                 LYXERR(Debug::DEBUG, "Feature: " << s << "\t\tvalue: " << val);
5319                 tabularFeatures(cur, action, val);
5320         }
5321         return true;
5322 }
5323
5324
5325 static void checkLongtableSpecial(Tabular::ltType & ltt,
5326                           string const & special, bool & flag)
5327 {
5328         if (special == "dl_above") {
5329                 ltt.topDL = flag;
5330                 ltt.set = false;
5331         } else if (special == "dl_below") {
5332                 ltt.bottomDL = flag;
5333                 ltt.set = false;
5334         } else if (special == "empty") {
5335                 ltt.empty = flag;
5336                 ltt.set = false;
5337         } else if (flag) {
5338                 ltt.empty = false;
5339                 ltt.set = true;
5340         }
5341 }
5342
5343
5344 bool InsetTabular::oneCellHasRotationState(bool rotated,
5345                 row_type row_start, row_type row_end,
5346                 col_type col_start, col_type col_end) const 
5347 {
5348         for (row_type r = row_start; r <= row_end; ++r)
5349                 for (col_type c = col_start; c <= col_end; ++c)
5350                         if (rotated) {
5351                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) != 0)
5352                                         return true;
5353                         } else {
5354                                 if (tabular.getRotateCell(tabular.cellIndex(r, c)) == 0)
5355                                         return true;
5356                         }
5357         return false;
5358 }
5359
5360
5361 void InsetTabular::tabularFeatures(Cursor & cur,
5362         Tabular::Feature feature, string const & value)
5363 {
5364         col_type sel_col_start;
5365         col_type sel_col_end;
5366         row_type sel_row_start;
5367         row_type sel_row_end;
5368         bool setLines = false;
5369         LyXAlignment setAlign = LYX_ALIGN_LEFT;
5370         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
5371
5372         switch (feature) {
5373
5374         case Tabular::M_ALIGN_LEFT:
5375         case Tabular::ALIGN_LEFT:
5376                 setAlign = LYX_ALIGN_LEFT;
5377                 break;
5378
5379         case Tabular::M_ALIGN_RIGHT:
5380         case Tabular::ALIGN_RIGHT:
5381                 setAlign = LYX_ALIGN_RIGHT;
5382                 break;
5383
5384         case Tabular::M_ALIGN_CENTER:
5385         case Tabular::ALIGN_CENTER:
5386                 setAlign = LYX_ALIGN_CENTER;
5387                 break;
5388
5389         case Tabular::ALIGN_BLOCK:
5390                 setAlign = LYX_ALIGN_BLOCK;
5391                 break;
5392
5393         case Tabular::ALIGN_DECIMAL:
5394                 if (tabular.column_info[tabular.cellColumn(cur.idx())].alignment == LYX_ALIGN_DECIMAL)
5395                         setAlign = LYX_ALIGN_CENTER;
5396                 else
5397                         setAlign = LYX_ALIGN_DECIMAL;
5398                 break;
5399
5400         case Tabular::M_VALIGN_TOP:
5401         case Tabular::VALIGN_TOP:
5402                 setVAlign = Tabular::LYX_VALIGN_TOP;
5403                 break;
5404
5405         case Tabular::M_VALIGN_BOTTOM:
5406         case Tabular::VALIGN_BOTTOM:
5407                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
5408                 break;
5409
5410         case Tabular::M_VALIGN_MIDDLE:
5411         case Tabular::VALIGN_MIDDLE:
5412                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
5413                 break;
5414
5415         default:
5416                 break;
5417         }
5418
5419         cur.recordUndoInset(ATOMIC_UNDO, this);
5420
5421         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5422         row_type const row = tabular.cellRow(cur.idx());
5423         col_type const column = tabular.cellColumn(cur.idx());
5424         bool flag = true;
5425         Tabular::ltType ltt;
5426
5427         switch (feature) {
5428
5429         case Tabular::SET_TABULAR_WIDTH:
5430                 tabular.setTabularWidth(Length(value));
5431                 break;
5432
5433         case Tabular::SET_PWIDTH: {
5434                 Length const len(value);
5435                 tabular.setColumnPWidth(cur, cur.idx(), len);
5436                 if (len.zero()
5437                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
5438                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
5439                 break;
5440         }
5441
5442         case Tabular::SET_MPWIDTH:
5443                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
5444                 break;
5445
5446         case Tabular::SET_MROFFSET:
5447                 tabular.setMROffset(cur, cur.idx(), Length(value));
5448                 break;
5449
5450         case Tabular::SET_SPECIAL_COLUMN:
5451         case Tabular::SET_SPECIAL_MULTICOLUMN:
5452                 if (value == "none")
5453                         tabular.setAlignSpecial(cur.idx(), docstring(), feature);
5454                 else
5455                         tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
5456                 break;
5457
5458         case Tabular::APPEND_ROW:
5459                 // append the row into the tabular
5460                 tabular.appendRow(row);
5461                 break;
5462
5463         case Tabular::APPEND_COLUMN:
5464                 // append the column into the tabular
5465                 tabular.appendColumn(column);
5466                 cur.idx() = tabular.cellIndex(row, column);
5467                 break;
5468
5469         case Tabular::DELETE_ROW:
5470                 if (sel_row_end == tabular.nrows() - 1 && sel_row_start != 0) {
5471                         for (col_type c = 0; c < tabular.ncols(); c++)
5472                                 tabular.setBottomLine(tabular.cellIndex(sel_row_start - 1, c),
5473                                         tabular.bottomLine(tabular.cellIndex(sel_row_end, c)));
5474                 }
5475
5476                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5477                         tabular.deleteRow(sel_row_start);
5478                 if (sel_row_start >= tabular.nrows())
5479                         --sel_row_start;
5480                 cur.idx() = tabular.cellIndex(sel_row_start, column);
5481                 cur.pit() = 0;
5482                 cur.pos() = 0;
5483                 cur.setSelection(false);
5484                 break;
5485
5486         case Tabular::DELETE_COLUMN:
5487                 if (sel_col_end == tabular.ncols() - 1 && sel_col_start != 0) {
5488                         for (row_type r = 0; r < tabular.nrows(); r++)
5489                                 tabular.setRightLine(tabular.cellIndex(r, sel_col_start - 1),
5490                                         tabular.rightLine(tabular.cellIndex(r, sel_col_end)));
5491                 }
5492
5493                 if (sel_col_start == 0 && sel_col_end != tabular.ncols() - 1) {
5494                         for (row_type r = 0; r < tabular.nrows(); r++)
5495                                 tabular.setLeftLine(tabular.cellIndex(r, sel_col_end + 1),
5496                                         tabular.leftLine(tabular.cellIndex(r, 0)));
5497                 }
5498
5499                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5500                         tabular.deleteColumn(sel_col_start);
5501                 if (sel_col_start >= tabular.ncols())
5502                         --sel_col_start;
5503                 cur.idx() = tabular.cellIndex(row, sel_col_start);
5504                 cur.pit() = 0;
5505                 cur.pos() = 0;
5506                 cur.setSelection(false);
5507                 break;
5508
5509         case Tabular::COPY_ROW:
5510                 tabular.copyRow(row);
5511                 break;
5512
5513         case Tabular::COPY_COLUMN:
5514                 tabular.copyColumn(column);
5515                 cur.idx() = tabular.cellIndex(row, column);
5516                 break;
5517
5518         case Tabular::MOVE_COLUMN_RIGHT:
5519                 tabular.moveColumn(column, Tabular::RIGHT);
5520                 cur.idx() = tabular.cellIndex(row, column + 1);
5521                 break;
5522
5523         case Tabular::MOVE_COLUMN_LEFT:
5524                 tabular.moveColumn(column, Tabular::LEFT);
5525                 cur.idx() = tabular.cellIndex(row, column - 1);
5526                 break;
5527
5528         case Tabular::MOVE_ROW_DOWN:
5529                 tabular.moveRow(row, Tabular::DOWN);
5530                 cur.idx() = tabular.cellIndex(row + 1, column);
5531                 break;
5532
5533         case Tabular::MOVE_ROW_UP:
5534                 tabular.moveRow(row, Tabular::UP);
5535                 cur.idx() = tabular.cellIndex(row - 1, column);
5536                 break;
5537
5538         case Tabular::SET_LINE_TOP:
5539         case Tabular::TOGGLE_LINE_TOP: {
5540                 bool lineSet = (feature == Tabular::SET_LINE_TOP)
5541                                ? (value == "true") : !tabular.topLine(cur.idx());
5542                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5543                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5544                                 tabular.setTopLine(tabular.cellIndex(r, c), lineSet);
5545                 break;
5546         }
5547
5548         case Tabular::SET_LINE_BOTTOM:
5549         case Tabular::TOGGLE_LINE_BOTTOM: {
5550                 bool lineSet = (feature == Tabular::SET_LINE_BOTTOM)
5551                                ? (value == "true") : !tabular.bottomLine(cur.idx());
5552                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5553                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5554                                 tabular.setBottomLine(tabular.cellIndex(r, c), lineSet);
5555                 break;
5556         }
5557
5558         case Tabular::SET_LINE_LEFT:
5559         case Tabular::TOGGLE_LINE_LEFT: {
5560                 bool lineSet = (feature == Tabular::SET_LINE_LEFT)
5561                                ? (value == "true") : !tabular.leftLine(cur.idx());
5562                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5563                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5564                                 tabular.setLeftLine(tabular.cellIndex(r, c), lineSet);
5565                 break;
5566         }
5567
5568         case Tabular::SET_LINE_RIGHT:
5569         case Tabular::TOGGLE_LINE_RIGHT: {
5570                 bool lineSet = (feature == Tabular::SET_LINE_RIGHT)
5571                                ? (value == "true") : !tabular.rightLine(cur.idx());
5572                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5573                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5574                                 tabular.setRightLine(tabular.cellIndex(r, c), lineSet);
5575                 break;
5576         }
5577
5578         case Tabular::M_ALIGN_LEFT:
5579         case Tabular::M_ALIGN_RIGHT:
5580         case Tabular::M_ALIGN_CENTER:
5581         case Tabular::ALIGN_LEFT:
5582         case Tabular::ALIGN_RIGHT:
5583         case Tabular::ALIGN_CENTER:
5584         case Tabular::ALIGN_BLOCK:
5585         case Tabular::ALIGN_DECIMAL:
5586                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5587                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5588                                 tabular.setAlignment(tabular.cellIndex(r, c), setAlign,
5589                                 !tabular.getPWidth(c).zero());
5590                 break;
5591
5592         case Tabular::M_VALIGN_TOP:
5593         case Tabular::M_VALIGN_BOTTOM:
5594         case Tabular::M_VALIGN_MIDDLE:
5595                 flag = false;
5596         case Tabular::VALIGN_TOP:
5597         case Tabular::VALIGN_BOTTOM:
5598         case Tabular::VALIGN_MIDDLE:
5599                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5600                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5601                                 tabular.setVAlignment(tabular.cellIndex(r, c), setVAlign, flag);
5602                 break;
5603
5604         case Tabular::SET_MULTICOLUMN: {
5605                 if (!cur.selection()) {
5606                         // just multicol for one single cell
5607                         // check whether we are completely in a multicol
5608                         if (!tabular.isMultiColumn(cur.idx()))
5609                                 tabular.setMultiColumn(cur.idx(), 1,
5610                                         tabular.rightLine(cur.idx()));
5611                         break;
5612                 }
5613                 // we have a selection so this means we just add all these
5614                 // cells to form a multicolumn cell
5615                 idx_type const s_start = cur.selBegin().idx();
5616                 row_type const col_start = tabular.cellColumn(s_start);
5617                 row_type const col_end = tabular.cellColumn(cur.selEnd().idx());
5618                 cur.idx() = tabular.setMultiColumn(s_start, col_end - col_start + 1,
5619                                                    tabular.rightLine(cur.selEnd().idx()));
5620                 cur.pit() = 0;
5621                 cur.pos() = 0;
5622                 cur.setSelection(false);
5623                 break;
5624         }
5625
5626         case Tabular::UNSET_MULTICOLUMN: {
5627                 if (!cur.selection()) {
5628                         if (tabular.isMultiColumn(cur.idx()))
5629                                 tabular.unsetMultiColumn(cur.idx());
5630                 }
5631                 break;
5632         }
5633
5634         case Tabular::MULTICOLUMN: {
5635                 if (!cur.selection()) {
5636                         if (tabular.isMultiColumn(cur.idx()))
5637                                 tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5638                         else
5639                                 tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5640                         break;
5641                 }
5642                 bool merge = false;
5643                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5644                         row_type const r = sel_row_start;
5645                         if (!tabular.isMultiColumn(tabular.cellIndex(r, c))
5646                             || (r > sel_row_start && !tabular.isPartOfMultiColumn(r, c)))
5647                                 merge = true;
5648                 }
5649                 // If the selection contains at least one singlecol cell
5650                 // or multiple multicol cells,
5651                 // we assume the user will merge is to a single multicol
5652                 if (merge)
5653                         tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5654                 else
5655                         tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5656                 break;
5657         }
5658
5659         case Tabular::SET_MULTIROW: {
5660                 if (!cur.selection()) {
5661                         // just multirow for one single cell
5662                         // check whether we are completely in a multirow
5663                         if (!tabular.isMultiRow(cur.idx()))
5664                                 tabular.setMultiRow(cur.idx(), 1,
5665                                                     tabular.bottomLine(cur.idx()));
5666                         break;
5667                 }
5668                 // we have a selection so this means we just add all this
5669                 // cells to form a multirow cell
5670                 idx_type const s_start = cur.selBegin().idx();
5671                 row_type const row_start = tabular.cellRow(s_start);
5672                 row_type const row_end = tabular.cellRow(cur.selEnd().idx());
5673                 cur.idx() = tabular.setMultiRow(s_start, row_end - row_start + 1,
5674                                                 tabular.bottomLine(cur.selEnd().idx()));
5675                 cur.pit() = 0;
5676                 cur.pos() = 0;
5677                 cur.setSelection(false);
5678                 break;
5679         }
5680
5681         case Tabular::UNSET_MULTIROW: {
5682                 if (!cur.selection()) {
5683                         if (tabular.isMultiRow(cur.idx()))
5684                                 tabular.unsetMultiRow(cur.idx());
5685                 }
5686                 break;
5687         }
5688
5689         case Tabular::MULTIROW: {
5690                 if (!cur.selection()) {
5691                         if (tabular.isMultiRow(cur.idx()))
5692                                 tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5693                         else
5694                                 tabularFeatures(cur, Tabular::SET_MULTIROW);
5695                         break;
5696                 }
5697                 bool merge = false;
5698                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5699                         col_type const c = sel_col_start;
5700                         if (!tabular.isMultiRow(tabular.cellIndex(r, c))
5701                             || (r > sel_row_start && !tabular.isPartOfMultiRow(r, c)))
5702                                 merge = true;
5703                 }
5704                 // If the selection contains at least one singlerow cell
5705                 // or multiple multirow cells,
5706                 // we assume the user will merge is to a single multirow
5707                 if (merge)
5708                         tabularFeatures(cur, Tabular::SET_MULTIROW);
5709                 else
5710                         tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5711                 break;
5712         }
5713
5714         case Tabular::SET_ALL_LINES:
5715                 setLines = true;
5716         case Tabular::UNSET_ALL_LINES:
5717                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5718                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5719                                 idx_type const cell = tabular.cellIndex(r, c);
5720                                 tabular.setTopLine(cell, setLines);
5721                                 tabular.setBottomLine(cell, setLines);
5722                                 tabular.setRightLine(cell, setLines);
5723                                 tabular.setLeftLine(cell, setLines);
5724                         }
5725                 break;
5726
5727         case Tabular::SET_BORDER_LINES:
5728                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5729                         tabular.setLeftLine(tabular.cellIndex(r, sel_col_start), true);
5730                         tabular.setRightLine(tabular.cellIndex(r, sel_col_end), true);
5731                 }
5732                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5733                         tabular.setTopLine(tabular.cellIndex(sel_row_start, c), true);
5734                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, c), true);
5735                 }
5736                 break;
5737
5738         case Tabular::SET_LONGTABULAR:
5739                 tabular.is_long_tabular = true;
5740                 break;
5741
5742         case Tabular::UNSET_LONGTABULAR:
5743                 for (row_type r = 0; r < tabular.nrows(); ++r) {
5744                         if (tabular.ltCaption(r)) {
5745                                 cur.idx() = tabular.cellIndex(r, 0);
5746                                 cur.pit() = 0;
5747                                 cur.pos() = 0;
5748                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
5749                         }
5750                 }
5751                 tabular.is_long_tabular = false;
5752                 break;
5753
5754         case Tabular::SET_ROTATE_TABULAR:
5755                 tabular.rotate = convert<int>(value);
5756                 break;
5757
5758         case Tabular::UNSET_ROTATE_TABULAR:
5759                 tabular.rotate = 0;
5760                 break;
5761
5762         case Tabular::TOGGLE_ROTATE_TABULAR:
5763                 // when pressing the rotate button we default to 90° rotation
5764                 tabular.rotate != 0 ? tabular.rotate = 0 : tabular.rotate = 90;
5765                 break;
5766
5767         case Tabular::TABULAR_VALIGN_TOP:
5768                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
5769                 break;
5770
5771         case Tabular::TABULAR_VALIGN_MIDDLE:
5772                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
5773                 break;
5774
5775         case Tabular::TABULAR_VALIGN_BOTTOM:
5776                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
5777                 break;
5778
5779         case Tabular::LONGTABULAR_ALIGN_LEFT:
5780                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
5781                 break;
5782
5783         case Tabular::LONGTABULAR_ALIGN_CENTER:
5784                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
5785                 break;
5786
5787         case Tabular::LONGTABULAR_ALIGN_RIGHT:
5788                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
5789                 break;
5790
5791                 
5792
5793         case Tabular::SET_ROTATE_CELL:
5794                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5795                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5796                                 tabular.setRotateCell(tabular.cellIndex(r, c), convert<int>(value));
5797                 break;
5798
5799         case Tabular::UNSET_ROTATE_CELL:
5800                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5801                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5802                                 tabular.setRotateCell(tabular.cellIndex(r, c), 0);
5803                 break;
5804
5805         case Tabular::TOGGLE_ROTATE_CELL:
5806                 {
5807                 bool oneNotRotated = oneCellHasRotationState(false,
5808                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5809
5810                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5811                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5812                                 // when pressing the rotate cell button we default to 90° rotation
5813                                 if (oneNotRotated)
5814                                         tabular.setRotateCell(tabular.cellIndex(r, c), 90);
5815                                 else
5816                                         tabular.setRotateCell(tabular.cellIndex(r, c), 0);
5817                         }
5818                 }
5819                 break;
5820
5821         case Tabular::SET_USEBOX: {
5822                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
5823                 if (val == tabular.getUsebox(cur.idx()))
5824                         val = Tabular::BOX_NONE;
5825                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5826                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5827                                 tabular.setUsebox(tabular.cellIndex(r, c), val);
5828                 break;
5829         }
5830
5831         case Tabular::UNSET_LTFIRSTHEAD:
5832                 flag = false;
5833         case Tabular::SET_LTFIRSTHEAD:
5834                 tabular.getRowOfLTFirstHead(row, ltt);
5835                 checkLongtableSpecial(ltt, value, flag);
5836                 tabular.setLTHead(row, flag, ltt, true);
5837                 break;
5838
5839         case Tabular::UNSET_LTHEAD:
5840                 flag = false;
5841         case Tabular::SET_LTHEAD:
5842                 tabular.getRowOfLTHead(row, ltt);
5843                 checkLongtableSpecial(ltt, value, flag);
5844                 tabular.setLTHead(row, flag, ltt, false);
5845                 break;
5846
5847         case Tabular::UNSET_LTFOOT:
5848                 flag = false;
5849         case Tabular::SET_LTFOOT:
5850                 tabular.getRowOfLTFoot(row, ltt);
5851                 checkLongtableSpecial(ltt, value, flag);
5852                 tabular.setLTFoot(row, flag, ltt, false);
5853                 break;
5854
5855         case Tabular::UNSET_LTLASTFOOT:
5856                 flag = false;
5857         case Tabular::SET_LTLASTFOOT:
5858                 tabular.getRowOfLTLastFoot(row, ltt);
5859                 checkLongtableSpecial(ltt, value, flag);
5860                 tabular.setLTFoot(row, flag, ltt, true);
5861                 break;
5862
5863         case Tabular::UNSET_LTNEWPAGE:
5864                 flag = false;
5865         case Tabular::SET_LTNEWPAGE:
5866                 tabular.setLTNewPage(row, flag);
5867                 break;
5868
5869         case Tabular::SET_LTCAPTION: {
5870                 if (tabular.ltCaption(row))
5871                         break;
5872                 cur.idx() = tabular.setLTCaption(row, true);
5873                 cur.pit() = 0;
5874                 cur.pos() = 0;
5875                 cur.setSelection(false);
5876                 // If a row is set as caption, then also insert
5877                 // a caption. Otherwise the LaTeX output is broken.
5878                 lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
5879                 lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
5880                 break;
5881         }
5882         
5883         case Tabular::UNSET_LTCAPTION: {
5884                 if (!tabular.ltCaption(row))
5885                         break;
5886                 cur.idx() = tabular.setLTCaption(row, false);
5887                 cur.pit() = 0;
5888                 cur.pos() = 0;
5889                 cur.setSelection(false);
5890                 FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
5891                 if (lyx::getStatus(fr).enabled())
5892                         lyx::dispatch(fr);
5893                 break;
5894         }
5895
5896         case Tabular::TOGGLE_LTCAPTION: {
5897                 if (tabular.ltCaption(row))
5898                         tabularFeatures(cur, Tabular::UNSET_LTCAPTION);
5899                 else
5900                         tabularFeatures(cur, Tabular::SET_LTCAPTION);
5901                 break;
5902         }
5903
5904         case Tabular::SET_BOOKTABS:
5905                 tabular.use_booktabs = true;
5906                 break;
5907
5908         case Tabular::UNSET_BOOKTABS:
5909                 tabular.use_booktabs = false;
5910                 break;
5911
5912         case Tabular::SET_TOP_SPACE: {
5913                 Length len;
5914                 if (value == "default")
5915                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5916                                 tabular.row_info[r].top_space_default = true;
5917                 else if (value == "none")
5918                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5919                                 tabular.row_info[r].top_space_default = false;
5920                                 tabular.row_info[r].top_space = len;
5921                         }
5922                 else if (isValidLength(value, &len))
5923                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5924                                 tabular.row_info[r].top_space_default = false;
5925                                 tabular.row_info[r].top_space = len;
5926                         }
5927                 break;
5928         }
5929
5930         case Tabular::SET_BOTTOM_SPACE: {
5931                 Length len;
5932                 if (value == "default")
5933                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5934                                 tabular.row_info[r].bottom_space_default = true;
5935                 else if (value == "none")
5936                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5937                                 tabular.row_info[r].bottom_space_default = false;
5938                                 tabular.row_info[r].bottom_space = len;
5939                         }
5940                 else if (isValidLength(value, &len))
5941                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5942                                 tabular.row_info[r].bottom_space_default = false;
5943                                 tabular.row_info[r].bottom_space = len;
5944                         }
5945                 break;
5946         }
5947
5948         case Tabular::SET_INTERLINE_SPACE: {
5949                 Length len;
5950                 if (value == "default")
5951                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5952                                 tabular.row_info[r].interline_space_default = true;
5953                 else if (value == "none")
5954                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5955                                 tabular.row_info[r].interline_space_default = false;
5956                                 tabular.row_info[r].interline_space = len;
5957                         }
5958                 else if (isValidLength(value, &len))
5959                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5960                                 tabular.row_info[r].interline_space_default = false;
5961                                 tabular.row_info[r].interline_space = len;
5962                         }
5963                 break;
5964         }
5965
5966         case Tabular::SET_DECIMAL_POINT:
5967                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5968                         tabular.column_info[c].decimal_point = from_utf8(value);
5969                 break;
5970
5971         // dummy stuff just to avoid warnings
5972         case Tabular::LAST_ACTION:
5973                 break;
5974         }
5975 }
5976
5977
5978 bool InsetTabular::copySelection(Cursor & cur)
5979 {
5980         if (!cur.selection())
5981                 return false;
5982
5983         row_type rs, re;
5984         col_type cs, ce;
5985         getSelection(cur, rs, re, cs, ce);
5986
5987         paste_tabular.reset(new Tabular(tabular));
5988
5989         for (row_type r = 0; r < rs; ++r)
5990                 paste_tabular->deleteRow(0);
5991
5992         row_type const rows = re - rs + 1;
5993         while (paste_tabular->nrows() > rows)
5994                 paste_tabular->deleteRow(rows);
5995
5996         for (col_type c = 0; c < cs; ++c)
5997                 paste_tabular->deleteColumn(0);
5998
5999         col_type const columns = ce - cs + 1;
6000         while (paste_tabular->ncols() > columns)
6001                 paste_tabular->deleteColumn(columns);
6002
6003         paste_tabular->setBuffer(tabular.buffer());
6004
6005         odocstringstream os;
6006         OutputParams const runparams(0);
6007         paste_tabular->plaintext(os, runparams, 0, true, '\t', INT_MAX);
6008         // Needed for the "Edit->Paste recent" menu and the system clipboard.
6009         cap::copySelection(cur, os.str());
6010
6011         // mark tabular stack dirty
6012         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
6013         // when we (hopefully) have a one-for-all paste mechanism.
6014         // This must be called after cap::copySelection.
6015         dirtyTabularStack(true);
6016
6017         return true;
6018 }
6019
6020
6021 bool InsetTabular::pasteClipboard(Cursor & cur)
6022 {
6023         if (!paste_tabular)
6024                 return false;
6025         col_type actcol = tabular.cellColumn(cur.idx());
6026         row_type actrow = tabular.cellRow(cur.idx());
6027
6028         if (cur.selIsMultiCell()) {
6029                 row_type re;
6030                 col_type ce;
6031                 getSelection(cur, actrow, re, actcol, ce);
6032         }
6033
6034         for (row_type r1 = 0, r2 = actrow;
6035              r1 < paste_tabular->nrows() && r2 < tabular.nrows();
6036              ++r1, ++r2) {
6037                 for (col_type c1 = 0, c2 = actcol;
6038                     c1 < paste_tabular->ncols() && c2 < tabular.ncols();
6039                     ++c1, ++c2) {
6040                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
6041                               tabular.isPartOfMultiColumn(r2, c2))
6042                                 continue;
6043                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
6044                                 --c2;
6045                                 continue;
6046                         }
6047                         if (tabular.isPartOfMultiColumn(r2, c2)) {
6048                                 --c1;
6049                                 continue;
6050                         }
6051                         shared_ptr<InsetTableCell> inset(
6052                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
6053                         tabular.setCellInset(r2, c2, inset);
6054                         // FIXME?: why do we need to do this explicitly? (EL)
6055                         tabular.cellInset(r2, c2)->setBuffer(tabular.buffer());
6056
6057                         // FIXME: change tracking (MG)
6058                         inset->setChange(Change(buffer().params().trackChanges ?
6059                                                 Change::INSERTED : Change::UNCHANGED));
6060                         cur.pos() = 0;
6061                 }
6062         }
6063         return true;
6064 }
6065
6066
6067 void InsetTabular::cutSelection(Cursor & cur)
6068 {
6069         if (!cur.selection())
6070                 return;
6071
6072         row_type rs, re;
6073         col_type cs, ce;
6074         getSelection(cur, rs, re, cs, ce);
6075         for (row_type r = rs; r <= re; ++r) {
6076                 for (col_type c = cs; c <= ce; ++c) {
6077                         shared_ptr<InsetTableCell> t
6078                                 = cell(tabular.cellIndex(r, c));
6079                         if (buffer().params().trackChanges)
6080                                 // FIXME: Change tracking (MG)
6081                                 t->setChange(Change(Change::DELETED));
6082                         else
6083                                 t->clear();
6084                 }
6085         }
6086
6087         // cursor position might be invalid now
6088         if (cur.pit() > cur.lastpit())
6089                 cur.pit() = cur.lastpit();
6090         if (cur.pos() > cur.lastpos())
6091                 cur.pos() = cur.lastpos();
6092         cur.clearSelection();
6093 }
6094
6095
6096 bool InsetTabular::isRightToLeft(Cursor & cur) const
6097 {
6098         LASSERT(cur.depth() > 1, /**/);
6099         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
6100         pos_type const parentpos = cur[cur.depth() - 2].pos();
6101         return parentpar.getFontSettings(buffer().params(),
6102                                          parentpos).language()->rightToLeft();
6103 }
6104
6105
6106 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
6107                                  bool intoInsets)
6108 {
6109         LASSERT(stidx <= enidx, return docstring());
6110         docstring retval;
6111         col_type const col1 = tabular.cellColumn(stidx);
6112         col_type const col2 = tabular.cellColumn(enidx);
6113         row_type const row1 = tabular.cellRow(stidx);
6114         row_type const row2 = tabular.cellRow(enidx);
6115         bool first = true;
6116         for (col_type col = col1; col <= col2; col++)
6117                 for (row_type row = row1; row <= row2; row++) {
6118                         if (!first)
6119                                 retval += "\n";
6120                         else
6121                                 first = false;
6122                         retval += tabular.cellInset(row, col)->asString(intoInsets);
6123                 }
6124         return retval;
6125 }
6126
6127
6128 void InsetTabular::getSelection(Cursor & cur,
6129         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
6130 {
6131         CursorSlice const & beg = cur.selBegin();
6132         CursorSlice const & end = cur.selEnd();
6133         cs = tabular.cellColumn(beg.idx());
6134         ce = tabular.cellColumn(end.idx());
6135         if (cs > ce)
6136                 swap(cs, ce);
6137
6138         rs = tabular.cellRow(beg.idx());
6139         re = tabular.cellRow(end.idx());
6140         if (rs > re)
6141                 swap(rs, re);
6142 }
6143
6144
6145 Text * InsetTabular::getText(int idx) const
6146 {
6147         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
6148 }
6149
6150
6151 void InsetTabular::setChange(Change const & change)
6152 {
6153         for (idx_type idx = 0; idx < nargs(); ++idx)
6154                 cell(idx)->setChange(change);
6155 }
6156
6157
6158 void InsetTabular::acceptChanges()
6159 {
6160         for (idx_type idx = 0; idx < nargs(); ++idx)
6161                 cell(idx)->acceptChanges();
6162 }
6163
6164
6165 void InsetTabular::rejectChanges()
6166 {
6167         for (idx_type idx = 0; idx < nargs(); ++idx)
6168                 cell(idx)->rejectChanges();
6169 }
6170
6171
6172 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
6173 {
6174         return tabular.getPWidth(cell).zero();
6175 }
6176
6177
6178 bool InsetTabular::forcePlainLayout(idx_type cell) const
6179 {
6180         return !tabular.getPWidth(cell).zero();
6181 }
6182
6183
6184 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
6185                                      bool usePaste)
6186 {
6187         if (buf.length() <= 0)
6188                 return true;
6189
6190         col_type cols = 1;
6191         row_type rows = 1;
6192         col_type maxCols = 1;
6193         size_t const len = buf.length();
6194         size_t p = 0;
6195
6196         while (p < len &&
6197                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
6198                 switch (buf[p]) {
6199                 case '\t':
6200                         ++cols;
6201                         break;
6202                 case '\n':
6203                         if (p + 1 < len)
6204                                 ++rows;
6205                         maxCols = max(cols, maxCols);
6206                         cols = 1;
6207                         break;
6208                 }
6209                 ++p;
6210         }
6211         maxCols = max(cols, maxCols);
6212         Tabular * loctab;
6213         idx_type cell = 0;
6214         col_type ocol = 0;
6215         row_type row = 0;
6216         if (usePaste) {
6217                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
6218                 loctab = paste_tabular.get();
6219                 cols = 0;
6220                 dirtyTabularStack(true);
6221         } else {
6222                 loctab = &tabular;
6223                 cell = bv.cursor().idx();
6224                 ocol = tabular.cellColumn(cell);
6225                 row = tabular.cellRow(cell);
6226         }
6227
6228         size_t op = 0;
6229         idx_type const cells = loctab->numberofcells;
6230         p = 0;
6231         cols = ocol;
6232         rows = loctab->nrows();
6233         col_type const columns = loctab->ncols();
6234
6235         while (cell < cells && p < len && row < rows &&
6236                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
6237         {
6238                 if (p >= len)
6239                         break;
6240                 switch (buf[p]) {
6241                 case '\t':
6242                         // we can only set this if we are not too far right
6243                         if (cols < columns) {
6244                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6245                                 Font const font = bv.textMetrics(&inset->text()).
6246                                         displayFont(0, 0);
6247                                 inset->setText(buf.substr(op, p - op), font,
6248                                                buffer().params().trackChanges);
6249                                 ++cols;
6250                                 ++cell;
6251                         }
6252                         break;
6253                 case '\n':
6254                         // we can only set this if we are not too far right
6255                         if (cols < columns) {
6256                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
6257                                 Font const font = bv.textMetrics(&inset->text()).
6258                                         displayFont(0, 0);
6259                                 inset->setText(buf.substr(op, p - op), font,
6260                                                buffer().params().trackChanges);
6261                         }
6262                         cols = ocol;
6263                         ++row;
6264                         if (row < rows)
6265                                 cell = loctab->cellIndex(row, cols);
6266                         break;
6267                 }
6268                 ++p;
6269                 op = p;
6270         }
6271         // check for the last cell if there is no trailing '\n'
6272         if (cell < cells && op < len) {
6273                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6274                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
6275                 inset->setText(buf.substr(op, len - op), font,
6276                         buffer().params().trackChanges);
6277         }
6278         return true;
6279 }
6280
6281
6282 void InsetTabular::addPreview(DocIterator const & inset_pos,
6283         PreviewLoader & loader) const
6284 {
6285         DocIterator cell_pos = inset_pos;
6286
6287         cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
6288         for (row_type r = 0; r < tabular.nrows(); ++r) {
6289                 for (col_type c = 0; c < tabular.ncols(); ++c) {
6290                         cell_pos.top().idx() = tabular.cellIndex(r, c);
6291                         tabular.cellInset(r, c)->addPreview(cell_pos, loader);
6292                 }
6293         }
6294 }
6295
6296
6297 bool InsetTabular::completionSupported(Cursor const & cur) const
6298 {
6299         Cursor const & bvCur = cur.bv().cursor();
6300         if (&bvCur.inset() != this)
6301                 return false;
6302         return cur.text()->completionSupported(cur);
6303 }
6304
6305
6306 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
6307 {
6308         return completionSupported(cur);
6309 }
6310
6311
6312 bool InsetTabular::automaticInlineCompletion() const
6313 {
6314         return lyxrc.completion_inline_text;
6315 }
6316
6317
6318 bool InsetTabular::automaticPopupCompletion() const
6319 {
6320         return lyxrc.completion_popup_text;
6321 }
6322
6323
6324 bool InsetTabular::showCompletionCursor() const
6325 {
6326         return lyxrc.completion_cursor_text;
6327 }
6328
6329
6330 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
6331 {
6332         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
6333 }
6334
6335
6336 docstring InsetTabular::completionPrefix(Cursor const & cur) const
6337 {
6338         if (!completionSupported(cur))
6339                 return docstring();
6340         return cur.text()->completionPrefix(cur);
6341 }
6342
6343
6344 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
6345 {
6346         if (!completionSupported(cur))
6347                 return false;
6348
6349         return cur.text()->insertCompletion(cur, s, finished);
6350 }
6351
6352
6353 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
6354                                     Dimension & dim) const
6355 {
6356         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
6357         tm.completionPosAndDim(cur, x, y, dim);
6358 }
6359
6360
6361 void InsetTabular::string2params(string const & in, InsetTabular & inset)
6362 {
6363         istringstream data(in);
6364         Lexer lex;
6365         lex.setStream(data);
6366
6367         if (in.empty())
6368                 return;
6369
6370         string token;
6371         lex >> token;
6372         if (!lex || token != "tabular") {
6373                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
6374                 return;
6375         }
6376
6377         // This is part of the inset proper that is usually swallowed
6378         // by Buffer::readInset
6379         lex >> token;
6380         if (!lex || token != "Tabular") {
6381                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
6382                 return;
6383         }
6384
6385         inset.read(lex);
6386 }
6387
6388
6389 string InsetTabular::params2string(InsetTabular const & inset)
6390 {
6391         ostringstream data;
6392         data << "tabular" << ' ';
6393         inset.write(data);
6394         data << "\\end_inset\n";
6395         return data.str();
6396 }
6397
6398
6399 } // namespace lyx