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