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