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