]> git.lyx.org Git - lyx.git/blob - src/insets/InsetTabular.cpp
Fix crash when outputting XHTML. Not resetting the paragraphs
[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                 if (!tabularFeatures(cur, to_utf8(cmd.argument())))
4164                         cur.undispatched();
4165                 break;
4166
4167         // insert file functions
4168         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
4169         case LFUN_FILE_INSERT_PLAINTEXT:
4170                 // FIXME UNICODE
4171                 if (FileName::isAbsolute(to_utf8(cmd.argument()))) {
4172                         docstring const tmpstr = cur.bv().contentsOfPlaintextFile(
4173                                 FileName(to_utf8(cmd.argument())));
4174                         if (tmpstr.empty())
4175                                 break;
4176                         cur.recordUndoInset(INSERT_UNDO);
4177                         if (insertPlaintextString(cur.bv(), tmpstr, false)) {
4178                                 // content has been replaced,
4179                                 // so cursor might be invalid
4180                                 cur.pos() = cur.lastpos();
4181                                 cur.pit() = cur.lastpit();
4182                                 bvcur.setCursor(cur);
4183                         } else
4184                                 cur.undispatched();
4185                 }
4186                 break;
4187
4188         case LFUN_CUT:
4189                 if (cur.selIsMultiCell()) {
4190                         if (copySelection(cur)) {
4191                                 cur.recordUndoInset(DELETE_UNDO);
4192                                 cutSelection(cur);
4193                         }
4194                 } else
4195                         cell(cur.idx())->dispatch(cur, cmd);
4196                 break;
4197
4198         case LFUN_SELF_INSERT:
4199                 if (cur.selIsMultiCell()) {
4200                         cur.recordUndoInset(DELETE_UNDO);
4201                         cutSelection(cur);
4202                 }
4203                 cell(cur.idx())->dispatch(cur, cmd);
4204                 break;
4205
4206         case LFUN_CHAR_DELETE_BACKWARD:
4207         case LFUN_CHAR_DELETE_FORWARD:
4208                 if (cur.selIsMultiCell()) {
4209                         cur.recordUndoInset(DELETE_UNDO);
4210                         cutSelection(cur);
4211                 } else
4212                         cell(cur.idx())->dispatch(cur, cmd);
4213                 break;
4214
4215         case LFUN_COPY:
4216                 if (!cur.selection())
4217                         break;
4218                 if (cur.selIsMultiCell()) {
4219                         cur.finishUndo();
4220                         copySelection(cur);
4221                 } else
4222                         cell(cur.idx())->dispatch(cur, cmd);
4223                 break;
4224
4225         case LFUN_CLIPBOARD_PASTE:
4226         case LFUN_PRIMARY_SELECTION_PASTE: {
4227                 docstring const clip = (act == LFUN_CLIPBOARD_PASTE) ?
4228                         theClipboard().getAsText() :
4229                         theSelection().get();
4230                 if (clip.empty())
4231                         break;
4232                 // pass to InsertPlaintextString, but
4233                 // only if we have multi-cell content
4234                 if (clip.find_first_of(from_ascii("\t\n")) != docstring::npos) {
4235                         cur.recordUndoInset(INSERT_UNDO);
4236                         if (insertPlaintextString(cur.bv(), clip, false)) {
4237                                 // content has been replaced,
4238                                 // so cursor might be invalid
4239                                 cur.pos() = cur.lastpos();
4240                                 cur.pit() = cur.lastpit();
4241                                 bvcur.setCursor(cur);
4242                                 break;
4243                         }
4244                 }
4245                 // Let the cell handle normal text
4246                 cell(cur.idx())->dispatch(cur, cmd);
4247                 break;
4248         }
4249
4250         case LFUN_PASTE:
4251                 if (!tabularStackDirty()) {
4252                         if (!cur.selIsMultiCell())
4253                                 cell(cur.idx())->dispatch(cur, cmd);
4254                         break;
4255                 }
4256                 if (theClipboard().isInternal()) {
4257                         cur.recordUndoInset(INSERT_UNDO);
4258                         pasteClipboard(cur);
4259                 }
4260                 break;
4261
4262         case LFUN_FONT_EMPH:
4263         case LFUN_FONT_BOLD:
4264         case LFUN_FONT_BOLDSYMBOL:
4265         case LFUN_FONT_ROMAN:
4266         case LFUN_FONT_NOUN:
4267         case LFUN_FONT_ITAL:
4268         case LFUN_FONT_FRAK:
4269         case LFUN_FONT_TYPEWRITER:
4270         case LFUN_FONT_SANS:
4271         case LFUN_TEXTSTYLE_APPLY:
4272         case LFUN_TEXTSTYLE_UPDATE:
4273         case LFUN_FONT_SIZE:
4274         case LFUN_FONT_UNDERLINE:
4275         case LFUN_FONT_STRIKEOUT:
4276         case LFUN_FONT_UULINE:
4277         case LFUN_FONT_UWAVE:
4278         case LFUN_LANGUAGE:
4279         case LFUN_WORD_CAPITALIZE:
4280         case LFUN_WORD_UPCASE:
4281         case LFUN_WORD_LOWCASE:
4282         case LFUN_CHARS_TRANSPOSE:
4283                 if (cur.selIsMultiCell()) {
4284                         row_type rs, re;
4285                         col_type cs, ce;
4286                         getSelection(cur, rs, re, cs, ce);
4287                         Cursor tmpcur = cur;
4288                         for (row_type r = rs; r <= re; ++r) {
4289                                 for (col_type c = cs; c <= ce; ++c) {
4290                                         // cursor follows cell:
4291                                         tmpcur.idx() = tabular.cellIndex(r, c);
4292                                         // select this cell only:
4293                                         tmpcur.pit() = 0;
4294                                         tmpcur.pos() = 0;
4295                                         tmpcur.resetAnchor();
4296                                         tmpcur.pit() = tmpcur.lastpit();
4297                                         tmpcur.pos() = tmpcur.top().lastpos();
4298                                         tmpcur.setCursor(tmpcur);
4299                                         tmpcur.setSelection();
4300                                         cell(tmpcur.idx())->dispatch(tmpcur, cmd);
4301                                 }
4302                         }
4303                         break;
4304                 } else {
4305                         cell(cur.idx())->dispatch(cur, cmd);
4306                         break;
4307                 }
4308
4309         case LFUN_INSET_SETTINGS:
4310                 // relay this lfun to Inset, not to the cell.
4311                 Inset::doDispatch(cur, cmd);
4312                 break;
4313
4314         default:
4315                 // we try to handle this event in the insets dispatch function.
4316                 cell(cur.idx())->dispatch(cur, cmd);
4317                 break;
4318         }
4319 }
4320
4321
4322 // function sets an object as defined in func_status.h:
4323 // states OK, Unknown, Disabled, On, Off.
4324 bool InsetTabular::getStatus(Cursor & cur, FuncRequest const & cmd,
4325         FuncStatus & status) const
4326 {
4327         switch (cmd.action()) {
4328         case LFUN_INSET_MODIFY: {
4329                 if (&cur.inset() != this || cmd.getArg(0) != "tabular") 
4330                         break;
4331
4332                 // FIXME: We only check for the very first argument...
4333                 string const s = cmd.getArg(1);
4334                 // We always enable the lfun if it is coming from the dialog
4335                 // because the dialog makes sure all the settings are valid,
4336                 // even though the first argument might not be valid now.
4337                 if (s == "from-dialog") {
4338                         status.setEnabled(true);
4339                         return true;
4340                 }
4341
4342                 int action = Tabular::LAST_ACTION;
4343                 int i = 0;
4344                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
4345                         if (tabularFeature[i].feature == s) {
4346                                 action = tabularFeature[i].action;
4347                                 break;
4348                         }
4349                 }
4350                 if (action == Tabular::LAST_ACTION) {
4351                         status.clear();
4352                         status.setUnknown(true);
4353                         return true;
4354                 }
4355
4356                 string const argument = cmd.getLongArg(2);
4357
4358                 row_type sel_row_start = 0;
4359                 row_type sel_row_end = 0;
4360                 col_type sel_col_start = 0;
4361                 col_type sel_col_end = 0;
4362                 Tabular::ltType dummyltt;
4363                 bool flag = true;
4364
4365                 getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
4366
4367                 switch (action) {
4368                 case Tabular::SET_PWIDTH:
4369                 case Tabular::SET_MPWIDTH:
4370                 case Tabular::SET_SPECIAL_COLUMN:
4371                 case Tabular::SET_SPECIAL_MULTICOLUMN:
4372                 case Tabular::APPEND_ROW:
4373                 case Tabular::APPEND_COLUMN:
4374                 case Tabular::DELETE_ROW:
4375                 case Tabular::DELETE_COLUMN:
4376                 case Tabular::COPY_ROW:
4377                 case Tabular::COPY_COLUMN:
4378                 case Tabular::SET_TOP_SPACE:
4379                 case Tabular::SET_BOTTOM_SPACE:
4380                 case Tabular::SET_INTERLINE_SPACE:
4381                         status.clear();
4382                         return true;
4383
4384                 case Tabular::SET_TABULAR_WIDTH:
4385                         status.setEnabled(!tabular.rotate &&  !tabular.is_long_tabular
4386                                 && tabular.tabular_valignment == Tabular::LYX_VALIGN_MIDDLE);
4387                         break;
4388
4389                 case Tabular::SET_DECIMAL_POINT:
4390                         status.setEnabled(
4391                                 tabular.getAlignment(cur.idx()) == LYX_ALIGN_DECIMAL);
4392                         break;
4393
4394                 case Tabular::SET_MULTICOLUMN:
4395                 case Tabular::UNSET_MULTICOLUMN:
4396                 case Tabular::MULTICOLUMN:
4397                         // If a row is set as longtable caption, it must not be allowed
4398                         // to unset that this row is a multicolumn.
4399                         status.setEnabled(sel_row_start == sel_row_end
4400                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4401                         status.setOnOff(tabular.isMultiColumn(cur.idx()));
4402                         break;
4403
4404                 case Tabular::SET_MULTIROW:
4405                 case Tabular::UNSET_MULTIROW:
4406                 case Tabular::MULTIROW:
4407                         // If a row is set as longtable caption, it must not be allowed
4408                         // to unset that this row is a multirow.
4409                         status.setEnabled(sel_col_start == sel_col_end
4410                                 && !tabular.ltCaption(tabular.cellRow(cur.idx())));
4411                         status.setOnOff(tabular.isMultiRow(cur.idx()));
4412                         break;
4413
4414                 case Tabular::SET_ALL_LINES:
4415                 case Tabular::UNSET_ALL_LINES:
4416                 case Tabular::SET_BORDER_LINES:
4417                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4418                         break;
4419
4420                 case Tabular::SET_LINE_TOP:
4421                 case Tabular::SET_LINE_BOTTOM:
4422                 case Tabular::SET_LINE_LEFT:
4423                 case Tabular::SET_LINE_RIGHT:
4424                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4425                         break;
4426
4427                 case Tabular::TOGGLE_LINE_TOP:
4428                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4429                         status.setOnOff(tabular.topLine(cur.idx()));
4430                         break;
4431
4432                 case Tabular::TOGGLE_LINE_BOTTOM:
4433                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4434                         status.setOnOff(tabular.bottomLine(cur.idx()));
4435                         break;
4436
4437                 case Tabular::TOGGLE_LINE_LEFT:
4438                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4439                         status.setOnOff(tabular.leftLine(cur.idx()));
4440                         break;
4441
4442                 case Tabular::TOGGLE_LINE_RIGHT:
4443                         status.setEnabled(!tabular.ltCaption(tabular.cellRow(cur.idx())));
4444                         status.setOnOff(tabular.rightLine(cur.idx()));
4445                         break;
4446
4447                 // multirow cells only inherit the alignment of the column if the column has
4448                 // no width, otherwise they are left-aligned
4449                 // therefore allow always left but right and center only if there is no width
4450                 case Tabular::M_ALIGN_LEFT:
4451                         flag = false;
4452                 case Tabular::ALIGN_LEFT:
4453                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_LEFT);
4454                         break;
4455
4456                 case Tabular::M_ALIGN_RIGHT:
4457                         flag = false;
4458                 case Tabular::ALIGN_RIGHT:
4459                         status.setEnabled(!(tabular.isMultiRow(cur.idx()) 
4460                                 && !tabular.getPWidth(cur.idx()).zero()));
4461                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_RIGHT);
4462                         break;
4463
4464                 case Tabular::M_ALIGN_CENTER:
4465                         flag = false;
4466                 case Tabular::ALIGN_CENTER:
4467                         status.setEnabled(!(tabular.isMultiRow(cur.idx()) 
4468                                 && !tabular.getPWidth(cur.idx()).zero()));
4469                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_CENTER);
4470                         break;
4471
4472                 case Tabular::ALIGN_BLOCK:
4473                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4474                                 && !tabular.isMultiRow(cur.idx()));
4475                         status.setOnOff(tabular.getAlignment(cur.idx(), flag) == LYX_ALIGN_BLOCK);
4476                         break;
4477
4478                 case Tabular::ALIGN_DECIMAL:
4479                         status.setEnabled(!tabular.isMultiRow(cur.idx()) 
4480                                 && !tabular.isMultiColumn(cur.idx()));
4481                         status.setOnOff(tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_DECIMAL);
4482                         break;
4483
4484                 case Tabular::M_VALIGN_TOP:
4485                         flag = false;
4486                 case Tabular::VALIGN_TOP:
4487                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4488                                 && !tabular.isMultiRow(cur.idx()));
4489                         status.setOnOff(
4490                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_TOP);
4491                         break;
4492
4493                 case Tabular::M_VALIGN_BOTTOM:
4494                         flag = false;
4495                 case Tabular::VALIGN_BOTTOM:
4496                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4497                                 && !tabular.isMultiRow(cur.idx()));
4498                         status.setOnOff(
4499                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_BOTTOM);
4500                         break;
4501
4502                 case Tabular::M_VALIGN_MIDDLE:
4503                         flag = false;
4504                 case Tabular::VALIGN_MIDDLE:
4505                         status.setEnabled(!tabular.getPWidth(cur.idx()).zero()
4506                                 && !tabular.isMultiRow(cur.idx()));
4507                         status.setOnOff(
4508                                 tabular.getVAlignment(cur.idx(), flag) == Tabular::LYX_VALIGN_MIDDLE);
4509                         break;
4510
4511                 case Tabular::SET_LONGTABULAR:
4512                         // setting as longtable is not allowed when table is inside a float
4513                         if (cur.innerInsetOfType(FLOAT_CODE) != 0
4514                                 || cur.innerInsetOfType(WRAP_CODE) != 0)
4515                                 status.setEnabled(false);
4516                         else
4517                                 status.setEnabled(true);
4518                         status.setOnOff(tabular.is_long_tabular);
4519                         break;
4520
4521                 case Tabular::UNSET_LONGTABULAR:
4522                         status.setOnOff(!tabular.is_long_tabular);
4523                         break;
4524
4525                 case Tabular::TOGGLE_ROTATE_TABULAR:
4526                 case Tabular::SET_ROTATE_TABULAR:
4527                         status.setEnabled(tabular.tabular_width.zero());
4528                         status.setOnOff(tabular.rotate);
4529                         break;
4530
4531                 case Tabular::TABULAR_VALIGN_TOP:
4532                         status.setEnabled(tabular.tabular_width.zero());
4533                         status.setOnOff(tabular.tabular_valignment 
4534                                 == Tabular::LYX_VALIGN_TOP);
4535                         break;
4536                 case Tabular::TABULAR_VALIGN_MIDDLE:
4537                         status.setEnabled(tabular.tabular_width.zero());
4538                         status.setOnOff(tabular.tabular_valignment 
4539                                 == Tabular::LYX_VALIGN_MIDDLE);
4540                         break;
4541                 case Tabular::TABULAR_VALIGN_BOTTOM:
4542                         status.setEnabled(tabular.tabular_width.zero());
4543                         status.setOnOff(tabular.tabular_valignment 
4544                                 == Tabular::LYX_VALIGN_BOTTOM);
4545                         break;
4546
4547                 case Tabular::LONGTABULAR_ALIGN_LEFT:
4548                         status.setOnOff(tabular.longtabular_alignment 
4549                                 == Tabular::LYX_LONGTABULAR_ALIGN_LEFT);
4550                         break;
4551                 case Tabular::LONGTABULAR_ALIGN_CENTER:
4552                         status.setOnOff(tabular.longtabular_alignment 
4553                                 == Tabular::LYX_LONGTABULAR_ALIGN_CENTER);
4554                         break;
4555                 case Tabular::LONGTABULAR_ALIGN_RIGHT:
4556                         status.setOnOff(tabular.longtabular_alignment 
4557                                 == Tabular::LYX_LONGTABULAR_ALIGN_RIGHT);
4558                         break;
4559
4560                 case Tabular::UNSET_ROTATE_TABULAR:
4561                         status.setOnOff(!tabular.rotate);
4562                         break;
4563
4564                 case Tabular::TOGGLE_ROTATE_CELL:
4565                 case Tabular::SET_ROTATE_CELL:
4566                         status.setOnOff(!oneCellHasRotationState(false,
4567                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4568                         break;
4569
4570                 case Tabular::UNSET_ROTATE_CELL:
4571                         status.setOnOff(!oneCellHasRotationState(true,
4572                                 sel_row_start, sel_row_end, sel_col_start, sel_col_end));
4573                         break;
4574
4575                 case Tabular::SET_USEBOX:
4576                         status.setOnOff(convert<int>(argument) == tabular.getUsebox(cur.idx()));
4577                         break;
4578
4579                 // every row can only be one thing:
4580                 // either a footer or header or caption
4581                 case Tabular::SET_LTFIRSTHEAD:
4582                         status.setEnabled(sel_row_start == sel_row_end
4583                                 && !tabular.ltCaption(sel_row_start));
4584                         status.setOnOff(tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4585                         break;
4586
4587                 case Tabular::UNSET_LTFIRSTHEAD:
4588                         status.setOnOff(!tabular.getRowOfLTFirstHead(sel_row_start, dummyltt));
4589                         break;
4590
4591                 case Tabular::SET_LTHEAD:
4592                         status.setEnabled(sel_row_start == sel_row_end
4593                                 && !tabular.ltCaption(sel_row_start));
4594                         status.setOnOff(tabular.getRowOfLTHead(sel_row_start, dummyltt));
4595                         break;
4596
4597                 case Tabular::UNSET_LTHEAD:
4598                         status.setOnOff(!tabular.getRowOfLTHead(sel_row_start, dummyltt));
4599                         break;
4600
4601                 case Tabular::SET_LTFOOT:
4602                         status.setEnabled(sel_row_start == sel_row_end
4603                                 && !tabular.ltCaption(sel_row_start));
4604                         status.setOnOff(tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4605                         break;
4606
4607                 case Tabular::UNSET_LTFOOT:
4608                         status.setOnOff(!tabular.getRowOfLTFoot(sel_row_start, dummyltt));
4609                         break;
4610
4611                 case Tabular::SET_LTLASTFOOT:
4612                         status.setEnabled(sel_row_start == sel_row_end
4613                                 && !tabular.ltCaption(sel_row_start));
4614                         status.setOnOff(tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4615                         break;
4616
4617                 case Tabular::UNSET_LTLASTFOOT:
4618                         status.setOnOff(!tabular.getRowOfLTLastFoot(sel_row_start, dummyltt));
4619                         break;
4620
4621                 case Tabular::SET_LTNEWPAGE:
4622                         status.setOnOff(tabular.getLTNewPage(sel_row_start));
4623                         break;
4624
4625                 // only one row can be the caption
4626                 // and a multirow cannot be set as caption
4627                 case Tabular::SET_LTCAPTION:
4628                 case Tabular::UNSET_LTCAPTION:
4629                 case Tabular::TOGGLE_LTCAPTION:
4630                         status.setEnabled(sel_row_start == sel_row_end
4631                                 && !tabular.getRowOfLTFirstHead(sel_row_start, dummyltt)
4632                                 && !tabular.getRowOfLTHead(sel_row_start, dummyltt)
4633                                 && !tabular.getRowOfLTFoot(sel_row_start, dummyltt)
4634                                 && !tabular.getRowOfLTLastFoot(sel_row_start, dummyltt)
4635                                 && (!tabular.haveLTCaption()
4636                                         || tabular.ltCaption(sel_row_start))
4637                                 && !tabular.isMultiRow(sel_row_start));
4638                         status.setOnOff(tabular.ltCaption(sel_row_start));
4639                         break;
4640
4641                 case Tabular::SET_BOOKTABS:
4642                         status.setOnOff(tabular.use_booktabs);
4643                         break;
4644
4645                 case Tabular::UNSET_BOOKTABS:
4646                         status.setOnOff(!tabular.use_booktabs);
4647                         break;
4648
4649                 default:
4650                         status.clear();
4651                         status.setEnabled(false);
4652                         break;
4653                 }
4654                 return true;
4655         }
4656
4657         // These are only enabled inside tabular
4658         case LFUN_CELL_BACKWARD:
4659         case LFUN_CELL_FORWARD:
4660                 status.setEnabled(true);
4661                 return true;
4662
4663         // disable these with multiple cells selected
4664         case LFUN_INSET_INSERT:
4665         case LFUN_TABULAR_INSERT:
4666         case LFUN_FLEX_INSERT:
4667         case LFUN_FLOAT_INSERT:
4668         case LFUN_FLOAT_WIDE_INSERT:
4669         case LFUN_FOOTNOTE_INSERT:
4670         case LFUN_MARGINALNOTE_INSERT:
4671         case LFUN_MATH_INSERT:
4672         case LFUN_MATH_MODE:
4673         case LFUN_MATH_MUTATE:
4674         case LFUN_MATH_DISPLAY:
4675         case LFUN_NOTE_INSERT:
4676         case LFUN_ARGUMENT_INSERT:
4677         case LFUN_BOX_INSERT:
4678         case LFUN_BRANCH_INSERT:
4679         case LFUN_PHANTOM_INSERT:
4680         case LFUN_WRAP_INSERT:
4681         case LFUN_PREVIEW_INSERT:
4682         case LFUN_ERT_INSERT: {
4683                 if (cur.selIsMultiCell()) {
4684                         status.setEnabled(false);
4685                         return true;
4686                 } else
4687                         return cell(cur.idx())->getStatus(cur, cmd, status);
4688         }
4689
4690         // disable in non-fixed-width cells
4691         case LFUN_BREAK_PARAGRAPH:
4692                 // multirow does not allow paragraph breaks
4693                 if (tabular.isMultiRow(cur.idx())) {
4694                         status.setEnabled(false);
4695                         return true;
4696                 }
4697         case LFUN_NEWLINE_INSERT: {
4698                 if (tabular.getPWidth(cur.idx()).zero()) {
4699                         status.setEnabled(false);
4700                         return true;
4701                 } else
4702                         return cell(cur.idx())->getStatus(cur, cmd, status);
4703         }
4704
4705         case LFUN_NEWPAGE_INSERT:
4706                 status.setEnabled(false);
4707                 return true;
4708
4709         case LFUN_PASTE:
4710                 if (tabularStackDirty() && theClipboard().isInternal()) {
4711                         if (cur.selIsMultiCell()) {
4712                                 row_type rs, re;
4713                                 col_type cs, ce;
4714                                 getSelection(cur, rs, re, cs, ce);
4715                                 if (paste_tabular && paste_tabular->ncols() == ce - cs + 1
4716                                           && paste_tabular->nrows() == re - rs + 1)
4717                                         status.setEnabled(true);        
4718                                 else {
4719                                         status.setEnabled(false);
4720                                         status.message(_("Selection size should match clipboard content."));
4721                                 }
4722                         } else
4723                                 status.setEnabled(true);
4724                         return true;
4725                 }
4726                 return cell(cur.idx())->getStatus(cur, cmd, status);
4727
4728         case LFUN_INSET_SETTINGS:
4729                 // relay this lfun to Inset, not to the cell.
4730                 return Inset::getStatus(cur, cmd, status);
4731
4732         default:
4733                 // we try to handle this event in the insets dispatch function.
4734                 return cell(cur.idx())->getStatus(cur, cmd, status);
4735         }
4736         return false;
4737 }
4738
4739
4740 Inset::DisplayType InsetTabular::display() const
4741 {
4742                 if (tabular.is_long_tabular) {
4743                         switch (tabular.longtabular_alignment) {
4744                         case Tabular::LYX_LONGTABULAR_ALIGN_LEFT:
4745                                 return AlignLeft;
4746                         case Tabular::LYX_LONGTABULAR_ALIGN_CENTER:
4747                                 return AlignCenter;
4748                         case Tabular::LYX_LONGTABULAR_ALIGN_RIGHT:
4749                                 return AlignRight;
4750                         default:
4751                                 return AlignCenter;
4752                         }
4753                 } else
4754                         return Inline;
4755 }
4756
4757
4758 void InsetTabular::latex(otexstream & os, OutputParams const & runparams) const
4759 {
4760         tabular.latex(os, runparams);
4761 }
4762
4763
4764 int InsetTabular::plaintext(odocstream & os, OutputParams const & runparams) const
4765 {
4766         os << '\n'; // output table on a new line
4767         int const dp = runparams.linelen > 0 ? runparams.depth : 0;
4768         tabular.plaintext(os, runparams, dp, false, 0);
4769         return PLAINTEXT_NEWLINE;
4770 }
4771
4772
4773 int InsetTabular::docbook(odocstream & os, OutputParams const & runparams) const
4774 {
4775         int ret = 0;
4776         Inset * master = 0;
4777
4778         // FIXME: Why not pass a proper DocIterator here?
4779 #if 0
4780         // if the table is inside a float it doesn't need the informaltable
4781         // wrapper. Search for it.
4782         for (master = owner(); master; master = master->owner())
4783                 if (master->lyxCode() == FLOAT_CODE)
4784                         break;
4785 #endif
4786
4787         if (!master) {
4788                 os << "<informaltable>";
4789                 ++ret;
4790         }
4791         ret += tabular.docbook(os, runparams);
4792         if (!master) {
4793                 os << "</informaltable>";
4794                 ++ret;
4795         }
4796         return ret;
4797 }
4798
4799
4800 docstring InsetTabular::xhtml(XHTMLStream & xs, OutputParams const & rp) const
4801 {
4802         return tabular.xhtml(xs, rp);
4803 }
4804
4805
4806 void InsetTabular::validate(LaTeXFeatures & features) const
4807 {
4808         tabular.validate(features);
4809         // FIXME XHTML
4810         // It'd be better to be able to get this from an InsetLayout, but at present
4811         // InsetLayouts do not seem really to work for things that aren't InsetTexts.
4812         if (features.runparams().flavor == OutputParams::HTML)
4813                 features.addPreambleSnippet("<style type=\"text/css\">\n"
4814       "table { border: 1px solid black; display: inline-block; }\n"
4815       "td { border: 1px solid black; padding: 0.5ex; }\n"
4816       "</style>");
4817 }
4818
4819
4820 shared_ptr<InsetTableCell const> InsetTabular::cell(idx_type idx) const
4821 {
4822         return tabular.cellInset(idx);
4823 }
4824
4825
4826 shared_ptr<InsetTableCell> InsetTabular::cell(idx_type idx)
4827 {
4828         return tabular.cellInset(idx);
4829 }
4830
4831
4832 void InsetTabular::cursorPos(BufferView const & bv,
4833                 CursorSlice const & sl, bool boundary, int & x, int & y) const
4834 {
4835         cell(sl.idx())->cursorPos(bv, sl, boundary, x, y);
4836
4837         // y offset     correction
4838         y += cellYPos(sl.idx());
4839         y += tabular.textVOffset(sl.idx());
4840         y += offset_valign_;
4841
4842         // x offset correction
4843         x += cellXPos(sl.idx());
4844         x += tabular.textHOffset(sl.idx());
4845         x += ADD_TO_TABULAR_WIDTH;
4846         x += scx_;
4847 }
4848
4849
4850 int InsetTabular::dist(BufferView & bv, idx_type const cell, int x, int y) const
4851 {
4852         int xx = 0;
4853         int yy = 0;
4854         Inset const & inset = *tabular.cellInset(cell);
4855         Point o = bv.coordCache().getInsets().xy(&inset);
4856         int const xbeg = o.x_ - tabular.textHOffset(cell);
4857         int const xend = xbeg + tabular.cellWidth(cell);
4858         row_type const row = tabular.cellRow(cell);
4859         int const ybeg = o.y_ - tabular.rowAscent(row)
4860                 - tabular.interRowSpace(row);
4861         int const yend = ybeg + tabular.cellHeight(cell);
4862
4863         if (x < xbeg)
4864                 xx = xbeg - x;
4865         else if (x > xend)
4866                 xx = x - xend;
4867
4868         if (y < ybeg)
4869                 yy = ybeg - y;
4870         else if (y > yend)
4871                 yy = y - yend;
4872
4873         //lyxerr << " xbeg=" << xbeg << "  xend=" << xend
4874         //       << " ybeg=" << ybeg << " yend=" << yend
4875         //       << " xx=" << xx << " yy=" << yy
4876         //       << " dist=" << xx + yy << endl;
4877         return xx + yy;
4878 }
4879
4880
4881 Inset * InsetTabular::editXY(Cursor & cur, int x, int y)
4882 {
4883         //lyxerr << "InsetTabular::editXY: " << this << endl;
4884         cur.setSelection(false);
4885         cur.push(*this);
4886         cur.idx() = getNearestCell(cur.bv(), x, y);
4887         resetPos(cur);
4888         return cur.bv().textMetrics(&cell(cur.idx())->text()).editXY(cur, x, y);
4889 }
4890
4891
4892 void InsetTabular::setCursorFromCoordinates(Cursor & cur, int x, int y) const
4893 {
4894         cur.idx() = getNearestCell(cur.bv(), x, y);
4895         cur.bv().textMetrics(&cell(cur.idx())->text()).setCursorFromCoordinates(cur, x, y);
4896 }
4897
4898
4899 InsetTabular::idx_type InsetTabular::getNearestCell(BufferView & bv, int x, int y) const
4900 {
4901         idx_type idx_min = 0;
4902         int dist_min = numeric_limits<int>::max();
4903         for (idx_type i = 0, n = nargs(); i != n; ++i) {
4904                 if (bv.coordCache().getInsets().has(tabular.cellInset(i).get())) {
4905                         int const d = dist(bv, i, x, y);
4906                         if (d < dist_min) {
4907                                 dist_min = d;
4908                                 idx_min = i;
4909                         }
4910                 }
4911         }
4912         return idx_min;
4913 }
4914
4915
4916 int InsetTabular::cellYPos(idx_type const cell) const
4917 {
4918         row_type row = tabular.cellRow(cell);
4919         int ly = 0;
4920         for (row_type r = 0; r < row; ++r)
4921                 ly += tabular.rowDescent(r) + tabular.rowAscent(r + 1) 
4922                         + tabular.interRowSpace(r + 1);
4923         return ly;
4924 }
4925
4926
4927 int InsetTabular::cellXPos(idx_type const cell) const
4928 {
4929         col_type col = tabular.cellColumn(cell);
4930         int lx = 0;
4931         for (col_type c = 0; c < col; ++c)
4932                 lx += tabular.column_info[c].width;
4933         return lx;
4934 }
4935
4936
4937 void InsetTabular::resetPos(Cursor & cur) const
4938 {
4939         BufferView & bv = cur.bv();
4940         int const maxwidth = bv.workWidth();
4941
4942         int const scx_old = scx_;
4943         int const i = cur.find(this);
4944         if (i == -1) {
4945                 scx_ = 0;
4946         } else {
4947                 int const X1 = 0;
4948                 int const X2 = maxwidth;
4949                 int const offset = ADD_TO_TABULAR_WIDTH + 2;
4950                 int const x1 = xo(cur.bv()) + cellXPos(cur[i].idx()) + offset;
4951                 int const x2 = x1 + tabular.cellWidth(cur[i].idx());
4952
4953                 if (x1 < X1)
4954                         scx_ = X1 + 20 - x1;
4955                 else if (x2 > X2)
4956                         scx_ = X2 - 20 - x2;
4957                 else
4958                         scx_ = 0;
4959         }
4960
4961         // only update if offset changed
4962         if (scx_ != scx_old)
4963                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
4964 }
4965
4966
4967 void InsetTabular::moveNextCell(Cursor & cur, EntryDirection entry_from)
4968 {
4969         row_type const row = tabular.cellRow(cur.idx());
4970         col_type const col = tabular.cellColumn(cur.idx());
4971
4972         if (isRightToLeft(cur)) {
4973                 if (tabular.cellColumn(cur.idx()) == 0) {
4974                         if (row == tabular.nrows() - 1)
4975                                 return;
4976                         cur.idx() = tabular.cellBelow(tabular.getLastCellInRow(row));
4977                 } else {
4978                         if (cur.idx() == 0)
4979                                 return;
4980                         if (col == 0)
4981                                 cur.idx() = tabular.getLastCellInRow(row - 1);
4982                         else
4983                                 cur.idx() = tabular.cellIndex(row, col - 1);
4984                 }
4985         } else {
4986                 if (tabular.isLastCell(cur.idx()))
4987                         return;
4988                 if (cur.idx() == tabular.getLastCellInRow(row))
4989                         cur.idx() = tabular.cellIndex(row + 1, 0);
4990                 else {
4991                         col_type const colnextcell = col + tabular.columnSpan(cur.idx());
4992                         cur.idx() = tabular.cellIndex(row, colnextcell);
4993                 }
4994         }
4995
4996         cur.boundary(false);
4997
4998         if (cur.selIsMultiCell()) {
4999                 cur.pit() = cur.lastpit();
5000                 cur.pos() = cur.lastpos();
5001                 resetPos(cur);
5002                 return;
5003         }
5004
5005         cur.pit() = 0;
5006         cur.pos() = 0;
5007
5008         // in visual mode, place cursor at extreme left or right
5009         
5010         switch(entry_from) {
5011
5012         case ENTRY_DIRECTION_RIGHT:
5013                 cur.posVisToRowExtremity(false /* !left */);
5014                 break;
5015         case ENTRY_DIRECTION_LEFT:
5016                 cur.posVisToRowExtremity(true /* left */);
5017                 break;
5018         case ENTRY_DIRECTION_IGNORE:
5019                 // nothing to do in this case
5020                 break;
5021
5022         }
5023         cur.setCurrentFont();
5024         resetPos(cur);
5025 }
5026
5027
5028 void InsetTabular::movePrevCell(Cursor & cur, EntryDirection entry_from)
5029 {
5030         row_type const row = tabular.cellRow(cur.idx());
5031         col_type const col = tabular.cellColumn(cur.idx());
5032
5033         if (isRightToLeft(cur)) {
5034                 if (cur.idx() == tabular.getLastCellInRow(row)) {
5035                         if (row == 0)
5036                                 return;
5037                         cur.idx() = tabular.getFirstCellInRow(row);
5038                         cur.idx() = tabular.cellAbove(cur.idx());
5039                 } else {
5040                         if (tabular.isLastCell(cur.idx()))
5041                                 return;
5042                         if (cur.idx() == tabular.getLastCellInRow(row))
5043                                 cur.idx() = tabular.cellIndex(row + 1, 0);
5044                         else
5045                                 cur.idx() = tabular.cellIndex(row, col + 1);
5046                 }
5047         } else {
5048                 if (cur.idx() == 0) // first cell
5049                         return;
5050                 if (col == 0)
5051                         cur.idx() = tabular.getLastCellInRow(row - 1);
5052                 else
5053                         cur.idx() = tabular.cellIndex(row, col - 1);
5054         }
5055
5056         if (cur.selIsMultiCell()) {
5057                 cur.pit() = cur.lastpit();
5058                 cur.pos() = cur.lastpos();
5059                 resetPos(cur);
5060                 return;
5061         }
5062
5063         cur.pit() = cur.lastpit();
5064         cur.pos() = cur.lastpos();
5065
5066         // in visual mode, place cursor at extreme left or right
5067         
5068         switch(entry_from) {
5069
5070         case ENTRY_DIRECTION_RIGHT:
5071                 cur.posVisToRowExtremity(false /* !left */);
5072                 break;
5073         case ENTRY_DIRECTION_LEFT:
5074                 cur.posVisToRowExtremity(true /* left */);
5075                 break;
5076         case ENTRY_DIRECTION_IGNORE:
5077                 // nothing to do in this case
5078                 break;
5079
5080         }
5081         cur.setCurrentFont();
5082         resetPos(cur);
5083 }
5084
5085
5086 bool InsetTabular::tabularFeatures(Cursor & cur, string const & argument)
5087 {
5088         istringstream is(argument);
5089         string s;
5090         is >> s;
5091         if (insetCode(s) != TABULAR_CODE)
5092                 return false;
5093
5094         // Safe guard.
5095         size_t safe_guard = 0;
5096         for (;;) {
5097                 if (is.eof())
5098                         break;
5099                 safe_guard++;
5100                 if (safe_guard > 1000) {
5101                         LYXERR0("parameter max count reached!");
5102                         break;
5103                 }
5104                 is >> s;
5105                 Tabular::Feature action = Tabular::LAST_ACTION;
5106
5107                 size_t i = 0;
5108                 for (; tabularFeature[i].action != Tabular::LAST_ACTION; ++i) {
5109                         if (s != tabularFeature[i].feature)
5110                                 continue;
5111
5112                         action = tabularFeature[i].action;
5113                         break;
5114                 }
5115                 if (action == Tabular::LAST_ACTION) {
5116                         LYXERR0("Feature not found " << s);
5117                         continue;
5118                 }
5119                 string val;
5120                 if (tabularFeature[i].need_value)
5121                         is >> val;
5122                 LYXERR(Debug::DEBUG, "Feature: " << s << "\t\tvalue: " << val);
5123                 tabularFeatures(cur, action, val);
5124         }
5125         return true;
5126 }
5127
5128
5129 static void checkLongtableSpecial(Tabular::ltType & ltt,
5130                           string const & special, bool & flag)
5131 {
5132         if (special == "dl_above") {
5133                 ltt.topDL = flag;
5134                 ltt.set = false;
5135         } else if (special == "dl_below") {
5136                 ltt.bottomDL = flag;
5137                 ltt.set = false;
5138         } else if (special == "empty") {
5139                 ltt.empty = flag;
5140                 ltt.set = false;
5141         } else if (flag) {
5142                 ltt.empty = false;
5143                 ltt.set = true;
5144         }
5145 }
5146
5147
5148 bool InsetTabular::oneCellHasRotationState(bool rotated,
5149                 row_type row_start, row_type row_end,
5150                 col_type col_start, col_type col_end) const 
5151 {
5152         for (row_type r = row_start; r <= row_end; ++r)
5153                 for (col_type c = col_start; c <= col_end; ++c)
5154                         if (tabular.getRotateCell(tabular.cellIndex(r, c)) == rotated)
5155                                 return true;
5156
5157         return false;
5158 }
5159
5160 void InsetTabular::tabularFeatures(Cursor & cur,
5161         Tabular::Feature feature, string const & value)
5162 {
5163         col_type sel_col_start;
5164         col_type sel_col_end;
5165         row_type sel_row_start;
5166         row_type sel_row_end;
5167         bool setLines = false;
5168         LyXAlignment setAlign = LYX_ALIGN_LEFT;
5169         Tabular::VAlignment setVAlign = Tabular::LYX_VALIGN_TOP;
5170
5171         switch (feature) {
5172
5173         case Tabular::M_ALIGN_LEFT:
5174         case Tabular::ALIGN_LEFT:
5175                 setAlign = LYX_ALIGN_LEFT;
5176                 break;
5177
5178         case Tabular::M_ALIGN_RIGHT:
5179         case Tabular::ALIGN_RIGHT:
5180                 setAlign = LYX_ALIGN_RIGHT;
5181                 break;
5182
5183         case Tabular::M_ALIGN_CENTER:
5184         case Tabular::ALIGN_CENTER:
5185                 setAlign = LYX_ALIGN_CENTER;
5186                 break;
5187
5188         case Tabular::ALIGN_BLOCK:
5189                 setAlign = LYX_ALIGN_BLOCK;
5190                 break;
5191
5192         case Tabular::ALIGN_DECIMAL:
5193                 setAlign = LYX_ALIGN_DECIMAL;
5194                 break;
5195
5196         case Tabular::M_VALIGN_TOP:
5197         case Tabular::VALIGN_TOP:
5198                 setVAlign = Tabular::LYX_VALIGN_TOP;
5199                 break;
5200
5201         case Tabular::M_VALIGN_BOTTOM:
5202         case Tabular::VALIGN_BOTTOM:
5203                 setVAlign = Tabular::LYX_VALIGN_BOTTOM;
5204                 break;
5205
5206         case Tabular::M_VALIGN_MIDDLE:
5207         case Tabular::VALIGN_MIDDLE:
5208                 setVAlign = Tabular::LYX_VALIGN_MIDDLE;
5209                 break;
5210
5211         default:
5212                 break;
5213         }
5214
5215         cur.recordUndoInset(ATOMIC_UNDO, this);
5216
5217         getSelection(cur, sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5218         row_type const row = tabular.cellRow(cur.idx());
5219         col_type const column = tabular.cellColumn(cur.idx());
5220         bool flag = true;
5221         Tabular::ltType ltt;
5222
5223         switch (feature) {
5224
5225         case Tabular::SET_TABULAR_WIDTH:
5226                 tabular.setTabularWidth(Length(value));
5227                 break;
5228
5229         case Tabular::SET_PWIDTH: {
5230                 Length const len(value);
5231                 tabular.setColumnPWidth(cur, cur.idx(), len);
5232                 if (len.zero()
5233                     && tabular.getAlignment(cur.idx(), true) == LYX_ALIGN_BLOCK)
5234                         tabularFeatures(cur, Tabular::ALIGN_CENTER, string());
5235                 break;
5236         }
5237
5238         case Tabular::SET_MPWIDTH:
5239                 tabular.setMColumnPWidth(cur, cur.idx(), Length(value));
5240                 break;
5241
5242         case Tabular::SET_MROFFSET:
5243                 tabular.setMROffset(cur, cur.idx(), Length(value));
5244                 break;
5245
5246         case Tabular::SET_SPECIAL_COLUMN:
5247         case Tabular::SET_SPECIAL_MULTICOLUMN:
5248                 if (value == "none")
5249                         tabular.setAlignSpecial(cur.idx(), docstring(), feature);
5250                 else
5251                         tabular.setAlignSpecial(cur.idx(), from_utf8(value), feature);
5252                 break;
5253
5254         case Tabular::APPEND_ROW:
5255                 // append the row into the tabular
5256                 tabular.appendRow(cur.idx());
5257                 break;
5258
5259         case Tabular::APPEND_COLUMN:
5260                 // append the column into the tabular
5261                 tabular.appendColumn(cur.idx());
5262                 cur.idx() = tabular.cellIndex(row, column);
5263                 break;
5264
5265         case Tabular::DELETE_ROW:
5266                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5267                         tabular.deleteRow(sel_row_start);
5268                 if (sel_row_start >= tabular.nrows())
5269                         --sel_row_start;
5270                 cur.idx() = tabular.cellIndex(sel_row_start, column);
5271                 cur.pit() = 0;
5272                 cur.pos() = 0;
5273                 cur.setSelection(false);
5274                 break;
5275
5276         case Tabular::DELETE_COLUMN:
5277                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5278                         tabular.deleteColumn(sel_col_start);
5279                 if (sel_col_start >= tabular.ncols())
5280                         --sel_col_start;
5281                 cur.idx() = tabular.cellIndex(row, sel_col_start);
5282                 cur.pit() = 0;
5283                 cur.pos() = 0;
5284                 cur.setSelection(false);
5285                 break;
5286
5287         case Tabular::COPY_ROW:
5288                 tabular.copyRow(row);
5289                 break;
5290
5291         case Tabular::COPY_COLUMN:
5292                 tabular.copyColumn(column);
5293                 cur.idx() = tabular.cellIndex(row, column);
5294                 break;
5295
5296         case Tabular::SET_LINE_TOP:
5297         case Tabular::TOGGLE_LINE_TOP: {
5298                 bool lineSet = (feature == Tabular::SET_LINE_TOP)
5299                                ? (value == "true") : !tabular.topLine(cur.idx());
5300                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5301                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5302                                 tabular.setTopLine(tabular.cellIndex(r, c), lineSet);
5303                 break;
5304         }
5305
5306         case Tabular::SET_LINE_BOTTOM:
5307         case Tabular::TOGGLE_LINE_BOTTOM: {
5308                 bool lineSet = (feature == Tabular::SET_LINE_BOTTOM)
5309                                ? (value == "true") : !tabular.bottomLine(cur.idx());
5310                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5311                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5312                                 tabular.setBottomLine(tabular.cellIndex(r, c), lineSet);
5313                 break;
5314         }
5315
5316         case Tabular::SET_LINE_LEFT:
5317         case Tabular::TOGGLE_LINE_LEFT: {
5318                 bool lineSet = (feature == Tabular::SET_LINE_LEFT)
5319                                ? (value == "true") : !tabular.leftLine(cur.idx());
5320                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5321                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5322                                 tabular.setLeftLine(tabular.cellIndex(r, c), lineSet);
5323                 break;
5324         }
5325
5326         case Tabular::SET_LINE_RIGHT:
5327         case Tabular::TOGGLE_LINE_RIGHT: {
5328                 bool lineSet = (feature == Tabular::SET_LINE_RIGHT)
5329                                ? (value == "true") : !tabular.rightLine(cur.idx());
5330                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5331                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5332                                 tabular.setRightLine(tabular.cellIndex(r, c), lineSet);
5333                 break;
5334         }
5335
5336         case Tabular::M_ALIGN_LEFT:
5337         case Tabular::M_ALIGN_RIGHT:
5338         case Tabular::M_ALIGN_CENTER:
5339         case Tabular::ALIGN_LEFT:
5340         case Tabular::ALIGN_RIGHT:
5341         case Tabular::ALIGN_CENTER:
5342         case Tabular::ALIGN_BLOCK:
5343         case Tabular::ALIGN_DECIMAL:
5344                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5345                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5346                                 tabular.setAlignment(tabular.cellIndex(r, c), setAlign,
5347                                 !tabular.getPWidth(c).zero());
5348                 break;
5349
5350         case Tabular::M_VALIGN_TOP:
5351         case Tabular::M_VALIGN_BOTTOM:
5352         case Tabular::M_VALIGN_MIDDLE:
5353                 flag = false;
5354         case Tabular::VALIGN_TOP:
5355         case Tabular::VALIGN_BOTTOM:
5356         case Tabular::VALIGN_MIDDLE:
5357                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5358                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5359                                 tabular.setVAlignment(tabular.cellIndex(r, c), setVAlign, flag);
5360                 break;
5361
5362         case Tabular::SET_MULTICOLUMN: {
5363                 if (!cur.selection()) {
5364                         // just multicol for one single cell
5365                         // check whether we are completely in a multicol
5366                         if (!tabular.isMultiColumn(cur.idx()))
5367                                 tabular.setMultiColumn(cur.idx(), 1,
5368                                         tabular.rightLine(cur.idx()));
5369                         break;
5370                 }
5371                 // we have a selection so this means we just add all this
5372                 // cells to form a multicolumn cell
5373                 idx_type const s_start = cur.selBegin().idx();
5374                 row_type const col_start = tabular.cellColumn(s_start);
5375                 row_type const col_end = tabular.cellColumn(cur.selEnd().idx());
5376                 cur.idx() = tabular.setMultiColumn(s_start, col_end - col_start + 1,
5377                                                    tabular.rightLine(cur.selEnd().idx()));
5378                 cur.pit() = 0;
5379                 cur.pos() = 0;
5380                 cur.setSelection(false);
5381                 break;
5382         }
5383
5384         case Tabular::UNSET_MULTICOLUMN: {
5385                 if (!cur.selection()) {
5386                         if (tabular.isMultiColumn(cur.idx()))
5387                                 tabular.unsetMultiColumn(cur.idx());
5388                 }
5389                 break;
5390         }
5391
5392         case Tabular::MULTICOLUMN: {
5393                 if (!cur.selection()) {
5394                         if (tabular.isMultiColumn(cur.idx()))
5395                                 tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5396                         else
5397                                 tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5398                         break;
5399                 }
5400                 bool merge = false;
5401                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5402                         row_type const r = sel_row_start;
5403                         if (!tabular.isMultiColumn(tabular.cellIndex(r, c))
5404                             || (r > sel_row_start && !tabular.isPartOfMultiColumn(r, c)))
5405                                 merge = true;
5406                 }
5407                 // If the selection contains at least one singlecol cell
5408                 // or multiple multicol cells,
5409                 // we assume the user will merge is to a single multicol
5410                 if (merge)
5411                         tabularFeatures(cur, Tabular::SET_MULTICOLUMN);
5412                 else
5413                         tabularFeatures(cur, Tabular::UNSET_MULTICOLUMN);
5414                 break;
5415         }
5416
5417         case Tabular::SET_MULTIROW: {
5418                 if (!cur.selection()) {
5419                         // just multirow for one single cell
5420                         // check whether we are completely in a multirow
5421                         if (!tabular.isMultiRow(cur.idx()))
5422                                 tabular.setMultiRow(cur.idx(), 1,
5423                                                     tabular.bottomLine(cur.idx()));
5424                         break;
5425                 }
5426                 // we have a selection so this means we just add all this
5427                 // cells to form a multirow cell
5428                 idx_type const s_start = cur.selBegin().idx();
5429                 row_type const row_start = tabular.cellRow(s_start);
5430                 row_type const row_end = tabular.cellRow(cur.selEnd().idx());
5431                 cur.idx() = tabular.setMultiRow(s_start, row_end - row_start + 1,
5432                                                 tabular.bottomLine(cur.selEnd().idx()));
5433                 cur.pit() = 0;
5434                 cur.pos() = 0;
5435                 cur.setSelection(false);
5436                 break;
5437         }
5438
5439         case Tabular::UNSET_MULTIROW: {
5440                 if (!cur.selection()) {
5441                         if (tabular.isMultiRow(cur.idx()))
5442                                 tabular.unsetMultiRow(cur.idx());
5443                 }
5444                 break;
5445         }
5446
5447         case Tabular::MULTIROW: {
5448                 if (!cur.selection()) {
5449                         if (tabular.isMultiRow(cur.idx()))
5450                                 tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5451                         else
5452                                 tabularFeatures(cur, Tabular::SET_MULTIROW);
5453                         break;
5454                 }
5455                 bool merge = false;
5456                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5457                         col_type const c = sel_col_start;
5458                         if (!tabular.isMultiRow(tabular.cellIndex(r, c))
5459                             || (r > sel_row_start && !tabular.isPartOfMultiRow(r, c)))
5460                                 merge = true;
5461                 }
5462                 // If the selection contains at least one singlerow cell
5463                 // or multiple multirow cells,
5464                 // we assume the user will merge is to a single multirow
5465                 if (merge)
5466                         tabularFeatures(cur, Tabular::SET_MULTIROW);
5467                 else
5468                         tabularFeatures(cur, Tabular::UNSET_MULTIROW);
5469                 break;
5470         }
5471
5472         case Tabular::SET_ALL_LINES:
5473                 setLines = true;
5474         case Tabular::UNSET_ALL_LINES:
5475                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5476                         for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5477                                 idx_type const cell = tabular.cellIndex(r, c);
5478                                 tabular.setTopLine(cell, setLines);
5479                                 tabular.setBottomLine(cell, setLines);
5480                                 tabular.setRightLine(cell, setLines);
5481                                 tabular.setLeftLine(cell, setLines);
5482                         }
5483                 break;
5484
5485         case Tabular::SET_BORDER_LINES:
5486                 for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5487                         tabular.setLeftLine(tabular.cellIndex(r, sel_col_start), true);
5488                         tabular.setRightLine(tabular.cellIndex(r, sel_col_end), true);
5489                 }
5490                 for (col_type c = sel_col_start; c <= sel_col_end; ++c) {
5491                         tabular.setTopLine(tabular.cellIndex(sel_row_start, c), true);
5492                         tabular.setBottomLine(tabular.cellIndex(sel_row_end, c), true);
5493                 }
5494                 break;
5495
5496         case Tabular::SET_LONGTABULAR:
5497                 tabular.is_long_tabular = true;
5498                 break;
5499
5500         case Tabular::UNSET_LONGTABULAR:
5501                 for (row_type r = 0; r < tabular.nrows(); ++r) {
5502                         if (tabular.ltCaption(r)) {
5503                                 cur.idx() = tabular.cellIndex(r, 0);
5504                                 cur.pit() = 0;
5505                                 cur.pos() = 0;
5506                                 tabularFeatures(cur, Tabular::TOGGLE_LTCAPTION);
5507                         }
5508                 }
5509                 tabular.is_long_tabular = false;
5510                 break;
5511
5512         case Tabular::SET_ROTATE_TABULAR:
5513                 tabular.rotate = true;
5514                 break;
5515
5516         case Tabular::UNSET_ROTATE_TABULAR:
5517                 tabular.rotate = false;
5518                 break;
5519
5520         case Tabular::TOGGLE_ROTATE_TABULAR:
5521                 tabular.rotate = !tabular.rotate;
5522                 break;
5523
5524         case Tabular::TABULAR_VALIGN_TOP:
5525                 tabular.tabular_valignment = Tabular::LYX_VALIGN_TOP;
5526                 break;
5527
5528         case Tabular::TABULAR_VALIGN_MIDDLE:
5529                 tabular.tabular_valignment = Tabular::LYX_VALIGN_MIDDLE;
5530                 break;
5531
5532         case Tabular::TABULAR_VALIGN_BOTTOM:
5533                 tabular.tabular_valignment = Tabular::LYX_VALIGN_BOTTOM;
5534                 break;
5535
5536         case Tabular::LONGTABULAR_ALIGN_LEFT:
5537                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_LEFT;
5538                 break;
5539
5540         case Tabular::LONGTABULAR_ALIGN_CENTER:
5541                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_CENTER;
5542                 break;
5543
5544         case Tabular::LONGTABULAR_ALIGN_RIGHT:
5545                 tabular.longtabular_alignment = Tabular::LYX_LONGTABULAR_ALIGN_RIGHT;
5546                 break;
5547
5548                 
5549
5550         case Tabular::SET_ROTATE_CELL:
5551                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5552                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5553                                 tabular.setRotateCell(tabular.cellIndex(r, c), true);
5554                 break;
5555
5556         case Tabular::UNSET_ROTATE_CELL:
5557                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5558                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5559                                 tabular.setRotateCell(tabular.cellIndex(r, c), false);
5560                 break;
5561
5562         case Tabular::TOGGLE_ROTATE_CELL:
5563                 {
5564                 bool oneNotRotated = oneCellHasRotationState(false,
5565                         sel_row_start, sel_row_end, sel_col_start, sel_col_end);
5566
5567                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5568                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5569                                 tabular.setRotateCell(tabular.cellIndex(r, c),
5570                                                                           oneNotRotated);
5571                 }
5572                 break;
5573
5574         case Tabular::SET_USEBOX: {
5575                 Tabular::BoxType val = Tabular::BoxType(convert<int>(value));
5576                 if (val == tabular.getUsebox(cur.idx()))
5577                         val = Tabular::BOX_NONE;
5578                 for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5579                         for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5580                                 tabular.setUsebox(tabular.cellIndex(r, c), val);
5581                 break;
5582         }
5583
5584         case Tabular::UNSET_LTFIRSTHEAD:
5585                 flag = false;
5586         case Tabular::SET_LTFIRSTHEAD:
5587                 tabular.getRowOfLTFirstHead(row, ltt);
5588                 checkLongtableSpecial(ltt, value, flag);
5589                 tabular.setLTHead(row, flag, ltt, true);
5590                 break;
5591
5592         case Tabular::UNSET_LTHEAD:
5593                 flag = false;
5594         case Tabular::SET_LTHEAD:
5595                 tabular.getRowOfLTHead(row, ltt);
5596                 checkLongtableSpecial(ltt, value, flag);
5597                 tabular.setLTHead(row, flag, ltt, false);
5598                 break;
5599
5600         case Tabular::UNSET_LTFOOT:
5601                 flag = false;
5602         case Tabular::SET_LTFOOT:
5603                 tabular.getRowOfLTFoot(row, ltt);
5604                 checkLongtableSpecial(ltt, value, flag);
5605                 tabular.setLTFoot(row, flag, ltt, false);
5606                 break;
5607
5608         case Tabular::UNSET_LTLASTFOOT:
5609                 flag = false;
5610         case Tabular::SET_LTLASTFOOT:
5611                 tabular.getRowOfLTLastFoot(row, ltt);
5612                 checkLongtableSpecial(ltt, value, flag);
5613                 tabular.setLTFoot(row, flag, ltt, true);
5614                 break;
5615
5616         case Tabular::SET_LTNEWPAGE:
5617                 tabular.setLTNewPage(row, !tabular.getLTNewPage(row));
5618                 break;
5619
5620         case Tabular::SET_LTCAPTION: {
5621                 if (tabular.ltCaption(row))
5622                         break;
5623                 cur.idx() = tabular.setLTCaption(row, true);
5624                 cur.pit() = 0;
5625                 cur.pos() = 0;
5626                 cur.setSelection(false);
5627                 // If a row is set as caption, then also insert
5628                 // a caption. Otherwise the LaTeX output is broken.
5629                 lyx::dispatch(FuncRequest(LFUN_INSET_SELECT_ALL));
5630                 lyx::dispatch(FuncRequest(LFUN_CAPTION_INSERT));
5631                 break;
5632         }
5633         
5634         case Tabular::UNSET_LTCAPTION: {
5635                 if (!tabular.ltCaption(row))
5636                         break;
5637                 cur.idx() = tabular.setLTCaption(row, false);
5638                 cur.pit() = 0;
5639                 cur.pos() = 0;
5640                 cur.setSelection(false);
5641                 FuncRequest fr(LFUN_INSET_DISSOLVE, "caption");
5642                 if (lyx::getStatus(fr).enabled())
5643                         lyx::dispatch(fr);
5644                 break;
5645         }
5646
5647         case Tabular::TOGGLE_LTCAPTION: {
5648                 if (tabular.ltCaption(row))
5649                         tabularFeatures(cur, Tabular::UNSET_LTCAPTION);
5650                 else
5651                         tabularFeatures(cur, Tabular::SET_LTCAPTION);
5652                 break;
5653         }
5654
5655         case Tabular::SET_BOOKTABS:
5656                 tabular.use_booktabs = true;
5657                 break;
5658
5659         case Tabular::UNSET_BOOKTABS:
5660                 tabular.use_booktabs = false;
5661                 break;
5662
5663         case Tabular::SET_TOP_SPACE: {
5664                 Length len;
5665                 if (value == "default")
5666                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5667                                 tabular.row_info[r].top_space_default = true;
5668                 else if (value == "none")
5669                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5670                                 tabular.row_info[r].top_space_default = false;
5671                                 tabular.row_info[r].top_space = len;
5672                         }
5673                 else if (isValidLength(value, &len))
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                 break;
5679         }
5680
5681         case Tabular::SET_BOTTOM_SPACE: {
5682                 Length len;
5683                 if (value == "default")
5684                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5685                                 tabular.row_info[r].bottom_space_default = true;
5686                 else if (value == "none")
5687                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5688                                 tabular.row_info[r].bottom_space_default = false;
5689                                 tabular.row_info[r].bottom_space = len;
5690                         }
5691                 else if (isValidLength(value, &len))
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                 break;
5697         }
5698
5699         case Tabular::SET_INTERLINE_SPACE: {
5700                 Length len;
5701                 if (value == "default")
5702                         for (row_type r = sel_row_start; r <= sel_row_end; ++r)
5703                                 tabular.row_info[r].interline_space_default = true;
5704                 else if (value == "none")
5705                         for (row_type r = sel_row_start; r <= sel_row_end; ++r) {
5706                                 tabular.row_info[r].interline_space_default = false;
5707                                 tabular.row_info[r].interline_space = len;
5708                         }
5709                 else if (isValidLength(value, &len))
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                 break;
5715         }
5716
5717         case Tabular::SET_DECIMAL_POINT:
5718                 for (col_type c = sel_col_start; c <= sel_col_end; ++c)
5719                         tabular.column_info[c].decimal_point = from_utf8(value);
5720                 break;
5721
5722         // dummy stuff just to avoid warnings
5723         case Tabular::LAST_ACTION:
5724                 break;
5725         }
5726 }
5727
5728
5729 bool InsetTabular::copySelection(Cursor & cur)
5730 {
5731         if (!cur.selection())
5732                 return false;
5733
5734         row_type rs, re;
5735         col_type cs, ce;
5736         getSelection(cur, rs, re, cs, ce);
5737
5738         paste_tabular.reset(new Tabular(tabular));
5739
5740         for (row_type r = 0; r < rs; ++r)
5741                 paste_tabular->deleteRow(0);
5742
5743         row_type const rows = re - rs + 1;
5744         while (paste_tabular->nrows() > rows)
5745                 paste_tabular->deleteRow(rows);
5746
5747         for (col_type c = 0; c < cs; ++c)
5748                 paste_tabular->deleteColumn(0);
5749
5750         col_type const columns = ce - cs + 1;
5751         while (paste_tabular->ncols() > columns)
5752                 paste_tabular->deleteColumn(columns);
5753
5754         paste_tabular->setBuffer(tabular.buffer());
5755
5756         odocstringstream os;
5757         OutputParams const runparams(0);
5758         paste_tabular->plaintext(os, runparams, 0, true, '\t');
5759         // Needed for the "Edit->Paste recent" menu and the system clipboard.
5760         cap::copySelection(cur, os.str());
5761
5762         // mark tabular stack dirty
5763         // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
5764         // when we (hopefully) have a one-for-all paste mechanism.
5765         // This must be called after cap::copySelection.
5766         dirtyTabularStack(true);
5767
5768         return true;
5769 }
5770
5771
5772 bool InsetTabular::pasteClipboard(Cursor & cur)
5773 {
5774         if (!paste_tabular)
5775                 return false;
5776         col_type actcol = tabular.cellColumn(cur.idx());
5777         row_type actrow = tabular.cellRow(cur.idx());
5778
5779         if (cur.selIsMultiCell()) {
5780                 row_type re;
5781                 col_type ce;
5782                 getSelection(cur, actrow, re, actcol, ce);
5783         }
5784
5785         for (row_type r1 = 0, r2 = actrow;
5786              r1 < paste_tabular->nrows() && r2 < tabular.nrows();
5787              ++r1, ++r2) {
5788                 for (col_type c1 = 0, c2 = actcol;
5789                     c1 < paste_tabular->ncols() && c2 < tabular.ncols();
5790                     ++c1, ++c2) {
5791                         if (paste_tabular->isPartOfMultiColumn(r1, c1) &&
5792                               tabular.isPartOfMultiColumn(r2, c2))
5793                                 continue;
5794                         if (paste_tabular->isPartOfMultiColumn(r1, c1)) {
5795                                 --c2;
5796                                 continue;
5797                         }
5798                         if (tabular.isPartOfMultiColumn(r2, c2)) {
5799                                 --c1;
5800                                 continue;
5801                         }
5802                         shared_ptr<InsetTableCell> inset(
5803                                 new InsetTableCell(*paste_tabular->cellInset(r1, c1)));
5804                         tabular.setCellInset(r2, c2, inset);
5805                         // FIXME?: why do we need to do this explicitly? (EL)
5806                         tabular.cellInset(r2, c2)->setBuffer(tabular.buffer());
5807
5808                         // FIXME: change tracking (MG)
5809                         inset->setChange(Change(buffer().params().trackChanges ?
5810                                                 Change::INSERTED : Change::UNCHANGED));
5811                         cur.pos() = 0;
5812                 }
5813         }
5814         return true;
5815 }
5816
5817
5818 void InsetTabular::cutSelection(Cursor & cur)
5819 {
5820         if (!cur.selection())
5821                 return;
5822
5823         row_type rs, re;
5824         col_type cs, ce;
5825         getSelection(cur, rs, re, cs, ce);
5826         for (row_type r = rs; r <= re; ++r) {
5827                 for (col_type c = cs; c <= ce; ++c) {
5828                         shared_ptr<InsetTableCell> t
5829                                 = cell(tabular.cellIndex(r, c));
5830                         if (buffer().params().trackChanges)
5831                                 // FIXME: Change tracking (MG)
5832                                 t->setChange(Change(Change::DELETED));
5833                         else
5834                                 t->clear();
5835                 }
5836         }
5837
5838         // cursor position might be invalid now
5839         if (cur.pit() > cur.lastpit())
5840                 cur.pit() = cur.lastpit();
5841         if (cur.pos() > cur.lastpos())
5842                 cur.pos() = cur.lastpos();
5843         cur.clearSelection();
5844 }
5845
5846
5847 bool InsetTabular::isRightToLeft(Cursor & cur) const
5848 {
5849         LASSERT(cur.depth() > 1, /**/);
5850         Paragraph const & parentpar = cur[cur.depth() - 2].paragraph();
5851         pos_type const parentpos = cur[cur.depth() - 2].pos();
5852         return parentpar.getFontSettings(buffer().params(),
5853                                          parentpos).language()->rightToLeft();
5854 }
5855
5856
5857 docstring InsetTabular::asString(idx_type stidx, idx_type enidx, 
5858                                  bool intoInsets)
5859 {
5860         LASSERT(stidx <= enidx, return docstring());
5861         docstring retval;
5862         col_type const col1 = tabular.cellColumn(stidx);
5863         col_type const col2 = tabular.cellColumn(enidx);
5864         row_type const row1 = tabular.cellRow(stidx);
5865         row_type const row2 = tabular.cellRow(enidx);
5866         bool first = true;
5867         for (col_type col = col1; col <= col2; col++)
5868                 for (row_type row = row1; row <= row2; row++) {
5869                         if (!first)
5870                                 retval += "\n";
5871                         else
5872                                 first = false;
5873                         retval += tabular.cellInset(row, col)->asString(intoInsets);
5874                 }
5875         return retval;
5876 }
5877
5878
5879 void InsetTabular::getSelection(Cursor & cur,
5880         row_type & rs, row_type & re, col_type & cs, col_type & ce) const
5881 {
5882         CursorSlice const & beg = cur.selBegin();
5883         CursorSlice const & end = cur.selEnd();
5884         cs = tabular.cellColumn(beg.idx());
5885         ce = tabular.cellColumn(end.idx());
5886         if (cs > ce)
5887                 swap(cs, ce);
5888
5889         rs = tabular.cellRow(beg.idx());
5890         re = tabular.cellRow(end.idx());
5891         if (rs > re)
5892                 swap(rs, re);
5893 }
5894
5895
5896 Text * InsetTabular::getText(int idx) const
5897 {
5898         return size_t(idx) < nargs() ? cell(idx)->getText(0) : 0;
5899 }
5900
5901
5902 void InsetTabular::setChange(Change const & change)
5903 {
5904         for (idx_type idx = 0; idx < nargs(); ++idx)
5905                 cell(idx)->setChange(change);
5906 }
5907
5908
5909 void InsetTabular::acceptChanges()
5910 {
5911         for (idx_type idx = 0; idx < nargs(); ++idx)
5912                 cell(idx)->acceptChanges();
5913 }
5914
5915
5916 void InsetTabular::rejectChanges()
5917 {
5918         for (idx_type idx = 0; idx < nargs(); ++idx)
5919                 cell(idx)->rejectChanges();
5920 }
5921
5922
5923 bool InsetTabular::allowParagraphCustomization(idx_type cell) const
5924 {
5925         return tabular.getPWidth(cell).zero();
5926 }
5927
5928
5929 bool InsetTabular::forcePlainLayout(idx_type cell) const
5930 {
5931         return !tabular.getPWidth(cell).zero();
5932 }
5933
5934
5935 bool InsetTabular::insertPlaintextString(BufferView & bv, docstring const & buf,
5936                                      bool usePaste)
5937 {
5938         if (buf.length() <= 0)
5939                 return true;
5940
5941         col_type cols = 1;
5942         row_type rows = 1;
5943         col_type maxCols = 1;
5944         size_t const len = buf.length();
5945         size_t p = 0;
5946
5947         while (p < len &&
5948                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos) {
5949                 switch (buf[p]) {
5950                 case '\t':
5951                         ++cols;
5952                         break;
5953                 case '\n':
5954                         if (p + 1 < len)
5955                                 ++rows;
5956                         maxCols = max(cols, maxCols);
5957                         cols = 1;
5958                         break;
5959                 }
5960                 ++p;
5961         }
5962         maxCols = max(cols, maxCols);
5963         Tabular * loctab;
5964         idx_type cell = 0;
5965         col_type ocol = 0;
5966         row_type row = 0;
5967         if (usePaste) {
5968                 paste_tabular.reset(new Tabular(buffer_, rows, maxCols));
5969                 loctab = paste_tabular.get();
5970                 cols = 0;
5971                 dirtyTabularStack(true);
5972         } else {
5973                 loctab = &tabular;
5974                 cell = bv.cursor().idx();
5975                 ocol = tabular.cellColumn(cell);
5976                 row = tabular.cellRow(cell);
5977         }
5978
5979         size_t op = 0;
5980         idx_type const cells = loctab->numberofcells;
5981         p = 0;
5982         cols = ocol;
5983         rows = loctab->nrows();
5984         col_type const columns = loctab->ncols();
5985
5986         while (cell < cells && p < len && row < rows &&
5987                (p = buf.find_first_of(from_ascii("\t\n"), p)) != docstring::npos)
5988         {
5989                 if (p >= len)
5990                         break;
5991                 switch (buf[p]) {
5992                 case '\t':
5993                         // we can only set this if we are not too far right
5994                         if (cols < columns) {
5995                                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
5996                                 Font const font = bv.textMetrics(&inset->text()).
5997                                         displayFont(0, 0);
5998                                 inset->setText(buf.substr(op, p - op), font,
5999                                                buffer().params().trackChanges);
6000                                 ++cols;
6001                                 ++cell;
6002                         }
6003                         break;
6004                 case '\n':
6005                         // we can only set this if we are not too far right
6006                         if (cols < columns) {
6007                                 shared_ptr<InsetTableCell> inset = tabular.cellInset(cell);
6008                                 Font const font = bv.textMetrics(&inset->text()).
6009                                         displayFont(0, 0);
6010                                 inset->setText(buf.substr(op, p - op), font,
6011                                                buffer().params().trackChanges);
6012                         }
6013                         cols = ocol;
6014                         ++row;
6015                         if (row < rows)
6016                                 cell = loctab->cellIndex(row, cols);
6017                         break;
6018                 }
6019                 ++p;
6020                 op = p;
6021         }
6022         // check for the last cell if there is no trailing '\n'
6023         if (cell < cells && op < len) {
6024                 shared_ptr<InsetTableCell> inset = loctab->cellInset(cell);
6025                 Font const font = bv.textMetrics(&inset->text()).displayFont(0, 0);
6026                 inset->setText(buf.substr(op, len - op), font,
6027                         buffer().params().trackChanges);
6028         }
6029         return true;
6030 }
6031
6032
6033 void InsetTabular::addPreview(DocIterator const & inset_pos,
6034         PreviewLoader & loader) const
6035 {
6036         DocIterator cell_pos = inset_pos;
6037
6038         cell_pos.push_back(CursorSlice(*const_cast<InsetTabular *>(this)));
6039         for (row_type r = 0; r < tabular.nrows(); ++r) {
6040                 for (col_type c = 0; c < tabular.ncols(); ++c) {
6041                         cell_pos.top().idx() = tabular.cellIndex(r, c);
6042                         tabular.cellInset(r, c)->addPreview(cell_pos, loader);
6043                 }
6044         }
6045 }
6046
6047
6048 bool InsetTabular::completionSupported(Cursor const & cur) const
6049 {
6050         Cursor const & bvCur = cur.bv().cursor();
6051         if (&bvCur.inset() != this)
6052                 return false;
6053         return cur.text()->completionSupported(cur);
6054 }
6055
6056
6057 bool InsetTabular::inlineCompletionSupported(Cursor const & cur) const
6058 {
6059         return completionSupported(cur);
6060 }
6061
6062
6063 bool InsetTabular::automaticInlineCompletion() const
6064 {
6065         return lyxrc.completion_inline_text;
6066 }
6067
6068
6069 bool InsetTabular::automaticPopupCompletion() const
6070 {
6071         return lyxrc.completion_popup_text;
6072 }
6073
6074
6075 bool InsetTabular::showCompletionCursor() const
6076 {
6077         return lyxrc.completion_cursor_text;
6078 }
6079
6080
6081 CompletionList const * InsetTabular::createCompletionList(Cursor const & cur) const
6082 {
6083         return completionSupported(cur) ? cur.text()->createCompletionList(cur) : 0;
6084 }
6085
6086
6087 docstring InsetTabular::completionPrefix(Cursor const & cur) const
6088 {
6089         if (!completionSupported(cur))
6090                 return docstring();
6091         return cur.text()->completionPrefix(cur);
6092 }
6093
6094
6095 bool InsetTabular::insertCompletion(Cursor & cur, docstring const & s, bool finished)
6096 {
6097         if (!completionSupported(cur))
6098                 return false;
6099
6100         return cur.text()->insertCompletion(cur, s, finished);
6101 }
6102
6103
6104 void InsetTabular::completionPosAndDim(Cursor const & cur, int & x, int & y, 
6105                                     Dimension & dim) const
6106 {
6107         TextMetrics const & tm = cur.bv().textMetrics(cur.text());
6108         tm.completionPosAndDim(cur, x, y, dim);
6109 }
6110
6111
6112 void InsetTabular::string2params(string const & in, InsetTabular & inset)
6113 {
6114         istringstream data(in);
6115         Lexer lex;
6116         lex.setStream(data);
6117
6118         if (in.empty())
6119                 return;
6120
6121         string token;
6122         lex >> token;
6123         if (!lex || token != "tabular") {
6124                 LYXERR0("Expected arg 1 to be \"tabular\" in " << in);
6125                 return;
6126         }
6127
6128         // This is part of the inset proper that is usually swallowed
6129         // by Buffer::readInset
6130         lex >> token;
6131         if (!lex || token != "Tabular") {
6132                 LYXERR0("Expected arg 2 to be \"Tabular\" in " << in);
6133                 return;
6134         }
6135
6136         inset.read(lex);
6137 }
6138
6139
6140 string InsetTabular::params2string(InsetTabular const & inset)
6141 {
6142         ostringstream data;
6143         data << "tabular" << ' ';
6144         inset.write(data);
6145         data << "\\end_inset\n";
6146         return data.str();
6147 }
6148
6149
6150 } // namespace lyx